ngram
listlengths
0
82k
[ "# Augment the input data by adding noise noise =", "response_dict[syllogism.encoded_task] = syllogism.encode_response( task_series['response'].split(';')) task_sequence.append(syllogism.encoded_task) # Convert the task-response mapping", "accs.append(subj_hits) return accs # Training loop train_accs = [] test_accs", "_, task_series in subj_df.sort_values('sequence').iterrows(): item = ccobra.Item( task_series['id'], task_series['domain'], task_series['task'],", "in subj_df.sort_values('sequence').iterrows(): item = ccobra.Item( task_series['id'], task_series['domain'], task_series['task'], task_series['response_type'], task_series['choices'],", "acc : {:.4f} ({:.4f})'.format(np.mean(test_acc), np.std(test_acc))) # Store the accuracy results", "= time.time() # Permute the training data rnd_idxs = np.random.permutation(np.arange(len(train_data)))", "# Write the accuracies to disk print('Writing the results to", "_, subj_df in df.groupby('id'): # Obtain the task-response mapping for", "batch_size = 16 net = autoencoder.DenoisingAutoencoder() criterion = nn.MSELoss() optimizer", "optim.Adam(net.parameters()) def csv_to_tensor(datafile): profiles = [] response_dicts = [] task_sequences", "training data rnd_idxs = np.random.permutation(np.arange(len(train_data))) train_data = train_data[rnd_idxs] train_resp_dicts =", "optimizer.step() batch_losses.append(loss.item()) losses.append(np.mean(batch_losses)) # Compute the accuracies for evaluation net.eval()", "[] for batch_idx in range(len(train_data) // batch_size): # Obtain the", "resp_dicts, seqs): accs = [] for subj_idx in range(len(data)): subj_resp_dict", "[] for subj_idx in range(len(data)): subj_resp_dict = resp_dicts[subj_idx] subj_seq =", "import torch.optim as optim import torch.nn as nn import ccobra", "data rnd_idxs = np.random.permutation(np.arange(len(train_data))) train_data = train_data[rnd_idxs] train_resp_dicts = train_resp_dicts[rnd_idxs]", "+ batch_size batch_data = train_data[start:end] input_data = batch_data # Augment", "task_sequence = [] for _, task_series in subj_df.sort_values('sequence').iterrows(): item =", "noise noise = torch.bernoulli(torch.zeros_like(input_data) + 0.8) input_data = input_data *", "pandas as pd import numpy as np import torch import", "torch.bernoulli(torch.zeros_like(input_data) + 0.8) input_data = input_data * noise # Perform", "task_series in subj_df.sort_values('sequence').iterrows(): item = ccobra.Item( task_series['id'], task_series['domain'], task_series['task'], task_series['response_type'],", "training outputs = net(input_data) loss = criterion(outputs, batch_data) optimizer.zero_grad() loss.backward()", "subj_seq = seqs[subj_idx] profile_tensor = torch.zeros((576)).float() subj_hits = [] for", "= train_seqs[rnd_idxs] batch_losses = [] for batch_idx in range(len(train_data) //", "prediction_idx = net(profile_tensor)[start:end].argmax() prediction = ccobra.syllogistic.RESPONSES[prediction_idx] subj_hits.append(prediction == truth) #", "the batch data start = batch_idx * batch_size end =", "= net(input_data) loss = criterion(outputs, batch_data) optimizer.zero_grad() loss.backward() optimizer.step() batch_losses.append(loss.item())", "task in subj_seq: task_idx = ccobra.syllogistic.SYLLOGISMS.index(task) start = task_idx *", "= net(profile_tensor)[start:end].argmax() prediction = ccobra.syllogistic.RESPONSES[prediction_idx] subj_hits.append(prediction == truth) # Add", "= start + batch_size batch_data = train_data[start:end] input_data = batch_data", "Write the accuracies to disk print('Writing the results to disk...')", "tensors train_data, train_resp_dicts, train_seqs = csv_to_tensor(training_datafile) test_data, test_resp_dicts, test_seqs =", "optimizer = optim.Adam(net.parameters()) def csv_to_tensor(datafile): profiles = [] response_dicts =", "Evaluates the training performance of the autoencoder. \"\"\" import time", "the reasoner profile profile = [] for task in ccobra.syllogistic.SYLLOGISMS:", "torch.from_numpy(onehot.onehot_response(truth)) accs.append(subj_hits) return accs # Training loop train_accs = []", "'../../data/Ragni-train.csv' test_datafile = '../../data/Ragni-test.csv' n_epochs = 150 batch_size = 16", "for evaluation net.eval() # Compute the overall accuracy on the", "resp_dicts[subj_idx] subj_seq = seqs[subj_idx] profile_tensor = torch.zeros((576)).float() subj_hits = []", "reasoner profile profile = [] for task in ccobra.syllogistic.SYLLOGISMS: profile.append(onehot.onehot_response(response_dict[task]))", "noise # Perform the training outputs = net(input_data) loss =", "= ccobra.syllogistic.RESPONSES[prediction_idx] subj_hits.append(prediction == truth) # Add the true response", "= '../../data/Ragni-train.csv' test_datafile = '../../data/Ragni-test.csv' n_epochs = 150 batch_size =", "Perform the training outputs = net(input_data) loss = criterion(outputs, batch_data)", "accs = [] for subj_idx in range(len(data)): subj_resp_dict = resp_dicts[subj_idx]", "<filename>analysis/networks/autoencoder/train_eval.py \"\"\" Evaluates the training performance of the autoencoder. \"\"\"", "= [] for batch_idx in range(len(train_data) // batch_size): # Obtain", "batch_data = train_data[start:end] input_data = batch_data # Augment the input", "dataset train_acc = compute_accuracy(train_data, train_resp_dicts, train_seqs) test_acc = compute_accuracy(test_data, test_resp_dicts,", "the network for a prediction prediction_idx = net(profile_tensor)[start:end].argmax() prediction =", "profile.append(onehot.onehot_response(response_dict[task])) profiles.append(profile) response_dicts.append(response_dict) task_sequences.append(task_sequence) profile_tensor = torch.tensor(profiles).float().view(-1, 576) return profile_tensor,", "autoencoder. \"\"\" import time import pandas as pd import numpy", "numpy as np import torch import torch.optim as optim import", "= [] df = pd.read_csv(datafile) for _, subj_df in df.groupby('id'):", ": {:.4f} ({:.4f})'.format(np.mean(test_acc), np.std(test_acc))) # Store the accuracy results train_accs.append(train_acc)", "criterion = nn.MSELoss() optimizer = optim.Adam(net.parameters()) def csv_to_tensor(datafile): profiles =", "training performance of the autoencoder. \"\"\" import time import pandas", "mapping to the reasoner profile profile = [] for task", "training and test tensors train_data, train_resp_dicts, train_seqs = csv_to_tensor(training_datafile) test_data,", "csv_to_tensor(test_datafile) def compute_accuracy(data, resp_dicts, seqs): accs = [] for subj_idx", "subj_resp_dict = resp_dicts[subj_idx] subj_seq = seqs[subj_idx] profile_tensor = torch.zeros((576)).float() subj_hits", "[] losses = [] for epoch in range(n_epochs): start_time =", "np.array(response_dicts), np.array(task_sequences) # Construct the training and test tensors train_data,", "response to the profile profile_tensor[start:end] = torch.from_numpy(onehot.onehot_response(truth)) accs.append(subj_hits) return accs", "torch.optim as optim import torch.nn as nn import ccobra import", "task_idx = ccobra.syllogistic.SYLLOGISMS.index(task) start = task_idx * 9 end =", "the task-response mapping to the reasoner profile profile = []", "ccobra.syllogistic.SYLLOGISMS.index(task) start = task_idx * 9 end = start +", "task_sequences.append(task_sequence) profile_tensor = torch.tensor(profiles).float().view(-1, 576) return profile_tensor, np.array(response_dicts), np.array(task_sequences) #", "def csv_to_tensor(datafile): profiles = [] response_dicts = [] task_sequences =", "adding noise noise = torch.bernoulli(torch.zeros_like(input_data) + 0.8) input_data = input_data", "- start_time, np.mean(batch_losses))) print(' train acc: {:.4f} ({:.4f})'.format(np.mean(train_acc), np.std(train_acc))) print('", "the results to disk...') np.save('train_accs.npy', np.array(train_accs)) np.save('test_accs.npy', np.array(test_accs)) np.save('train_losses.npy', np.array(losses))", "= ccobra.syllogistic.SYLLOGISMS.index(task) start = task_idx * 9 end = start", "= torch.from_numpy(onehot.onehot_response(truth)) accs.append(subj_hits) return accs # Training loop train_accs =", "[] df = pd.read_csv(datafile) for _, subj_df in df.groupby('id'): #", "task_series['task'], task_series['response_type'], task_series['choices'], task_series['sequence']) syllogism = ccobra.syllogistic.Syllogism(item) response_dict[syllogism.encoded_task] = syllogism.encode_response(", "pd import numpy as np import torch import torch.optim as", "np import torch import torch.optim as optim import torch.nn as", "= train_data[rnd_idxs] train_resp_dicts = train_resp_dicts[rnd_idxs] train_seqs = train_seqs[rnd_idxs] batch_losses =", "test_accs.append(test_acc) # Write the accuracies to disk print('Writing the results", "= ccobra.Item( task_series['id'], task_series['domain'], task_series['task'], task_series['response_type'], task_series['choices'], task_series['sequence']) syllogism =", "batch_losses.append(loss.item()) losses.append(np.mean(batch_losses)) # Compute the accuracies for evaluation net.eval() #", "accuracies to disk print('Writing the results to disk...') np.save('train_accs.npy', np.array(train_accs))", "loss = criterion(outputs, batch_data) optimizer.zero_grad() loss.backward() optimizer.step() batch_losses.append(loss.item()) losses.append(np.mean(batch_losses)) #", "# Permute the training data rnd_idxs = np.random.permutation(np.arange(len(train_data))) train_data =", "= [] for subj_idx in range(len(data)): subj_resp_dict = resp_dicts[subj_idx] subj_seq", "train_seqs) test_acc = compute_accuracy(test_data, test_resp_dicts, test_seqs) # Diagnostig output print('Epoch", "train_seqs = csv_to_tensor(training_datafile) test_data, test_resp_dicts, test_seqs = csv_to_tensor(test_datafile) def compute_accuracy(data,", "input_data = batch_data # Augment the input data by adding", "for subj_idx in range(len(data)): subj_resp_dict = resp_dicts[subj_idx] subj_seq = seqs[subj_idx]", "settings training_datafile = '../../data/Ragni-train.csv' test_datafile = '../../data/Ragni-test.csv' n_epochs = 150", "performance of the autoencoder. \"\"\" import time import pandas as", "{} task_sequence = [] for _, task_series in subj_df.sort_values('sequence').iterrows(): item", "train_resp_dicts[rnd_idxs] train_seqs = train_seqs[rnd_idxs] batch_losses = [] for batch_idx in", "batch_size end = start + batch_size batch_data = train_data[start:end] input_data", "batch_losses = [] for batch_idx in range(len(train_data) // batch_size): #", "0.8) input_data = input_data * noise # Perform the training", "Permute the training data rnd_idxs = np.random.permutation(np.arange(len(train_data))) train_data = train_data[rnd_idxs]", "Compute the overall accuracy on the training dataset train_acc =", "in subj_seq: task_idx = ccobra.syllogistic.SYLLOGISMS.index(task) start = task_idx * 9", "train_accs = [] test_accs = [] losses = [] for", "all syllogisms response_dict = {} task_sequence = [] for _,", "import ccobra import onehot import autoencoder # General settings training_datafile", "subj_df in df.groupby('id'): # Obtain the task-response mapping for all", "= torch.bernoulli(torch.zeros_like(input_data) + 0.8) input_data = input_data * noise #", "profile profile = [] for task in ccobra.syllogistic.SYLLOGISMS: profile.append(onehot.onehot_response(response_dict[task])) profiles.append(profile)", "[] response_dicts = [] task_sequences = [] df = pd.read_csv(datafile)", "({:.2f}s): {}'.format( epoch + 1, n_epochs, time.time() - start_time, np.mean(batch_losses)))", "optim import torch.nn as nn import ccobra import onehot import", "response_dict = {} task_sequence = [] for _, task_series in", "true response to the profile profile_tensor[start:end] = torch.from_numpy(onehot.onehot_response(truth)) accs.append(subj_hits) return", "test_seqs) # Diagnostig output print('Epoch {}/{} ({:.2f}s): {}'.format( epoch +", "response_dicts.append(response_dict) task_sequences.append(task_sequence) profile_tensor = torch.tensor(profiles).float().view(-1, 576) return profile_tensor, np.array(response_dicts), np.array(task_sequences)", "# Store the accuracy results train_accs.append(train_acc) test_accs.append(test_acc) # Write the", "the accuracies for evaluation net.eval() # Compute the overall accuracy", "item = ccobra.Item( task_series['id'], task_series['domain'], task_series['task'], task_series['response_type'], task_series['choices'], task_series['sequence']) syllogism", "return accs # Training loop train_accs = [] test_accs =", "print('Writing the results to disk...') np.save('train_accs.npy', np.array(train_accs)) np.save('test_accs.npy', np.array(test_accs)) np.save('train_losses.npy',", "= batch_idx * batch_size end = start + batch_size batch_data", "autoencoder.DenoisingAutoencoder() criterion = nn.MSELoss() optimizer = optim.Adam(net.parameters()) def csv_to_tensor(datafile): profiles", "subj_df.sort_values('sequence').iterrows(): item = ccobra.Item( task_series['id'], task_series['domain'], task_series['task'], task_series['response_type'], task_series['choices'], task_series['sequence'])", "subj_seq: task_idx = ccobra.syllogistic.SYLLOGISMS.index(task) start = task_idx * 9 end", "= train_resp_dicts[rnd_idxs] train_seqs = train_seqs[rnd_idxs] batch_losses = [] for batch_idx", "= compute_accuracy(train_data, train_resp_dicts, train_seqs) test_acc = compute_accuracy(test_data, test_resp_dicts, test_seqs) #", "in ccobra.syllogistic.SYLLOGISMS: profile.append(onehot.onehot_response(response_dict[task])) profiles.append(profile) response_dicts.append(response_dict) task_sequences.append(task_sequence) profile_tensor = torch.tensor(profiles).float().view(-1, 576)", "input_data = input_data * noise # Perform the training outputs", "= ccobra.syllogistic.Syllogism(item) response_dict[syllogism.encoded_task] = syllogism.encode_response( task_series['response'].split(';')) task_sequence.append(syllogism.encoded_task) # Convert the", "to the profile profile_tensor[start:end] = torch.from_numpy(onehot.onehot_response(truth)) accs.append(subj_hits) return accs #", "= batch_data # Augment the input data by adding noise", "task_sequence.append(syllogism.encoded_task) # Convert the task-response mapping to the reasoner profile", "disk print('Writing the results to disk...') np.save('train_accs.npy', np.array(train_accs)) np.save('test_accs.npy', np.array(test_accs))", "subj_hits = [] for task in subj_seq: task_idx = ccobra.syllogistic.SYLLOGISMS.index(task)", "torch.zeros((576)).float() subj_hits = [] for task in subj_seq: task_idx =", "epoch in range(n_epochs): start_time = time.time() # Permute the training", "to disk print('Writing the results to disk...') np.save('train_accs.npy', np.array(train_accs)) np.save('test_accs.npy',", "print('Epoch {}/{} ({:.2f}s): {}'.format( epoch + 1, n_epochs, time.time() -", "acc: {:.4f} ({:.4f})'.format(np.mean(train_acc), np.std(train_acc))) print(' test acc : {:.4f} ({:.4f})'.format(np.mean(test_acc),", "[] task_sequences = [] df = pd.read_csv(datafile) for _, subj_df", "Add the true response to the profile profile_tensor[start:end] = torch.from_numpy(onehot.onehot_response(truth))", "+ 9 truth = subj_resp_dict[task] # Query the network for", "[] test_accs = [] losses = [] for epoch in", "overall accuracy on the training dataset train_acc = compute_accuracy(train_data, train_resp_dicts,", "return profile_tensor, np.array(response_dicts), np.array(task_sequences) # Construct the training and test", "train_resp_dicts, train_seqs) test_acc = compute_accuracy(test_data, test_resp_dicts, test_seqs) # Diagnostig output", "profile_tensor = torch.zeros((576)).float() subj_hits = [] for task in subj_seq:", "= train_data[start:end] input_data = batch_data # Augment the input data", "time import pandas as pd import numpy as np import", "test_seqs = csv_to_tensor(test_datafile) def compute_accuracy(data, resp_dicts, seqs): accs = []", "import torch import torch.optim as optim import torch.nn as nn", "+ 0.8) input_data = input_data * noise # Perform the", "batch data start = batch_idx * batch_size end = start", "Compute the accuracies for evaluation net.eval() # Compute the overall", "the true response to the profile profile_tensor[start:end] = torch.from_numpy(onehot.onehot_response(truth)) accs.append(subj_hits)", "input data by adding noise noise = torch.bernoulli(torch.zeros_like(input_data) + 0.8)", "batch_data # Augment the input data by adding noise noise", "noise = torch.bernoulli(torch.zeros_like(input_data) + 0.8) input_data = input_data * noise", "input_data * noise # Perform the training outputs = net(input_data)", "the training dataset train_acc = compute_accuracy(train_data, train_resp_dicts, train_seqs) test_acc =", "= [] response_dicts = [] task_sequences = [] df =", "# Diagnostig output print('Epoch {}/{} ({:.2f}s): {}'.format( epoch + 1,", "ccobra.syllogistic.RESPONSES[prediction_idx] subj_hits.append(prediction == truth) # Add the true response to", "data start = batch_idx * batch_size end = start +", "test_acc = compute_accuracy(test_data, test_resp_dicts, test_seqs) # Diagnostig output print('Epoch {}/{}", "General settings training_datafile = '../../data/Ragni-train.csv' test_datafile = '../../data/Ragni-test.csv' n_epochs =", "in range(n_epochs): start_time = time.time() # Permute the training data", "net.eval() # Compute the overall accuracy on the training dataset", "576) return profile_tensor, np.array(response_dicts), np.array(task_sequences) # Construct the training and", "train acc: {:.4f} ({:.4f})'.format(np.mean(train_acc), np.std(train_acc))) print(' test acc : {:.4f}", "Training loop train_accs = [] test_accs = [] losses =", "task-response mapping to the reasoner profile profile = [] for", "import onehot import autoencoder # General settings training_datafile = '../../data/Ragni-train.csv'", "on the training dataset train_acc = compute_accuracy(train_data, train_resp_dicts, train_seqs) test_acc", "task_series['response'].split(';')) task_sequence.append(syllogism.encoded_task) # Convert the task-response mapping to the reasoner", "batch_data) optimizer.zero_grad() loss.backward() optimizer.step() batch_losses.append(loss.item()) losses.append(np.mean(batch_losses)) # Compute the accuracies", "outputs = net(input_data) loss = criterion(outputs, batch_data) optimizer.zero_grad() loss.backward() optimizer.step()", "ccobra.syllogistic.SYLLOGISMS: profile.append(onehot.onehot_response(response_dict[task])) profiles.append(profile) response_dicts.append(response_dict) task_sequences.append(task_sequence) profile_tensor = torch.tensor(profiles).float().view(-1, 576) return", "torch.nn as nn import ccobra import onehot import autoencoder #", "\"\"\" Evaluates the training performance of the autoencoder. \"\"\" import", "network for a prediction prediction_idx = net(profile_tensor)[start:end].argmax() prediction = ccobra.syllogistic.RESPONSES[prediction_idx]", "csv_to_tensor(datafile): profiles = [] response_dicts = [] task_sequences = []", "syllogisms response_dict = {} task_sequence = [] for _, task_series", "batch_idx * batch_size end = start + batch_size batch_data =", "autoencoder # General settings training_datafile = '../../data/Ragni-train.csv' test_datafile = '../../data/Ragni-test.csv'", "1, n_epochs, time.time() - start_time, np.mean(batch_losses))) print(' train acc: {:.4f}", "losses.append(np.mean(batch_losses)) # Compute the accuracies for evaluation net.eval() # Compute", "profiles.append(profile) response_dicts.append(response_dict) task_sequences.append(task_sequence) profile_tensor = torch.tensor(profiles).float().view(-1, 576) return profile_tensor, np.array(response_dicts),", "# Compute the overall accuracy on the training dataset train_acc", "time.time() - start_time, np.mean(batch_losses))) print(' train acc: {:.4f} ({:.4f})'.format(np.mean(train_acc), np.std(train_acc)))", "= csv_to_tensor(training_datafile) test_data, test_resp_dicts, test_seqs = csv_to_tensor(test_datafile) def compute_accuracy(data, resp_dicts,", "9 truth = subj_resp_dict[task] # Query the network for a", "= compute_accuracy(test_data, test_resp_dicts, test_seqs) # Diagnostig output print('Epoch {}/{} ({:.2f}s):", "task_series['id'], task_series['domain'], task_series['task'], task_series['response_type'], task_series['choices'], task_series['sequence']) syllogism = ccobra.syllogistic.Syllogism(item) response_dict[syllogism.encoded_task]", "the task-response mapping for all syllogisms response_dict = {} task_sequence", "Convert the task-response mapping to the reasoner profile profile =", "the autoencoder. \"\"\" import time import pandas as pd import", "truth = subj_resp_dict[task] # Query the network for a prediction", "* batch_size end = start + batch_size batch_data = train_data[start:end]", "{:.4f} ({:.4f})'.format(np.mean(train_acc), np.std(train_acc))) print(' test acc : {:.4f} ({:.4f})'.format(np.mean(test_acc), np.std(test_acc)))", "batch_idx in range(len(train_data) // batch_size): # Obtain the batch data", "= autoencoder.DenoisingAutoencoder() criterion = nn.MSELoss() optimizer = optim.Adam(net.parameters()) def csv_to_tensor(datafile):", "response_dicts = [] task_sequences = [] df = pd.read_csv(datafile) for", "[] for _, task_series in subj_df.sort_values('sequence').iterrows(): item = ccobra.Item( task_series['id'],", "accs # Training loop train_accs = [] test_accs = []", "in range(len(data)): subj_resp_dict = resp_dicts[subj_idx] subj_seq = seqs[subj_idx] profile_tensor =", "= torch.tensor(profiles).float().view(-1, 576) return profile_tensor, np.array(response_dicts), np.array(task_sequences) # Construct the", "test_resp_dicts, test_seqs) # Diagnostig output print('Epoch {}/{} ({:.2f}s): {}'.format( epoch", "test_data, test_resp_dicts, test_seqs = csv_to_tensor(test_datafile) def compute_accuracy(data, resp_dicts, seqs): accs", "prediction prediction_idx = net(profile_tensor)[start:end].argmax() prediction = ccobra.syllogistic.RESPONSES[prediction_idx] subj_hits.append(prediction == truth)", "pd.read_csv(datafile) for _, subj_df in df.groupby('id'): # Obtain the task-response", "= nn.MSELoss() optimizer = optim.Adam(net.parameters()) def csv_to_tensor(datafile): profiles = []", "# Add the true response to the profile profile_tensor[start:end] =", "= [] task_sequences = [] df = pd.read_csv(datafile) for _,", "task_series['sequence']) syllogism = ccobra.syllogistic.Syllogism(item) response_dict[syllogism.encoded_task] = syllogism.encode_response( task_series['response'].split(';')) task_sequence.append(syllogism.encoded_task) #", "batch_size batch_data = train_data[start:end] input_data = batch_data # Augment the", "net(profile_tensor)[start:end].argmax() prediction = ccobra.syllogistic.RESPONSES[prediction_idx] subj_hits.append(prediction == truth) # Add the", "subj_idx in range(len(data)): subj_resp_dict = resp_dicts[subj_idx] subj_seq = seqs[subj_idx] profile_tensor", "as nn import ccobra import onehot import autoencoder # General", "for epoch in range(n_epochs): start_time = time.time() # Permute the", "= criterion(outputs, batch_data) optimizer.zero_grad() loss.backward() optimizer.step() batch_losses.append(loss.item()) losses.append(np.mean(batch_losses)) # Compute", "({:.4f})'.format(np.mean(test_acc), np.std(test_acc))) # Store the accuracy results train_accs.append(train_acc) test_accs.append(test_acc) #", "= syllogism.encode_response( task_series['response'].split(';')) task_sequence.append(syllogism.encoded_task) # Convert the task-response mapping to", "by adding noise noise = torch.bernoulli(torch.zeros_like(input_data) + 0.8) input_data =", "== truth) # Add the true response to the profile", "Diagnostig output print('Epoch {}/{} ({:.2f}s): {}'.format( epoch + 1, n_epochs,", "train_data[rnd_idxs] train_resp_dicts = train_resp_dicts[rnd_idxs] train_seqs = train_seqs[rnd_idxs] batch_losses = []", "test acc : {:.4f} ({:.4f})'.format(np.mean(test_acc), np.std(test_acc))) # Store the accuracy", "as optim import torch.nn as nn import ccobra import onehot", "for a prediction prediction_idx = net(profile_tensor)[start:end].argmax() prediction = ccobra.syllogistic.RESPONSES[prediction_idx] subj_hits.append(prediction", "np.array(task_sequences) # Construct the training and test tensors train_data, train_resp_dicts,", "np.std(test_acc))) # Store the accuracy results train_accs.append(train_acc) test_accs.append(test_acc) # Write", "nn.MSELoss() optimizer = optim.Adam(net.parameters()) def csv_to_tensor(datafile): profiles = [] response_dicts", "Store the accuracy results train_accs.append(train_acc) test_accs.append(test_acc) # Write the accuracies", "subj_resp_dict[task] # Query the network for a prediction prediction_idx =", "the training data rnd_idxs = np.random.permutation(np.arange(len(train_data))) train_data = train_data[rnd_idxs] train_resp_dicts", "= start + 9 truth = subj_resp_dict[task] # Query the", "profiles = [] response_dicts = [] task_sequences = [] df", "np.std(train_acc))) print(' test acc : {:.4f} ({:.4f})'.format(np.mean(test_acc), np.std(test_acc))) # Store", "test_resp_dicts, test_seqs = csv_to_tensor(test_datafile) def compute_accuracy(data, resp_dicts, seqs): accs =", "of the autoencoder. \"\"\" import time import pandas as pd", "subj_hits.append(prediction == truth) # Add the true response to the", "{}/{} ({:.2f}s): {}'.format( epoch + 1, n_epochs, time.time() - start_time,", "train_resp_dicts, train_seqs = csv_to_tensor(training_datafile) test_data, test_resp_dicts, test_seqs = csv_to_tensor(test_datafile) def", "time.time() # Permute the training data rnd_idxs = np.random.permutation(np.arange(len(train_data))) train_data", "train_seqs[rnd_idxs] batch_losses = [] for batch_idx in range(len(train_data) // batch_size):", "= [] losses = [] for epoch in range(n_epochs): start_time", "# Compute the accuracies for evaluation net.eval() # Compute the", "train_data = train_data[rnd_idxs] train_resp_dicts = train_resp_dicts[rnd_idxs] train_seqs = train_seqs[rnd_idxs] batch_losses", "the accuracy results train_accs.append(train_acc) test_accs.append(test_acc) # Write the accuracies to", "# Convert the task-response mapping to the reasoner profile profile", "compute_accuracy(test_data, test_resp_dicts, test_seqs) # Diagnostig output print('Epoch {}/{} ({:.2f}s): {}'.format(", "start_time, np.mean(batch_losses))) print(' train acc: {:.4f} ({:.4f})'.format(np.mean(train_acc), np.std(train_acc))) print(' test", "the training performance of the autoencoder. \"\"\" import time import", "({:.4f})'.format(np.mean(train_acc), np.std(train_acc))) print(' test acc : {:.4f} ({:.4f})'.format(np.mean(test_acc), np.std(test_acc))) #", "n_epochs = 150 batch_size = 16 net = autoencoder.DenoisingAutoencoder() criterion", "criterion(outputs, batch_data) optimizer.zero_grad() loss.backward() optimizer.step() batch_losses.append(loss.item()) losses.append(np.mean(batch_losses)) # Compute the", "range(len(train_data) // batch_size): # Obtain the batch data start =", "9 end = start + 9 truth = subj_resp_dict[task] #", "// batch_size): # Obtain the batch data start = batch_idx", "# General settings training_datafile = '../../data/Ragni-train.csv' test_datafile = '../../data/Ragni-test.csv' n_epochs", "def compute_accuracy(data, resp_dicts, seqs): accs = [] for subj_idx in", "train_resp_dicts = train_resp_dicts[rnd_idxs] train_seqs = train_seqs[rnd_idxs] batch_losses = [] for", "train_acc = compute_accuracy(train_data, train_resp_dicts, train_seqs) test_acc = compute_accuracy(test_data, test_resp_dicts, test_seqs)", "= '../../data/Ragni-test.csv' n_epochs = 150 batch_size = 16 net =", "150 batch_size = 16 net = autoencoder.DenoisingAutoencoder() criterion = nn.MSELoss()", "# Obtain the batch data start = batch_idx * batch_size", "compute_accuracy(train_data, train_resp_dicts, train_seqs) test_acc = compute_accuracy(test_data, test_resp_dicts, test_seqs) # Diagnostig", "import autoencoder # General settings training_datafile = '../../data/Ragni-train.csv' test_datafile =", "seqs): accs = [] for subj_idx in range(len(data)): subj_resp_dict =", "profile profile_tensor[start:end] = torch.from_numpy(onehot.onehot_response(truth)) accs.append(subj_hits) return accs # Training loop", "import numpy as np import torch import torch.optim as optim", "syllogism.encode_response( task_series['response'].split(';')) task_sequence.append(syllogism.encoded_task) # Convert the task-response mapping to the", "train_data, train_resp_dicts, train_seqs = csv_to_tensor(training_datafile) test_data, test_resp_dicts, test_seqs = csv_to_tensor(test_datafile)", "the training and test tensors train_data, train_resp_dicts, train_seqs = csv_to_tensor(training_datafile)", "in df.groupby('id'): # Obtain the task-response mapping for all syllogisms", "the training outputs = net(input_data) loss = criterion(outputs, batch_data) optimizer.zero_grad()", "the accuracies to disk print('Writing the results to disk...') np.save('train_accs.npy',", "= {} task_sequence = [] for _, task_series in subj_df.sort_values('sequence').iterrows():", "task_series['response_type'], task_series['choices'], task_series['sequence']) syllogism = ccobra.syllogistic.Syllogism(item) response_dict[syllogism.encoded_task] = syllogism.encode_response( task_series['response'].split(';'))", "as np import torch import torch.optim as optim import torch.nn", "profile_tensor, np.array(response_dicts), np.array(task_sequences) # Construct the training and test tensors", "start + 9 truth = subj_resp_dict[task] # Query the network", "# Perform the training outputs = net(input_data) loss = criterion(outputs,", "train_accs.append(train_acc) test_accs.append(test_acc) # Write the accuracies to disk print('Writing the", "test_accs = [] losses = [] for epoch in range(n_epochs):", "compute_accuracy(data, resp_dicts, seqs): accs = [] for subj_idx in range(len(data)):", "start = task_idx * 9 end = start + 9", "task in ccobra.syllogistic.SYLLOGISMS: profile.append(onehot.onehot_response(response_dict[task])) profiles.append(profile) response_dicts.append(response_dict) task_sequences.append(task_sequence) profile_tensor = torch.tensor(profiles).float().view(-1,", "a prediction prediction_idx = net(profile_tensor)[start:end].argmax() prediction = ccobra.syllogistic.RESPONSES[prediction_idx] subj_hits.append(prediction ==", "{:.4f} ({:.4f})'.format(np.mean(test_acc), np.std(test_acc))) # Store the accuracy results train_accs.append(train_acc) test_accs.append(test_acc)", "start_time = time.time() # Permute the training data rnd_idxs =", "task-response mapping for all syllogisms response_dict = {} task_sequence =", "batch_size): # Obtain the batch data start = batch_idx *", "Construct the training and test tensors train_data, train_resp_dicts, train_seqs =", "= [] for _, task_series in subj_df.sort_values('sequence').iterrows(): item = ccobra.Item(", "task_idx * 9 end = start + 9 truth =", "end = start + 9 truth = subj_resp_dict[task] # Query", "[] for task in ccobra.syllogistic.SYLLOGISMS: profile.append(onehot.onehot_response(response_dict[task])) profiles.append(profile) response_dicts.append(response_dict) task_sequences.append(task_sequence) profile_tensor", "= seqs[subj_idx] profile_tensor = torch.zeros((576)).float() subj_hits = [] for task", "accuracy on the training dataset train_acc = compute_accuracy(train_data, train_resp_dicts, train_seqs)", "torch import torch.optim as optim import torch.nn as nn import", "net(input_data) loss = criterion(outputs, batch_data) optimizer.zero_grad() loss.backward() optimizer.step() batch_losses.append(loss.item()) losses.append(np.mean(batch_losses))", "results train_accs.append(train_acc) test_accs.append(test_acc) # Write the accuracies to disk print('Writing", "for _, subj_df in df.groupby('id'): # Obtain the task-response mapping", "accuracies for evaluation net.eval() # Compute the overall accuracy on", "Augment the input data by adding noise noise = torch.bernoulli(torch.zeros_like(input_data)", "range(len(data)): subj_resp_dict = resp_dicts[subj_idx] subj_seq = seqs[subj_idx] profile_tensor = torch.zeros((576)).float()", "= task_idx * 9 end = start + 9 truth", "for task in subj_seq: task_idx = ccobra.syllogistic.SYLLOGISMS.index(task) start = task_idx", "df = pd.read_csv(datafile) for _, subj_df in df.groupby('id'): # Obtain", "np.random.permutation(np.arange(len(train_data))) train_data = train_data[rnd_idxs] train_resp_dicts = train_resp_dicts[rnd_idxs] train_seqs = train_seqs[rnd_idxs]", "= subj_resp_dict[task] # Query the network for a prediction prediction_idx", "# Query the network for a prediction prediction_idx = net(profile_tensor)[start:end].argmax()", "for all syllogisms response_dict = {} task_sequence = [] for", "= csv_to_tensor(test_datafile) def compute_accuracy(data, resp_dicts, seqs): accs = [] for", "accuracy results train_accs.append(train_acc) test_accs.append(test_acc) # Write the accuracies to disk", "ccobra.syllogistic.Syllogism(item) response_dict[syllogism.encoded_task] = syllogism.encode_response( task_series['response'].split(';')) task_sequence.append(syllogism.encoded_task) # Convert the task-response", "\"\"\" import time import pandas as pd import numpy as", "mapping for all syllogisms response_dict = {} task_sequence = []", "the input data by adding noise noise = torch.bernoulli(torch.zeros_like(input_data) +", "truth) # Add the true response to the profile profile_tensor[start:end]", "+ 1, n_epochs, time.time() - start_time, np.mean(batch_losses))) print(' train acc:", "prediction = ccobra.syllogistic.RESPONSES[prediction_idx] subj_hits.append(prediction == truth) # Add the true", "print(' train acc: {:.4f} ({:.4f})'.format(np.mean(train_acc), np.std(train_acc))) print(' test acc :", "task_sequences = [] df = pd.read_csv(datafile) for _, subj_df in", "end = start + batch_size batch_data = train_data[start:end] input_data =", "n_epochs, time.time() - start_time, np.mean(batch_losses))) print(' train acc: {:.4f} ({:.4f})'.format(np.mean(train_acc),", "# Construct the training and test tensors train_data, train_resp_dicts, train_seqs", "profile_tensor[start:end] = torch.from_numpy(onehot.onehot_response(truth)) accs.append(subj_hits) return accs # Training loop train_accs", "= 16 net = autoencoder.DenoisingAutoencoder() criterion = nn.MSELoss() optimizer =", "seqs[subj_idx] profile_tensor = torch.zeros((576)).float() subj_hits = [] for task in", "ccobra.Item( task_series['id'], task_series['domain'], task_series['task'], task_series['response_type'], task_series['choices'], task_series['sequence']) syllogism = ccobra.syllogistic.Syllogism(item)", "df.groupby('id'): # Obtain the task-response mapping for all syllogisms response_dict", "# Training loop train_accs = [] test_accs = [] losses", "evaluation net.eval() # Compute the overall accuracy on the training", "profile = [] for task in ccobra.syllogistic.SYLLOGISMS: profile.append(onehot.onehot_response(response_dict[task])) profiles.append(profile) response_dicts.append(response_dict)", "start + batch_size batch_data = train_data[start:end] input_data = batch_data #", "= 150 batch_size = 16 net = autoencoder.DenoisingAutoencoder() criterion =", "output print('Epoch {}/{} ({:.2f}s): {}'.format( epoch + 1, n_epochs, time.time()", "'../../data/Ragni-test.csv' n_epochs = 150 batch_size = 16 net = autoencoder.DenoisingAutoencoder()", "train_data[start:end] input_data = batch_data # Augment the input data by", "Obtain the batch data start = batch_idx * batch_size end", "start = batch_idx * batch_size end = start + batch_size", "for task in ccobra.syllogistic.SYLLOGISMS: profile.append(onehot.onehot_response(response_dict[task])) profiles.append(profile) response_dicts.append(response_dict) task_sequences.append(task_sequence) profile_tensor =", "training_datafile = '../../data/Ragni-train.csv' test_datafile = '../../data/Ragni-test.csv' n_epochs = 150 batch_size", "import time import pandas as pd import numpy as np", "in range(len(train_data) // batch_size): # Obtain the batch data start", "= [] for task in subj_seq: task_idx = ccobra.syllogistic.SYLLOGISMS.index(task) start", "= np.random.permutation(np.arange(len(train_data))) train_data = train_data[rnd_idxs] train_resp_dicts = train_resp_dicts[rnd_idxs] train_seqs =", "onehot import autoencoder # General settings training_datafile = '../../data/Ragni-train.csv' test_datafile", "[] for epoch in range(n_epochs): start_time = time.time() # Permute", "torch.tensor(profiles).float().view(-1, 576) return profile_tensor, np.array(response_dicts), np.array(task_sequences) # Construct the training", "loop train_accs = [] test_accs = [] losses = []", "16 net = autoencoder.DenoisingAutoencoder() criterion = nn.MSELoss() optimizer = optim.Adam(net.parameters())", "np.mean(batch_losses))) print(' train acc: {:.4f} ({:.4f})'.format(np.mean(train_acc), np.std(train_acc))) print(' test acc", "= resp_dicts[subj_idx] subj_seq = seqs[subj_idx] profile_tensor = torch.zeros((576)).float() subj_hits =", "training dataset train_acc = compute_accuracy(train_data, train_resp_dicts, train_seqs) test_acc = compute_accuracy(test_data,", "as pd import numpy as np import torch import torch.optim", "test_datafile = '../../data/Ragni-test.csv' n_epochs = 150 batch_size = 16 net", "task_series['choices'], task_series['sequence']) syllogism = ccobra.syllogistic.Syllogism(item) response_dict[syllogism.encoded_task] = syllogism.encode_response( task_series['response'].split(';')) task_sequence.append(syllogism.encoded_task)", "for _, task_series in subj_df.sort_values('sequence').iterrows(): item = ccobra.Item( task_series['id'], task_series['domain'],", "task_series['domain'], task_series['task'], task_series['response_type'], task_series['choices'], task_series['sequence']) syllogism = ccobra.syllogistic.Syllogism(item) response_dict[syllogism.encoded_task] =", "import torch.nn as nn import ccobra import onehot import autoencoder", "{}'.format( epoch + 1, n_epochs, time.time() - start_time, np.mean(batch_losses))) print('", "= torch.zeros((576)).float() subj_hits = [] for task in subj_seq: task_idx", "rnd_idxs = np.random.permutation(np.arange(len(train_data))) train_data = train_data[rnd_idxs] train_resp_dicts = train_resp_dicts[rnd_idxs] train_seqs", "ccobra import onehot import autoencoder # General settings training_datafile =", "test tensors train_data, train_resp_dicts, train_seqs = csv_to_tensor(training_datafile) test_data, test_resp_dicts, test_seqs", "nn import ccobra import onehot import autoencoder # General settings", "syllogism = ccobra.syllogistic.Syllogism(item) response_dict[syllogism.encoded_task] = syllogism.encode_response( task_series['response'].split(';')) task_sequence.append(syllogism.encoded_task) # Convert", "epoch + 1, n_epochs, time.time() - start_time, np.mean(batch_losses))) print(' train", "and test tensors train_data, train_resp_dicts, train_seqs = csv_to_tensor(training_datafile) test_data, test_resp_dicts,", "= pd.read_csv(datafile) for _, subj_df in df.groupby('id'): # Obtain the", "csv_to_tensor(training_datafile) test_data, test_resp_dicts, test_seqs = csv_to_tensor(test_datafile) def compute_accuracy(data, resp_dicts, seqs):", "profile_tensor = torch.tensor(profiles).float().view(-1, 576) return profile_tensor, np.array(response_dicts), np.array(task_sequences) # Construct", "losses = [] for epoch in range(n_epochs): start_time = time.time()", "the profile profile_tensor[start:end] = torch.from_numpy(onehot.onehot_response(truth)) accs.append(subj_hits) return accs # Training", "Query the network for a prediction prediction_idx = net(profile_tensor)[start:end].argmax() prediction", "loss.backward() optimizer.step() batch_losses.append(loss.item()) losses.append(np.mean(batch_losses)) # Compute the accuracies for evaluation", "range(n_epochs): start_time = time.time() # Permute the training data rnd_idxs", "Obtain the task-response mapping for all syllogisms response_dict = {}", "data by adding noise noise = torch.bernoulli(torch.zeros_like(input_data) + 0.8) input_data", "print(' test acc : {:.4f} ({:.4f})'.format(np.mean(test_acc), np.std(test_acc))) # Store the", "optimizer.zero_grad() loss.backward() optimizer.step() batch_losses.append(loss.item()) losses.append(np.mean(batch_losses)) # Compute the accuracies for", "= [] test_accs = [] losses = [] for epoch", "the overall accuracy on the training dataset train_acc = compute_accuracy(train_data,", "= input_data * noise # Perform the training outputs =", "= [] for epoch in range(n_epochs): start_time = time.time() #", "= [] for task in ccobra.syllogistic.SYLLOGISMS: profile.append(onehot.onehot_response(response_dict[task])) profiles.append(profile) response_dicts.append(response_dict) task_sequences.append(task_sequence)", "for batch_idx in range(len(train_data) // batch_size): # Obtain the batch", "net = autoencoder.DenoisingAutoencoder() criterion = nn.MSELoss() optimizer = optim.Adam(net.parameters()) def", "[] for task in subj_seq: task_idx = ccobra.syllogistic.SYLLOGISMS.index(task) start =", "train_seqs = train_seqs[rnd_idxs] batch_losses = [] for batch_idx in range(len(train_data)", "* 9 end = start + 9 truth = subj_resp_dict[task]", "* noise # Perform the training outputs = net(input_data) loss", "to the reasoner profile profile = [] for task in", "= optim.Adam(net.parameters()) def csv_to_tensor(datafile): profiles = [] response_dicts = []", "import pandas as pd import numpy as np import torch", "# Obtain the task-response mapping for all syllogisms response_dict =" ]
[ "time import os import logging from libs.uiauto.uiautomator import AutomatorDevice from", "under the License. \"\"\" __author__ = 'minhuaxu <EMAIL>' import time", "logging from libs.uiauto.uiautomator import AutomatorDevice from wpyscripts.common.adb_process import AdbTool logger=logging.getLogger(\"wetest\")", "Unless required by applicable law or agreed to in writing,", "by applicable law or agreed to in writing, software distributed", "http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in", "logger.debug(\"Exit uiautomator\") adb.forward(_uiautomator_port,_device_port) def _init(): port = os.environ.get(\"UIAUTOMATORPORT\") if port:", "software distributed under the License is distributed on an \"AS", "distributed under the License is distributed on an \"AS IS\"", "\"AS IS\" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "if get_uiautomator.instance: return get_uiautomator.instance else: port=_init() get_uiautomator.instance = AutomatorDevice(None, port,", "to support the open source community by making GAutomator available.", "else: port=_init() get_uiautomator.instance = AutomatorDevice(None, port, os.environ.get(\"PLATFORM_IP\", \"127.0.0.1\"), None) return", "CONDITIONS OF ANY KIND, either express or implied. See the", "of the License at http://opensource.org/licenses/MIT Unless required by applicable law", "making GAutomator available. Copyright (C) 2016 THL A29 Limited, a", "wpyscripts.common.adb_process import AdbTool logger=logging.getLogger(\"wetest\") _device_port=9008 _uiautomator_port = os.environ.get(\"UIAUTOMATOR_PORT\",\"19008\") def _init_uiautomator():", "uiautomator_stub_path = os.path.abspath( os.path.join(file_path, \"..\",\"third\",\"libs\",\"uiAutomator\",\"uiautomator-stub.jar\")) adb=AdbTool() print(adb.cmd_wait(\"push\",uiautomator_stub_path,\"/data/local/tmp\")) logger.debug(\"Start UIAutomator\") uiautomator_process=adb.cmd(\"shell\",\"uiautomator\",\"runtest\",\"uiautomator-stub.jar\",\"-c\",\"com.github.uiautomatorstub.Stub\")", "writing, software distributed under the License is distributed on an", "_init_uiautomator(): \"\"\" 初始化uiautomator :return: \"\"\" file_path = os.path.split(os.path.realpath(__file__))[0] uiautomator_stub_path =", "not use this file except in compliance with the License.", "community by making GAutomator available. Copyright (C) 2016 THL A29", "express or implied. See the License for the specific language", "under the License is distributed on an \"AS IS\" basis,", "port=_init() get_uiautomator.instance = AutomatorDevice(None, port, os.environ.get(\"PLATFORM_IP\", \"127.0.0.1\"), None) return get_uiautomator.instance", "in compliance with the License. You may obtain a copy", "open source community by making GAutomator available. Copyright (C) 2016", "a copy of the License at http://opensource.org/licenses/MIT Unless required by", "you may not use this file except in compliance with", "\"\"\" Tencent is pleased to support the open source community", "import AdbTool logger=logging.getLogger(\"wetest\") _device_port=9008 _uiautomator_port = os.environ.get(\"UIAUTOMATOR_PORT\",\"19008\") def _init_uiautomator(): \"\"\"", "the License. You may obtain a copy of the License", "agreed to in writing, software distributed under the License is", "print(adb.cmd_wait(\"push\",uiautomator_stub_path,\"/data/local/tmp\")) logger.debug(\"Start UIAutomator\") uiautomator_process=adb.cmd(\"shell\",\"uiautomator\",\"runtest\",\"uiautomator-stub.jar\",\"-c\",\"com.github.uiautomatorstub.Stub\") time.sleep(3) logger.debug(\"Exit uiautomator\") adb.forward(_uiautomator_port,_device_port) def _init():", "UIAutomator\") uiautomator_process=adb.cmd(\"shell\",\"uiautomator\",\"runtest\",\"uiautomator-stub.jar\",\"-c\",\"com.github.uiautomatorstub.Stub\") time.sleep(3) logger.debug(\"Exit uiautomator\") adb.forward(_uiautomator_port,_device_port) def _init(): port =", "def get_uiautomator(): if get_uiautomator.instance: return get_uiautomator.instance else: port=_init() get_uiautomator.instance =", "Tencent is pleased to support the open source community by", "import time import os import logging from libs.uiauto.uiautomator import AutomatorDevice", "Tencent company. All rights reserved. Licensed under the MIT License", "use this file except in compliance with the License. You", "source community by making GAutomator available. Copyright (C) 2016 THL", "A29 Limited, a Tencent company. All rights reserved. Licensed under", "\"\"\" __author__ = 'minhuaxu <EMAIL>' import time import os import", "time.sleep(3) logger.debug(\"Exit uiautomator\") adb.forward(_uiautomator_port,_device_port) def _init(): port = os.environ.get(\"UIAUTOMATORPORT\") if", "= 'minhuaxu <EMAIL>' import time import os import logging from", "ANY KIND, either express or implied. See the License for", "#-*- coding: UTF-8 -*- \"\"\" Tencent is pleased to support", "os.environ.get(\"UIAUTOMATOR_PORT\",\"19008\") def _init_uiautomator(): \"\"\" 初始化uiautomator :return: \"\"\" file_path = os.path.split(os.path.realpath(__file__))[0]", "\"\"\" file_path = os.path.split(os.path.realpath(__file__))[0] uiautomator_stub_path = os.path.abspath( os.path.join(file_path, \"..\",\"third\",\"libs\",\"uiAutomator\",\"uiautomator-stub.jar\")) adb=AdbTool()", "_init(): port = os.environ.get(\"UIAUTOMATORPORT\") if port: return int(port) else: \"\"\"", "if port: return int(port) else: \"\"\" 本地,初始化UiAutomator \"\"\" _init_uiautomator() return", "logger.debug(\"Start UIAutomator\") uiautomator_process=adb.cmd(\"shell\",\"uiautomator\",\"runtest\",\"uiautomator-stub.jar\",\"-c\",\"com.github.uiautomatorstub.Stub\") time.sleep(3) logger.debug(\"Exit uiautomator\") adb.forward(_uiautomator_port,_device_port) def _init(): port", "UTF-8 -*- \"\"\" Tencent is pleased to support the open", "<EMAIL>' import time import os import logging from libs.uiauto.uiautomator import", "either express or implied. See the License for the specific", "\"License\"); you may not use this file except in compliance", "'minhuaxu <EMAIL>' import time import os import logging from libs.uiauto.uiautomator", "port: return int(port) else: \"\"\" 本地,初始化UiAutomator \"\"\" _init_uiautomator() return int(_uiautomator_port)", "adb=AdbTool() print(adb.cmd_wait(\"push\",uiautomator_stub_path,\"/data/local/tmp\")) logger.debug(\"Start UIAutomator\") uiautomator_process=adb.cmd(\"shell\",\"uiautomator\",\"runtest\",\"uiautomator-stub.jar\",\"-c\",\"com.github.uiautomatorstub.Stub\") time.sleep(3) logger.debug(\"Exit uiautomator\") adb.forward(_uiautomator_port,_device_port) def", "with the License. You may obtain a copy of the", "libs.uiauto.uiautomator import AutomatorDevice from wpyscripts.common.adb_process import AdbTool logger=logging.getLogger(\"wetest\") _device_port=9008 _uiautomator_port", "copy of the License at http://opensource.org/licenses/MIT Unless required by applicable", "return int(port) else: \"\"\" 本地,初始化UiAutomator \"\"\" _init_uiautomator() return int(_uiautomator_port) def", "os.path.split(os.path.realpath(__file__))[0] uiautomator_stub_path = os.path.abspath( os.path.join(file_path, \"..\",\"third\",\"libs\",\"uiAutomator\",\"uiautomator-stub.jar\")) adb=AdbTool() print(adb.cmd_wait(\"push\",uiautomator_stub_path,\"/data/local/tmp\")) logger.debug(\"Start UIAutomator\")", "License for the specific language governing permissions and limitations under", "Copyright (C) 2016 THL A29 Limited, a Tencent company. All", "the open source community by making GAutomator available. Copyright (C)", "= os.environ.get(\"UIAUTOMATORPORT\") if port: return int(port) else: \"\"\" 本地,初始化UiAutomator \"\"\"", "License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed", "_uiautomator_port = os.environ.get(\"UIAUTOMATOR_PORT\",\"19008\") def _init_uiautomator(): \"\"\" 初始化uiautomator :return: \"\"\" file_path", "from libs.uiauto.uiautomator import AutomatorDevice from wpyscripts.common.adb_process import AdbTool logger=logging.getLogger(\"wetest\") _device_port=9008", "and limitations under the License. \"\"\" __author__ = 'minhuaxu <EMAIL>'", "os.path.abspath( os.path.join(file_path, \"..\",\"third\",\"libs\",\"uiAutomator\",\"uiautomator-stub.jar\")) adb=AdbTool() print(adb.cmd_wait(\"push\",uiautomator_stub_path,\"/data/local/tmp\")) logger.debug(\"Start UIAutomator\") uiautomator_process=adb.cmd(\"shell\",\"uiautomator\",\"runtest\",\"uiautomator-stub.jar\",\"-c\",\"com.github.uiautomatorstub.Stub\") time.sleep(3) logger.debug(\"Exit", "the MIT License (the \"License\"); you may not use this", "uiautomator\") adb.forward(_uiautomator_port,_device_port) def _init(): port = os.environ.get(\"UIAUTOMATORPORT\") if port: return", "Licensed under the MIT License (the \"License\"); you may not", "language governing permissions and limitations under the License. \"\"\" __author__", "License is distributed on an \"AS IS\" basis, WITHOUT WARRANTIES", "this file except in compliance with the License. You may", "import os import logging from libs.uiauto.uiautomator import AutomatorDevice from wpyscripts.common.adb_process", "permissions and limitations under the License. \"\"\" __author__ = 'minhuaxu", "specific language governing permissions and limitations under the License. \"\"\"", "GAutomator available. Copyright (C) 2016 THL A29 Limited, a Tencent", "(the \"License\"); you may not use this file except in", "AdbTool logger=logging.getLogger(\"wetest\") _device_port=9008 _uiautomator_port = os.environ.get(\"UIAUTOMATOR_PORT\",\"19008\") def _init_uiautomator(): \"\"\" 初始化uiautomator", "applicable law or agreed to in writing, software distributed under", "port = os.environ.get(\"UIAUTOMATORPORT\") if port: return int(port) else: \"\"\" 本地,初始化UiAutomator", "= os.path.split(os.path.realpath(__file__))[0] uiautomator_stub_path = os.path.abspath( os.path.join(file_path, \"..\",\"third\",\"libs\",\"uiAutomator\",\"uiautomator-stub.jar\")) adb=AdbTool() print(adb.cmd_wait(\"push\",uiautomator_stub_path,\"/data/local/tmp\")) logger.debug(\"Start", "int(_uiautomator_port) def get_uiautomator(): if get_uiautomator.instance: return get_uiautomator.instance else: port=_init() get_uiautomator.instance", "return get_uiautomator.instance else: port=_init() get_uiautomator.instance = AutomatorDevice(None, port, os.environ.get(\"PLATFORM_IP\", \"127.0.0.1\"),", "limitations under the License. \"\"\" __author__ = 'minhuaxu <EMAIL>' import", "is pleased to support the open source community by making", "__author__ = 'minhuaxu <EMAIL>' import time import os import logging", "the specific language governing permissions and limitations under the License.", "governing permissions and limitations under the License. \"\"\" __author__ =", "get_uiautomator.instance: return get_uiautomator.instance else: port=_init() get_uiautomator.instance = AutomatorDevice(None, port, os.environ.get(\"PLATFORM_IP\",", "obtain a copy of the License at http://opensource.org/licenses/MIT Unless required", "2016 THL A29 Limited, a Tencent company. All rights reserved.", "os.path.join(file_path, \"..\",\"third\",\"libs\",\"uiAutomator\",\"uiautomator-stub.jar\")) adb=AdbTool() print(adb.cmd_wait(\"push\",uiautomator_stub_path,\"/data/local/tmp\")) logger.debug(\"Start UIAutomator\") uiautomator_process=adb.cmd(\"shell\",\"uiautomator\",\"runtest\",\"uiautomator-stub.jar\",\"-c\",\"com.github.uiautomatorstub.Stub\") time.sleep(3) logger.debug(\"Exit uiautomator\")", "an \"AS IS\" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "a Tencent company. All rights reserved. Licensed under the MIT", "file except in compliance with the License. You may obtain", "except in compliance with the License. You may obtain a", "or implied. See the License for the specific language governing", "KIND, either express or implied. See the License for the", "def _init_uiautomator(): \"\"\" 初始化uiautomator :return: \"\"\" file_path = os.path.split(os.path.realpath(__file__))[0] uiautomator_stub_path", "to in writing, software distributed under the License is distributed", "Limited, a Tencent company. All rights reserved. Licensed under the", "or agreed to in writing, software distributed under the License", "adb.forward(_uiautomator_port,_device_port) def _init(): port = os.environ.get(\"UIAUTOMATORPORT\") if port: return int(port)", "may obtain a copy of the License at http://opensource.org/licenses/MIT Unless", "law or agreed to in writing, software distributed under the", "the License is distributed on an \"AS IS\" basis, WITHOUT", "OR CONDITIONS OF ANY KIND, either express or implied. See", "rights reserved. Licensed under the MIT License (the \"License\"); you", "= os.environ.get(\"UIAUTOMATOR_PORT\",\"19008\") def _init_uiautomator(): \"\"\" 初始化uiautomator :return: \"\"\" file_path =", "compliance with the License. You may obtain a copy of", "(C) 2016 THL A29 Limited, a Tencent company. All rights", "reserved. Licensed under the MIT License (the \"License\"); you may", "OF ANY KIND, either express or implied. See the License", "os.environ.get(\"UIAUTOMATORPORT\") if port: return int(port) else: \"\"\" 本地,初始化UiAutomator \"\"\" _init_uiautomator()", "_device_port=9008 _uiautomator_port = os.environ.get(\"UIAUTOMATOR_PORT\",\"19008\") def _init_uiautomator(): \"\"\" 初始化uiautomator :return: \"\"\"", "under the MIT License (the \"License\"); you may not use", "file_path = os.path.split(os.path.realpath(__file__))[0] uiautomator_stub_path = os.path.abspath( os.path.join(file_path, \"..\",\"third\",\"libs\",\"uiAutomator\",\"uiautomator-stub.jar\")) adb=AdbTool() print(adb.cmd_wait(\"push\",uiautomator_stub_path,\"/data/local/tmp\"))", "at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to", "License (the \"License\"); you may not use this file except", "int(port) else: \"\"\" 本地,初始化UiAutomator \"\"\" _init_uiautomator() return int(_uiautomator_port) def get_uiautomator():", "pleased to support the open source community by making GAutomator", "_init_uiautomator() return int(_uiautomator_port) def get_uiautomator(): if get_uiautomator.instance: return get_uiautomator.instance else:", "available. Copyright (C) 2016 THL A29 Limited, a Tencent company.", "on an \"AS IS\" basis, WITHOUT WARRANTIES OR CONDITIONS OF", "\"\"\" 初始化uiautomator :return: \"\"\" file_path = os.path.split(os.path.realpath(__file__))[0] uiautomator_stub_path = os.path.abspath(", "coding: UTF-8 -*- \"\"\" Tencent is pleased to support the", "-*- \"\"\" Tencent is pleased to support the open source", "All rights reserved. Licensed under the MIT License (the \"License\");", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "get_uiautomator(): if get_uiautomator.instance: return get_uiautomator.instance else: port=_init() get_uiautomator.instance = AutomatorDevice(None,", "for the specific language governing permissions and limitations under the", "import AutomatorDevice from wpyscripts.common.adb_process import AdbTool logger=logging.getLogger(\"wetest\") _device_port=9008 _uiautomator_port =", "See the License for the specific language governing permissions and", "distributed on an \"AS IS\" basis, WITHOUT WARRANTIES OR CONDITIONS", "the License at http://opensource.org/licenses/MIT Unless required by applicable law or", "uiautomator_process=adb.cmd(\"shell\",\"uiautomator\",\"runtest\",\"uiautomator-stub.jar\",\"-c\",\"com.github.uiautomatorstub.Stub\") time.sleep(3) logger.debug(\"Exit uiautomator\") adb.forward(_uiautomator_port,_device_port) def _init(): port = os.environ.get(\"UIAUTOMATORPORT\")", "\"..\",\"third\",\"libs\",\"uiAutomator\",\"uiautomator-stub.jar\")) adb=AdbTool() print(adb.cmd_wait(\"push\",uiautomator_stub_path,\"/data/local/tmp\")) logger.debug(\"Start UIAutomator\") uiautomator_process=adb.cmd(\"shell\",\"uiautomator\",\"runtest\",\"uiautomator-stub.jar\",\"-c\",\"com.github.uiautomatorstub.Stub\") time.sleep(3) logger.debug(\"Exit uiautomator\") adb.forward(_uiautomator_port,_device_port)", "本地,初始化UiAutomator \"\"\" _init_uiautomator() return int(_uiautomator_port) def get_uiautomator(): if get_uiautomator.instance: return", "logger=logging.getLogger(\"wetest\") _device_port=9008 _uiautomator_port = os.environ.get(\"UIAUTOMATOR_PORT\",\"19008\") def _init_uiautomator(): \"\"\" 初始化uiautomator :return:", "初始化uiautomator :return: \"\"\" file_path = os.path.split(os.path.realpath(__file__))[0] uiautomator_stub_path = os.path.abspath( os.path.join(file_path,", "from wpyscripts.common.adb_process import AdbTool logger=logging.getLogger(\"wetest\") _device_port=9008 _uiautomator_port = os.environ.get(\"UIAUTOMATOR_PORT\",\"19008\") def", "License. You may obtain a copy of the License at", "IS\" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "= os.path.abspath( os.path.join(file_path, \"..\",\"third\",\"libs\",\"uiAutomator\",\"uiautomator-stub.jar\")) adb=AdbTool() print(adb.cmd_wait(\"push\",uiautomator_stub_path,\"/data/local/tmp\")) logger.debug(\"Start UIAutomator\") uiautomator_process=adb.cmd(\"shell\",\"uiautomator\",\"runtest\",\"uiautomator-stub.jar\",\"-c\",\"com.github.uiautomatorstub.Stub\") time.sleep(3)", "\"\"\" 本地,初始化UiAutomator \"\"\" _init_uiautomator() return int(_uiautomator_port) def get_uiautomator(): if get_uiautomator.instance:", "def _init(): port = os.environ.get(\"UIAUTOMATORPORT\") if port: return int(port) else:", "get_uiautomator.instance else: port=_init() get_uiautomator.instance = AutomatorDevice(None, port, os.environ.get(\"PLATFORM_IP\", \"127.0.0.1\"), None)", "THL A29 Limited, a Tencent company. All rights reserved. Licensed", "MIT License (the \"License\"); you may not use this file", "AutomatorDevice from wpyscripts.common.adb_process import AdbTool logger=logging.getLogger(\"wetest\") _device_port=9008 _uiautomator_port = os.environ.get(\"UIAUTOMATOR_PORT\",\"19008\")", "the License for the specific language governing permissions and limitations", "may not use this file except in compliance with the", "in writing, software distributed under the License is distributed on", "else: \"\"\" 本地,初始化UiAutomator \"\"\" _init_uiautomator() return int(_uiautomator_port) def get_uiautomator(): if", "required by applicable law or agreed to in writing, software", "implied. See the License for the specific language governing permissions", "return int(_uiautomator_port) def get_uiautomator(): if get_uiautomator.instance: return get_uiautomator.instance else: port=_init()", "import logging from libs.uiauto.uiautomator import AutomatorDevice from wpyscripts.common.adb_process import AdbTool", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "support the open source community by making GAutomator available. Copyright", "You may obtain a copy of the License at http://opensource.org/licenses/MIT", "\"\"\" _init_uiautomator() return int(_uiautomator_port) def get_uiautomator(): if get_uiautomator.instance: return get_uiautomator.instance", "basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "by making GAutomator available. Copyright (C) 2016 THL A29 Limited,", "get_uiautomator.instance = AutomatorDevice(None, port, os.environ.get(\"PLATFORM_IP\", \"127.0.0.1\"), None) return get_uiautomator.instance get_uiautomator.instance=None", "os import logging from libs.uiauto.uiautomator import AutomatorDevice from wpyscripts.common.adb_process import", ":return: \"\"\" file_path = os.path.split(os.path.realpath(__file__))[0] uiautomator_stub_path = os.path.abspath( os.path.join(file_path, \"..\",\"third\",\"libs\",\"uiAutomator\",\"uiautomator-stub.jar\"))", "company. All rights reserved. Licensed under the MIT License (the", "License. \"\"\" __author__ = 'minhuaxu <EMAIL>' import time import os", "the License. \"\"\" __author__ = 'minhuaxu <EMAIL>' import time import", "is distributed on an \"AS IS\" basis, WITHOUT WARRANTIES OR" ]
[ "vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT", "= vtk.vtkActor() head.SetMapper(mapper) head.GetProperty().SetColor(1,0.7,0.6) # Create the RenderWindow, Renderer and", "and Interactor # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1)", "vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() class TestSynchronizedTemplates3D(Testing.vtkTest): def testAll(self): reader =", "#vtkSynchronizedTemplates3D stemp stemp = vtk.vtkContourFilter() stemp.SetInputConnection(reader.GetOutputPort()) stemp.SetValue(0,1150) stemp.GenerateTrianglesOff() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315)", "mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stemp.GetOutputPort()) mapper.ScalarVisibilityOff() head = vtk.vtkActor() head.SetMapper(mapper) head.GetProperty().SetColor(1,0.7,0.6)", "stemp.SetValue(0,1150) stemp.GenerateTrianglesOff() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380) stemp.GenerateTrianglesOn() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268) mapper", "--- end of script -- if __name__ == \"__main__\": Testing.main([(TestSynchronizedTemplates3D,", "stemp.GenerateTrianglesOff() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380) stemp.GenerateTrianglesOn() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268) mapper =", "Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() class TestSynchronizedTemplates3D(Testing.vtkTest):", "start the event loop # --- end of script --", "reader.SetFilePrefix(\"\" + str(VTK_DATA_ROOT) + \"/Data/headsq/quarter\") reader.SetDataMask(0x7fff) # write isosurface to", "self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380) stemp.GenerateTrianglesOn() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stemp.GetOutputPort()) mapper.ScalarVisibilityOff()", "class TestSynchronizedTemplates3D(Testing.vtkTest): def testAll(self): reader = vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5)", "vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set", "vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot()", "= vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the", "stemp.SetInputConnection(reader.GetOutputPort()) stemp.SetValue(0,1150) stemp.GenerateTrianglesOff() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380) stemp.GenerateTrianglesOn() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268)", "import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() class", "Create the RenderWindow, Renderer and Interactor # ren1 = vtk.vtkRenderer()", "stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stemp.GetOutputPort()) mapper.ScalarVisibilityOff() head =", "then start the event loop # --- end of script", "the actors to the renderer, set the background and size", "python import vtk from vtk.test import Testing from vtk.util.misc import", "isosurface to file #vtkSynchronizedTemplates3D stemp stemp = vtk.vtkContourFilter() stemp.SetInputConnection(reader.GetOutputPort()) stemp.SetValue(0,1150)", "ren1.AddActor(head) ren1.SetBackground(1,1,1) renWin.SetSize(400,400) ren1.SetBackground(0.5,0.5,0.6) ren1.GetActiveCamera().SetPosition(99.8847,537.926,15) ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15) ren1.GetActiveCamera().SetViewAngle(20) ren1.GetActiveCamera().SetViewUp(0,0,-1) ren1.ResetCameraClippingRange() #", "import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot", "# Create the RenderWindow, Renderer and Interactor # ren1 =", "vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() class TestSynchronizedTemplates3D(Testing.vtkTest): def testAll(self):", "# --- end of script -- if __name__ == \"__main__\":", "# render the image # renWin.Render() # prevent the tk", "ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15) ren1.GetActiveCamera().SetViewAngle(20) ren1.GetActiveCamera().SetViewUp(0,0,-1) ren1.ResetCameraClippingRange() # render the image # renWin.Render()", "\"/Data/headsq/quarter\") reader.SetDataMask(0x7fff) # write isosurface to file #vtkSynchronizedTemplates3D stemp stemp", "stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380) stemp.GenerateTrianglesOn() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268) mapper = vtk.vtkPolyDataMapper()", "def testAll(self): reader = vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix(\"\" +", "str(VTK_DATA_ROOT) + \"/Data/headsq/quarter\") reader.SetDataMask(0x7fff) # write isosurface to file #vtkSynchronizedTemplates3D", "# ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren =", "# ren1.AddActor(head) ren1.SetBackground(1,1,1) renWin.SetSize(400,400) ren1.SetBackground(0.5,0.5,0.6) ren1.GetActiveCamera().SetPosition(99.8847,537.926,15) ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15) ren1.GetActiveCamera().SetViewAngle(20) ren1.GetActiveCamera().SetViewUp(0,0,-1) ren1.ResetCameraClippingRange()", "renWin.SetSize(400,400) ren1.SetBackground(0.5,0.5,0.6) ren1.GetActiveCamera().SetPosition(99.8847,537.926,15) ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15) ren1.GetActiveCamera().SetViewAngle(20) ren1.GetActiveCamera().SetViewUp(0,0,-1) ren1.ResetCameraClippingRange() # render the", "the tk window from showing up then start the event", "end of script -- if __name__ == \"__main__\": Testing.main([(TestSynchronizedTemplates3D, 'test')])", "vtkGetDataRoot() class TestSynchronizedTemplates3D(Testing.vtkTest): def testAll(self): reader = vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93)", "= vtk.vtkContourFilter() stemp.SetInputConnection(reader.GetOutputPort()) stemp.SetValue(0,1150) stemp.GenerateTrianglesOff() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380) stemp.GenerateTrianglesOn() stemp.Update()", "the event loop # --- end of script -- if", "tk window from showing up then start the event loop", "set the background and size # ren1.AddActor(head) ren1.SetBackground(1,1,1) renWin.SetSize(400,400) ren1.SetBackground(0.5,0.5,0.6)", "mapper.ScalarVisibilityOff() head = vtk.vtkActor() head.SetMapper(mapper) head.GetProperty().SetColor(1,0.7,0.6) # Create the RenderWindow,", "showing up then start the event loop # --- end", "vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors", "ren1.GetActiveCamera().SetPosition(99.8847,537.926,15) ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15) ren1.GetActiveCamera().SetViewAngle(20) ren1.GetActiveCamera().SetViewUp(0,0,-1) ren1.ResetCameraClippingRange() # render the image #", "reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix(\"\" + str(VTK_DATA_ROOT) + \"/Data/headsq/quarter\") reader.SetDataMask(0x7fff) # write isosurface", "image # renWin.Render() # prevent the tk window from showing", "head.SetMapper(mapper) head.GetProperty().SetColor(1,0.7,0.6) # Create the RenderWindow, Renderer and Interactor #", "stemp stemp = vtk.vtkContourFilter() stemp.SetInputConnection(reader.GetOutputPort()) stemp.SetValue(0,1150) stemp.GenerateTrianglesOff() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380)", "stemp.GenerateTrianglesOn() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stemp.GetOutputPort()) mapper.ScalarVisibilityOff() head", "ren1.ResetCameraClippingRange() # render the image # renWin.Render() # prevent the", "render the image # renWin.Render() # prevent the tk window", "prevent the tk window from showing up then start the", "+ \"/Data/headsq/quarter\") reader.SetDataMask(0x7fff) # write isosurface to file #vtkSynchronizedTemplates3D stemp", "iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the", "renderer, set the background and size # ren1.AddActor(head) ren1.SetBackground(1,1,1) renWin.SetSize(400,400)", "<gh_stars>0 #!/usr/bin/env python import vtk from vtk.test import Testing from", "reader = vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix(\"\" + str(VTK_DATA_ROOT) +", "file #vtkSynchronizedTemplates3D stemp stemp = vtk.vtkContourFilter() stemp.SetInputConnection(reader.GetOutputPort()) stemp.SetValue(0,1150) stemp.GenerateTrianglesOff() stemp.Update()", "head.GetProperty().SetColor(1,0.7,0.6) # Create the RenderWindow, Renderer and Interactor # ren1", "vtk.vtkContourFilter() stemp.SetInputConnection(reader.GetOutputPort()) stemp.SetValue(0,1150) stemp.GenerateTrianglesOff() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380) stemp.GenerateTrianglesOn() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315)", "the RenderWindow, Renderer and Interactor # ren1 = vtk.vtkRenderer() renWin", "RenderWindow, Renderer and Interactor # ren1 = vtk.vtkRenderer() renWin =", "the image # renWin.Render() # prevent the tk window from", "ren1.GetActiveCamera().SetViewAngle(20) ren1.GetActiveCamera().SetViewUp(0,0,-1) ren1.ResetCameraClippingRange() # render the image # renWin.Render() #", "to file #vtkSynchronizedTemplates3D stemp stemp = vtk.vtkContourFilter() stemp.SetInputConnection(reader.GetOutputPort()) stemp.SetValue(0,1150) stemp.GenerateTrianglesOff()", "loop # --- end of script -- if __name__ ==", "self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stemp.GetOutputPort()) mapper.ScalarVisibilityOff() head = vtk.vtkActor()", "Renderer and Interactor # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow()", "head = vtk.vtkActor() head.SetMapper(mapper) head.GetProperty().SetColor(1,0.7,0.6) # Create the RenderWindow, Renderer", "actors to the renderer, set the background and size #", "import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() class TestSynchronizedTemplates3D(Testing.vtkTest): def testAll(self): reader", "renWin.Render() # prevent the tk window from showing up then", "= vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix(\"\" + str(VTK_DATA_ROOT) + \"/Data/headsq/quarter\")", "#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc", "= vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer,", "self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380) stemp.GenerateTrianglesOn() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stemp.GetOutputPort())", "ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor()", "ren1.GetActiveCamera().SetViewUp(0,0,-1) ren1.ResetCameraClippingRange() # render the image # renWin.Render() # prevent", "reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix(\"\" + str(VTK_DATA_ROOT) + \"/Data/headsq/quarter\") reader.SetDataMask(0x7fff) # write", "Interactor # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren", "iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the", "# prevent the tk window from showing up then start", "+ str(VTK_DATA_ROOT) + \"/Data/headsq/quarter\") reader.SetDataMask(0x7fff) # write isosurface to file", "the renderer, set the background and size # ren1.AddActor(head) ren1.SetBackground(1,1,1)", "from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT =", "the background and size # ren1.AddActor(head) ren1.SetBackground(1,1,1) renWin.SetSize(400,400) ren1.SetBackground(0.5,0.5,0.6) ren1.GetActiveCamera().SetPosition(99.8847,537.926,15)", "vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix(\"\" + str(VTK_DATA_ROOT) + \"/Data/headsq/quarter\") reader.SetDataMask(0x7fff)", "vtk.vtkPolyDataMapper() mapper.SetInputConnection(stemp.GetOutputPort()) mapper.ScalarVisibilityOff() head = vtk.vtkActor() head.SetMapper(mapper) head.GetProperty().SetColor(1,0.7,0.6) # Create", "= vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin)", "TestSynchronizedTemplates3D(Testing.vtkTest): def testAll(self): reader = vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix(\"\"", "renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add", "event loop # --- end of script -- if __name__", "# Add the actors to the renderer, set the background", "VTK_DATA_ROOT = vtkGetDataRoot() class TestSynchronizedTemplates3D(Testing.vtkTest): def testAll(self): reader = vtk.vtkImageReader()", "# write isosurface to file #vtkSynchronizedTemplates3D stemp stemp = vtk.vtkContourFilter()", "from showing up then start the event loop # ---", "testAll(self): reader = vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix(\"\" + str(VTK_DATA_ROOT)", "= vtkGetDataRoot() class TestSynchronizedTemplates3D(Testing.vtkTest): def testAll(self): reader = vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian()", "write isosurface to file #vtkSynchronizedTemplates3D stemp stemp = vtk.vtkContourFilter() stemp.SetInputConnection(reader.GetOutputPort())", "background and size # ren1.AddActor(head) ren1.SetBackground(1,1,1) renWin.SetSize(400,400) ren1.SetBackground(0.5,0.5,0.6) ren1.GetActiveCamera().SetPosition(99.8847,537.926,15) ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15)", "# renWin.Render() # prevent the tk window from showing up", "reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix(\"\" + str(VTK_DATA_ROOT) + \"/Data/headsq/quarter\") reader.SetDataMask(0x7fff) #", "stemp = vtk.vtkContourFilter() stemp.SetInputConnection(reader.GetOutputPort()) stemp.SetValue(0,1150) stemp.GenerateTrianglesOff() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380) stemp.GenerateTrianglesOn()", "vtk.vtkActor() head.SetMapper(mapper) head.GetProperty().SetColor(1,0.7,0.6) # Create the RenderWindow, Renderer and Interactor", "window from showing up then start the event loop #", "from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() class TestSynchronizedTemplates3D(Testing.vtkTest): def", "size # ren1.AddActor(head) ren1.SetBackground(1,1,1) renWin.SetSize(400,400) ren1.SetBackground(0.5,0.5,0.6) ren1.GetActiveCamera().SetPosition(99.8847,537.926,15) ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15) ren1.GetActiveCamera().SetViewAngle(20) ren1.GetActiveCamera().SetViewUp(0,0,-1)", "mapper.SetInputConnection(stemp.GetOutputPort()) mapper.ScalarVisibilityOff() head = vtk.vtkActor() head.SetMapper(mapper) head.GetProperty().SetColor(1,0.7,0.6) # Create the", "ren1.SetBackground(1,1,1) renWin.SetSize(400,400) ren1.SetBackground(0.5,0.5,0.6) ren1.GetActiveCamera().SetPosition(99.8847,537.926,15) ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15) ren1.GetActiveCamera().SetViewAngle(20) ren1.GetActiveCamera().SetViewUp(0,0,-1) ren1.ResetCameraClippingRange() # render", "and size # ren1.AddActor(head) ren1.SetBackground(1,1,1) renWin.SetSize(400,400) ren1.SetBackground(0.5,0.5,0.6) ren1.GetActiveCamera().SetPosition(99.8847,537.926,15) ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15) ren1.GetActiveCamera().SetViewAngle(20)", "Add the actors to the renderer, set the background and", "to the renderer, set the background and size # ren1.AddActor(head)", "ren1.SetBackground(0.5,0.5,0.6) ren1.GetActiveCamera().SetPosition(99.8847,537.926,15) ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15) ren1.GetActiveCamera().SetViewAngle(20) ren1.GetActiveCamera().SetViewUp(0,0,-1) ren1.ResetCameraClippingRange() # render the image", "= vtk.vtkPolyDataMapper() mapper.SetInputConnection(stemp.GetOutputPort()) mapper.ScalarVisibilityOff() head = vtk.vtkActor() head.SetMapper(mapper) head.GetProperty().SetColor(1,0.7,0.6) #", "vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) #", "renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to", "up then start the event loop # --- end of", "self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stemp.GetOutputPort()) mapper.ScalarVisibilityOff() head = vtk.vtkActor() head.SetMapper(mapper)", "reader.SetDataMask(0x7fff) # write isosurface to file #vtkSynchronizedTemplates3D stemp stemp =" ]
[ "deserialized remaining_properties = set(data.keys()) if not isinstance(data, dict): raise DeserializeException(", "(WARNING: This can use a significant amount of memory) all", ") property_value = parser_function(None) if not using_default: deserialized_value = _deserialize(", "though. def finalize(value: Optional[Any]) -> Optional[Any]: \"\"\"Run through any finalization", "{debug_name}\" ) result[dict_key] = _deserialize( value_type, dict_value, f\"{debug_name}.{dict_key}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(),", "# pylint:enable=too-many-return-statements def _deserialize_list( class_reference, list_data, debug_name, *, throw_on_unhandled: bool,", "in [RawStorageMode.root, RawStorageMode.all]: # We can't set attributes on primitive", "show any errors. The other option is # to take", "mode for the raw data on each object. If a", "hints = typing.get_type_hints(class_reference) if len(hints) == 0: raise DeserializeException( f\"Could", "return output def _deserialize_dict( class_reference, data, debug_name, *, throw_on_unhandled: bool,", "enum.Enum): try: return finalize(class_reference(data)) # pylint:disable=bare-except except: enum_by_name = getattr(class_reference,", "is either correct, or invalid if isinstance(data, class_reference): return finalize(data)", "Error on: {debug_name}.{attribute_name}\" ) using_default = False if property_key in", "storage mode :returns: The child raw storage mode \"\"\" if", "# pylint:disable=too-many-return-statements def _deserialize( class_reference, data, debug_name, *, throw_on_unhandled: bool,", "0: raise UnhandledFieldException( f\"The following field was unhandled: {list(remaining_properties)[0]} for", "we need to change mode in some cases. For instance,", "or None type first and return # early, since we", "if we have an any type or None type first", "those (since that doesn't # make any sense). But then", "attribute_name): continue property_key = _get_key(class_reference, attribute_name) parser_function = _get_parser(class_reference, property_key)", "= False if property_key in data: value = data[property_key] handled_fields.add(property_key)", "data should not be None if we have a type", "go through each item in the data, and iterate. #", "all the children to not be stored. :raises Exception: If", "none = \"none\" # Only store the data on the", "be stored. :raises Exception: If we get an unexpected storage", "dict for instance: {class_reference} for {debug_name}\" ) if is_dict(class_reference): if", "class_reference.__new__(class_reference) handled_fields = set() hints = typing.get_type_hints(class_reference) if len(hints) ==", "class_instance = class_reference.__new__(class_reference) handled_fields = set() hints = typing.get_type_hints(class_reference) if", "RawStorageMode ): \"\"\"Deserialize data to a Python object, but allow", "with downcast identifier '{downcast_value}' for {debug_name}\" ) class_reference = new_reference", "debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize data to", "deserialize.decorators import constructed, _call_constructed from deserialize.decorators import default, _get_default, _has_default", "a mix of both. # # For example, we check", "# pylint: disable=unidiomatic-typecheck # pylint: disable=protected-access # pylint: disable=too-many-branches #", "attribute_name.lower() != attribute_name: raise DeserializeException( f\"When using auto_snake, all properties", "doing a straightforward dictionary parse first, or if it #", "unions above, so if we are here, it's a non-optional", "or if it # has to be deserialized remaining_properties =", "self == RawStorageMode.root: return RawStorageMode.none if self == RawStorageMode.all: return", "RawStorageMode.all: return RawStorageMode.all raise DeserializeException(f\"Unexpected raw storage mode: {self}\") #", "and camel_case(property_key) in data: value = data[camel_case(property_key)] handled_fields.add(camel_case(property_key)) property_value =", "root node, then we need to set all the children", "finalize(value: Optional[Any]) -> Optional[Any]: \"\"\"Run through any finalization steps before", "valid_type in valid_types: try: return finalize( _deserialize( valid_type, data, debug_name,", "pylint:enable=too-many-return-statements def _deserialize_list( class_reference, list_data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode:", "dict_value in data.items(): if key_type != Any and not isinstance(dict_key,", "*, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize data to a", "len(filtered_unhandled) > 0: raise UnhandledFieldException( f\"Unhandled field: {list(filtered_unhandled)[0]} for {debug_name}\"", "set, the data will be stored in the attribute named:", "if is_typing_type(class_reference): # The data should not be None if", "sense). But then later, we can't go for a list", "the data to that and show any errors. The other", "I've found to work is to try and do specific", "raw_storage_mode in [RawStorageMode.root, RawStorageMode.all]: # We can't set attributes on", "class_reference_downcast_field = _get_downcast_field(class_reference) if class_reference_downcast_field: downcast_value = data[class_reference_downcast_field] new_reference =", "from deserialize.decorators import default, _get_default, _has_default from deserialize.decorators import (", "throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize data to a Python", "# Check if we are doing a straightforward dictionary parse", "RawStorageMode.none if self == RawStorageMode.root: return RawStorageMode.none if self ==", "Only store the data on the root node root =", "# Whatever we have left now is either correct, or", "NoDefaultSpecifiedException, UndefinedDowncastException, UnhandledFieldException, ) from deserialize.type_checks import * class RawStorageMode(enum.Enum):", "early, since we can't deserialize directly to those (since that", "to the next child iteration, we need to change mode", "deserialize.decorators import auto_snake, _uses_auto_snake from deserialize.decorators import allow_unhandled, _should_allow_unhandled from", "set in stone though. def finalize(value: Optional[Any]) -> Optional[Any]: \"\"\"Run", "None. if data is None: raise DeserializeException( f\"No value for", ":raises Exception: If we get an unexpected storage mode :returns:", "deserialize return data key_type, value_type = dict_content_types(class_reference, debug_name) result =", "{debug_name}\" ) if is_dict(class_reference): if class_reference is dict: # If", "= _deserialize( list_content_type_value, item, f\"{debug_name}[{index}]\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) output.append(deserialized) return", "if key_type != Any and not isinstance(dict_key, key_type): raise DeserializeException(", "= _deserialize( value_type, dict_value, f\"{debug_name}.{dict_key}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) remaining_properties.remove(dict_key) if", "if isinstance(data, list): return finalize( _deserialize_list( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled,", "[ key for key in unhandled if not _should_allow_unhandled(class_reference, key)", "we need to set all the children to not be", "isinstance(list_data, list): raise DeserializeException( f\"Cannot deserialize '{type(list_data)}' as a list", "significant amount of memory) all = \"all\" def child_mode(self) ->", "not defined, do not deserialize return data key_type, value_type =", "== RawStorageMode.none: return RawStorageMode.none if self == RawStorageMode.root: return RawStorageMode.none", "if self == RawStorageMode.root: return RawStorageMode.none if self == RawStorageMode.all:", "functools import typing from typing import Any, Callable, Dict, List,", "from deserialize.decorators import allow_unhandled, _should_allow_unhandled from deserialize.exceptions import ( DeserializeException,", "raise DeserializeException( f\"Unexpected missing value for: {debug_name}.{attribute_name}\" ) property_value =", "in the data, and iterate. # # This produces quite", "_has_default(class_reference, attribute_name): deserialized_value = _get_default(class_reference, attribute_name) using_default = True else:", "index, item in enumerate(list_data): deserialized = _deserialize( list_content_type_value, item, f\"{debug_name}[{index}]\",", "then any other types afterwards. That's not # set in", "# and deserialize the data to that and show any", "in valid_types: try: return finalize( _deserialize( valid_type, data, debug_name, throw_on_unhandled=throw_on_unhandled,", "amount of memory) all = \"all\" def child_mode(self) -> \"RawStorageMode\":", ") raise UndefinedDowncastException( f\"Could not find subclass of {class_reference} with", "finalize( _deserialize_dict( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if", "sub_message += f\"\\n\\t{line}\" exception_message += sub_message raise DeserializeException(exception_message) if isinstance(data,", "# type and therefore should not be None. if data", "# type: ignore \"\"\"Deserialize data to a Python object.\"\"\" if", "types if hasattr(value, \"__dict__\"): setattr(value, \"__deserialize_raw__\", data) return value if", "Any, Callable, Dict, List, Optional, Union from deserialize.conversions import camel_case,", "try # and deserialize the data to that and show", "not deserialize key {dict_key} to type {key_type} for {debug_name}\" )", "parsing. When we move to the next child iteration, we", "raw_storage_mode: RawStorageMode ): \"\"\"Deserialize data to a Python object, but", "!= Any and not isinstance(dict_key, key_type): raise DeserializeException( f\"Could not", "for {debug_name}\" ) result[dict_key] = _deserialize( value_type, dict_value, f\"{debug_name}.{dict_key}\", throw_on_unhandled=throw_on_unhandled,", "\"all\" def child_mode(self) -> \"RawStorageMode\": \"\"\"Determine the mode for child", "in data: value = data[camel_case(property_key)] handled_fields.add(camel_case(property_key)) property_value = parser_function(value) elif", "# handle it if is_typing_type(class_reference): # The data should not", "for valid_type in valid_types: try: return finalize( _deserialize( valid_type, data,", "ex: exceptions.append(str(ex)) exception_message = ( f\"Cannot deserialize '{type(data)}' to '{class_reference}'", "[] for index, item in enumerate(list_data): deserialized = _deserialize( list_content_type_value,", "We can't set attributes on primitive types if hasattr(value, \"__dict__\"):", "not isinstance(data, dict): raise DeserializeException( f\"Data was not dict for", "try and use some \"heuristics\" to deserialize. We have 2", "attribute_type in hints.items(): if _should_ignore(class_reference, attribute_name): continue property_key = _get_key(class_reference,", "downcast identifier '{downcast_value}' for {debug_name}\" ) class_reference = new_reference class_instance", "main # options to do this. For the first, we", ") ) if isinstance(data, list): return finalize( _deserialize_list( class_reference, data,", "data, then any other types afterwards. That's not # set", "data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize data", "class_reference == type(None) and data is None: return finalize(None) if", "_deserialize_list( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if not", "be handled at the end pass # If we still", "is None: return finalize(None) if is_union(class_reference): valid_types = union_types(class_reference, debug_name)", "need to change mode in some cases. For instance, if", "an any type or None type first and return #", "union_types(class_reference, debug_name) exceptions = [] for valid_type in valid_types: try:", "objects.\"\"\" # pylint: disable=unidiomatic-typecheck # pylint: disable=protected-access # pylint: disable=too-many-branches", "finalize( _deserialize_list( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if", "deserialize. We have 2 main # options to do this.", "# Union[int, str, None] so we end up iterating against", "Any and not isinstance(dict_key, key_type): raise DeserializeException( f\"Could not deserialize", "from deserialize.decorators import ignore, _should_ignore from deserialize.decorators import key, _get_key", "the children to not be stored. :raises Exception: If we", "if _has_default(class_reference, attribute_name): deserialized_value = _get_default(class_reference, attribute_name) using_default = True", "if enum_by_name: return finalize(enum_by_name) # pylint:enable=bare-except # This will be", "_deserialize( valid_type, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) ) except DeserializeException", "# Only store the data on the root node root", "here, it's a non-optional # type and therefore should not", "'{debug_name}'\" ) # pylint:enable=too-many-return-statements def _deserialize_list( class_reference, list_data, debug_name, *,", "so we are in deserialize mode class_instance = None class_reference_downcast_field", "the root node, then we need to set all the", "move to the next child iteration, we need to change", "\"root\" # Store on all objects (WARNING: This can use", "any other types afterwards. That's not # set in stone", "= set() hints = typing.get_type_hints(class_reference) if len(hints) == 0: raise", "cannot be set: {debug_name}.{attribute_name}\" ) continue if _uses_auto_snake(class_reference) and attribute_name.lower()", "cased. Error on: {debug_name}.{attribute_name}\" ) using_default = False if property_key", "on all objects (WARNING: This can use a significant amount", "_deserialize( class_reference, data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ):", "are doing a straightforward dictionary parse first, or if it", "of type hints ({debug_name})\" ) for attribute_name, attribute_type in hints.items():", "\"__dict__\"): setattr(value, \"__deserialize_raw__\", data) return value if class_reference == Any:", "dictionaries are supported as base raw data types\" ) if", "= _get_parser(class_reference, property_key) if is_classvar(attribute_type): if property_key in data: raise", "before returning the value.\"\"\" # Set raw data where applicable", "The general # approach I've found to work is to", "the value.\"\"\" # Set raw data where applicable if raw_storage_mode", "store the root node, then we need to set all", "for {debug_name}\" ) # Whatever we have left now is", "data: value = data[camel_case(property_key)] handled_fields.add(camel_case(property_key)) property_value = parser_function(value) elif _uses_auto_snake(class_reference)", "# has to be deserialized remaining_properties = set(data.keys()) if not", "None) if enum_by_name: return finalize(enum_by_name) # pylint:enable=bare-except # This will", "in enumerate(list_data): deserialized = _deserialize( list_content_type_value, item, f\"{debug_name}[{index}]\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(),", "raw_storage_mode=raw_storage_mode, ) # pylint: enable=function-redefined # pylint:disable=too-many-return-statements def _deserialize( class_reference,", "import typing from typing import Any, Callable, Dict, List, Optional,", "the data on the root node root = \"root\" #", "we only store the root node, then we need to", "->\" ) for exception in exceptions: exception_lines = exception.split(\"\\n\") sub_message", "pylint:enable=bare-except # This will be handled at the end pass", "type and try # and deserialize the data to that", "property_key in data: raise DeserializeException( f\"ClassVars cannot be set: {debug_name}.{attribute_name}\"", "raw data on each object. If a store mode is", "property_value = parser_function(value) else: if _has_default(class_reference, attribute_name): deserialized_value = _get_default(class_reference,", "import functools import typing from typing import Any, Callable, Dict,", "DeserializeException( f\"Could not deserialize key {dict_key} to type {key_type} for", "can't set attributes on primitive types if hasattr(value, \"__dict__\"): setattr(value,", "not is_typing_type(class_reference) and issubclass(class_reference, enum.Enum): try: return finalize(class_reference(data)) # pylint:disable=bare-except", "list directly to a # type, so we have to", "= dict_content_types(class_reference, debug_name) result = {} for dict_key, dict_value in", "type hints ({debug_name})\" ) for attribute_name, attribute_type in hints.items(): if", ") # pylint: enable=function-redefined # pylint:disable=too-many-return-statements def _deserialize( class_reference, data,", "return finalize(class_reference(data)) # pylint:disable=bare-except except: enum_by_name = getattr(class_reference, str(data), None)", "make any sense). But then later, we can't go for", "RawStorageMode.none: return RawStorageMode.none if self == RawStorageMode.root: return RawStorageMode.none if", "using_default = True else: if not is_union(attribute_type) or type(None) not", "import default, _get_default, _has_default from deserialize.decorators import ( downcast_field, _get_downcast_field,", "Optional[str]] become # Union[int, str, None] so we end up", "\"\"\"Deserialize data to a Python object.\"\"\" if not isinstance(data, dict)", "of dictionary entries are not defined, do not deserialize return", "f\"{debug_name}[{index}]\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) output.append(deserialized) return output def _deserialize_dict( class_reference,", "disable=protected-access # pylint: disable=too-many-branches # pylint: disable=wildcard-import import enum import", "and attribute_name.lower() != attribute_name: raise DeserializeException( f\"When using auto_snake, all", "raw_storage_mode: RawStorageMode = RawStorageMode.none): # type: ignore \"\"\"Deserialize data to", "all none = \"none\" # Only store the data on", "'{downcast_value}' for {debug_name}\" ) class_reference = new_reference class_instance = class_reference.__new__(class_reference)", "here we try and use some \"heuristics\" to deserialize. We", "getattr(class_reference, str(data), None) if enum_by_name: return finalize(enum_by_name) # pylint:enable=bare-except #", "that got here. Optionals # are handled by unions above,", "item in the data, and iterate. # # This produces", ") # Whatever we have left now is either correct,", "raw storage mode: {self}\") # pylint: disable=function-redefined def deserialize(class_reference, data,", "for {debug_name}\" ) if is_dict(class_reference): if class_reference is dict: #", "class_reference, list_data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode, ): if", "== RawStorageMode.root: return RawStorageMode.none if self == RawStorageMode.all: return RawStorageMode.all", "exception_lines[1:]: sub_message += f\"\\n\\t{line}\" exception_message += sub_message raise DeserializeException(exception_message) if", "pylint: disable=too-many-branches # pylint: disable=wildcard-import import enum import functools import", "InvalidBaseTypeException( \"Only lists and dictionaries are supported as base raw", "result[dict_key] = _deserialize( value_type, dict_value, f\"{debug_name}.{dict_key}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) remaining_properties.remove(dict_key)", ") result[dict_key] = _deserialize( value_type, dict_value, f\"{debug_name}.{dict_key}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), )", ") # pylint:enable=too-many-return-statements def _deserialize_list( class_reference, list_data, debug_name, *, throw_on_unhandled:", "property_key in data: value = data[property_key] handled_fields.add(property_key) property_value = parser_function(value)", "class_reference.__name__ else: name = str(class_reference) return _deserialize( class_reference, data, name,", "type first and return # early, since we can't deserialize", "debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if isinstance(data, list): return finalize(", "and therefore should not be None. if data is None:", "in data: value = data[pascal_case(property_key)] handled_fields.add(pascal_case(property_key)) property_value = parser_function(value) else:", "except: enum_by_name = getattr(class_reference, str(data), None) if enum_by_name: return finalize(enum_by_name)", "be None. if data is None: raise DeserializeException( f\"No value", "UndefinedDowncastException( f\"Could not find subclass of {class_reference} with downcast identifier", "base raw data types\" ) if hasattr(class_reference, \"__name__\"): name =", "produces quite a complex interweaving of operations. The general #", "Dict[Any, Any], data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) raise UndefinedDowncastException( f\"Could", "and issubclass(class_reference, enum.Enum): try: return finalize(class_reference(data)) # pylint:disable=bare-except except: enum_by_name", "need to set all the children to not be stored.", "to deserialize. We have 2 main # options to do", "_get_downcast_field, downcast_identifier, _get_downcast_class, allow_downcast_fallback, _allows_downcast_fallback, ) from deserialize.decorators import ignore,", "dict): raise DeserializeException( f\"Data was not dict for instance: {class_reference}", "exceptions = [] for valid_type in valid_types: try: return finalize(", "how to # handle it if is_typing_type(class_reference): # The data", "bool, raw_storage_mode: RawStorageMode, ): if not isinstance(list_data, list): raise DeserializeException(", "in data: raise DeserializeException( f\"ClassVars cannot be set: {debug_name}.{attribute_name}\" )", ") if hasattr(class_reference, \"__name__\"): name = class_reference.__name__ else: name =", "to type {key_type} for {debug_name}\" ) result[dict_key] = _deserialize( value_type,", "class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if isinstance(data, list):", "mode for child parsing. When we move to the next", "object. If a store mode is set, the data will", "This will be handled at the end pass # If", "property_key = _get_key(class_reference, attribute_name) parser_function = _get_parser(class_reference, property_key) if is_classvar(attribute_type):", "it # has to be deserialized remaining_properties = set(data.keys()) if", "RawStorageMode ): \"\"\"Deserialize a dictionary to a Python object.\"\"\" #", "to change mode in some cases. For instance, if we", "to a # type, so we have to go through", "node, then we need to set all the children to", "don't know how to # handle it if is_typing_type(class_reference): #", "= None class_reference_downcast_field = _get_downcast_field(class_reference) if class_reference_downcast_field: downcast_value = data[class_reference_downcast_field]", "directly to those (since that doesn't # make any sense).", "_get_parser from deserialize.decorators import auto_snake, _uses_auto_snake from deserialize.decorators import allow_unhandled,", "a list directly to a # type, so we have", "any finalization steps before returning the value.\"\"\" # Set raw", "debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) ) except DeserializeException as ex: exceptions.append(str(ex))", "RawStorageMode.root: return RawStorageMode.none if self == RawStorageMode.all: return RawStorageMode.all raise", "store the raw data at all none = \"none\" #", "options to do this. For the first, we can take", "defined, do not deserialize return data key_type, value_type = dict_content_types(class_reference,", "isinstance(data, dict): return finalize( _deserialize_dict( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode,", "and try # and deserialize the data to that and", "# # For example, we check if we have an", "try and do specific type checks first, # then handle", "throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) setattr(class_instance, attribute_name, deserialized_value) unhandled = set(data.keys()) -", "import ignore, _should_ignore from deserialize.decorators import key, _get_key from deserialize.decorators", "# # This produces quite a complex interweaving of operations.", "f\"{debug_name}.{attribute_name}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) setattr(class_instance, attribute_name, deserialized_value) unhandled = set(data.keys())", "from deserialize.type_checks import * class RawStorageMode(enum.Enum): \"\"\"The storage mode for", "and pascal_case(property_key) in data: value = data[pascal_case(property_key)] handled_fields.add(pascal_case(property_key)) property_value =", "the data, and iterate. # # This produces quite a", "= \"none\" # Only store the data on the root", "DeserializeException( f\"Data was not dict for instance: {class_reference} for {debug_name}\"", "RawStorageMode.none): # type: ignore \"\"\"Deserialize data to a Python object.\"\"\"", "iterating against it) if class_reference == type(None) and data is", "except DeserializeException as ex: exceptions.append(str(ex)) exception_message = ( f\"Cannot deserialize", "straightforward dictionary parse first, or if it # has to", "on: {debug_name}.{attribute_name}\" ) using_default = False if property_key in data:", "then we need to set all the children to not", "property_key) if is_classvar(attribute_type): if property_key in data: raise DeserializeException( f\"ClassVars", "f\"Cannot deserialize '{type(list_data)}' as a list for {debug_name}.\" ) if", "if class_reference == type(None) and data is None: return finalize(None)", "determine the types and deserialize that # way. We do", "not be None if we have a type that got", "in stone though. def finalize(value: Optional[Any]) -> Optional[Any]: \"\"\"Run through", "from typing import Any, Callable, Dict, List, Optional, Union from", "enable=function-redefined # pylint:disable=too-many-return-statements def _deserialize( class_reference, data, debug_name, *, throw_on_unhandled:", "not deserialize return data key_type, value_type = dict_content_types(class_reference, debug_name) result", "to those (since that doesn't # make any sense). But", "): raise DeserializeException( f\"Unexpected missing value for: {debug_name}.{attribute_name}\" ) property_value", "> 0: raise UnhandledFieldException( f\"Unhandled field: {list(filtered_unhandled)[0]} for {debug_name}\" )", "the first, we can take the expected type and try", "'{class_reference}'\" ) raise DeserializeException( f\"Unsupported deserialization type: {class_reference} for {debug_name}\"", "allow_downcast_fallback, _allows_downcast_fallback, ) from deserialize.decorators import ignore, _should_ignore from deserialize.decorators", "union_types( attribute_type, debug_name ): raise DeserializeException( f\"Unexpected missing value for:", "= union_types(class_reference, debug_name) exceptions = [] for valid_type in valid_types:", "): \"\"\"Deserialize data to a Python object, but allow base", "name = class_reference.__name__ else: name = str(class_reference) return _deserialize( class_reference,", "throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize a dictionary to a", "and iterate. # # This produces quite a complex interweaving", "The child raw storage mode \"\"\" if self == RawStorageMode.none:", "\"Only lists and dictionaries are supported as base raw data", "in some cases. For instance, if we only store the", "_deserialize( attribute_type, property_value, f\"{debug_name}.{attribute_name}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) setattr(class_instance, attribute_name, deserialized_value)", "finalize( _deserialize( valid_type, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) ) except", "\"\"\" # Do not store the raw data at all", "key) ] if len(filtered_unhandled) > 0: raise UnhandledFieldException( f\"Unhandled field:", "deserialize.decorators import default, _get_default, _has_default from deserialize.decorators import ( downcast_field,", "now is either correct, or invalid if isinstance(data, class_reference): return", "return RawStorageMode.none if self == RawStorageMode.root: return RawStorageMode.none if self", "self == RawStorageMode.none: return RawStorageMode.none if self == RawStorageMode.root: return", "to '{class_reference}' for '{debug_name}' ->\" ) for exception in exceptions:", "(since things like Union[int, Optional[str]] become # Union[int, str, None]", "for '{debug_name}' ->\" ) for exception in exceptions: exception_lines =", "value = data[property_key] handled_fields.add(property_key) property_value = parser_function(value) elif _uses_auto_snake(class_reference) and", "{data} into {class_reference} due to lack of type hints ({debug_name})\"", "attribute_name, attribute_type in hints.items(): if _should_ignore(class_reference, attribute_name): continue property_key =", "is dict: # If types of dictionary entries are not", "deserialize(class_reference, data, *, throw_on_unhandled: bool = False, raw_storage_mode: RawStorageMode =", "data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize a", "_get_key from deserialize.decorators import parser, _get_parser from deserialize.decorators import auto_snake,", "if not is_union(attribute_type) or type(None) not in union_types( attribute_type, debug_name", "{key_type} for {debug_name}\" ) result[dict_key] = _deserialize( value_type, dict_value, f\"{debug_name}.{dict_key}\",", "value for: {debug_name}.{attribute_name}\" ) property_value = parser_function(None) if not using_default:", "it's None (since things like Union[int, Optional[str]] become # Union[int,", "self == RawStorageMode.all: return RawStorageMode.all raise DeserializeException(f\"Unexpected raw storage mode:", "from deserialize.decorators import auto_snake, _uses_auto_snake from deserialize.decorators import allow_unhandled, _should_allow_unhandled", "allow base types\"\"\" # In here we try and use", "data, and iterate. # # This produces quite a complex", "\"heuristics\" to deserialize. We have 2 main # options to", "memory) all = \"all\" def child_mode(self) -> \"RawStorageMode\": \"\"\"Determine the", "if self == RawStorageMode.none: return RawStorageMode.none if self == RawStorageMode.root:", "instance: {class_reference} for {debug_name}\" ) if is_dict(class_reference): if class_reference is", "deserialize.exceptions import ( DeserializeException, InvalidBaseTypeException, NoDefaultSpecifiedException, UndefinedDowncastException, UnhandledFieldException, ) from", "node root = \"root\" # Store on all objects (WARNING:", "return _deserialize( class_reference, data, name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) # pylint:", "have an any type or None type first and return", "so if we are here, it's a non-optional # type", "raise UnhandledFieldException( f\"Unhandled field: {list(filtered_unhandled)[0]} for {debug_name}\" ) _call_constructed(class_reference, class_instance)", "unhandled: {list(remaining_properties)[0]} for {debug_name}\" ) return result # It wasn't", "sub_message raise DeserializeException(exception_message) if isinstance(data, dict): return finalize( _deserialize_dict( class_reference,", "import constructed, _call_constructed from deserialize.decorators import default, _get_default, _has_default from", "not in union_types( attribute_type, debug_name ): raise DeserializeException( f\"Unexpected missing", "continue property_key = _get_key(class_reference, attribute_name) parser_function = _get_parser(class_reference, property_key) if", "set(data.keys()) - handled_fields if throw_on_unhandled and len(unhandled) > 0: filtered_unhandled", "list for {debug_name}.\" ) if not is_list(class_reference): raise DeserializeException( f\"Cannot", "class_reference): return finalize(data) raise DeserializeException( f\"Cannot deserialize '{type(data)}' to '{class_reference}'", "not dict for instance: {class_reference} for {debug_name}\" ) if is_dict(class_reference):", "DeserializeException( f\"Cannot deserialize '{type(data)}' to '{class_reference}' for '{debug_name}'\" ) #", "be deserialized remaining_properties = set(data.keys()) if not isinstance(data, dict): raise", "None class_reference_downcast_field = _get_downcast_field(class_reference) if class_reference_downcast_field: downcast_value = data[class_reference_downcast_field] new_reference", "directly to a # type, so we have to go", "have left now is either correct, or invalid if isinstance(data,", "If types of dictionary entries are not defined, do not", "data key_type, value_type = dict_content_types(class_reference, debug_name) result = {} for", "parser_function(value) elif _uses_auto_snake(class_reference) and camel_case(property_key) in data: value = data[camel_case(property_key)]", "a straight forward dictionary, so we are in deserialize mode", "DeserializeException( f\"No value for '{debug_name}'. Expected value of type '{class_reference}'\"", "to that and show any errors. The other option is", "return data key_type, value_type = dict_content_types(class_reference, debug_name) result = {}", "from the typing module, we don't know how to #", "dictionary entries are not defined, do not deserialize return data", "raw_storage_mode=raw_storage_mode, ) ) if isinstance(data, list): return finalize( _deserialize_list( class_reference,", "new_reference is None: if _allows_downcast_fallback(class_reference): return _deserialize( Dict[Any, Any], data,", "DeserializeException( f\"Unsupported deserialization type: {class_reference} for {debug_name}\" ) # Whatever", "that # way. We do a mix of both. #", "first, we can take the expected type and try #", "types and deserialize that # way. We do a mix", "_allows_downcast_fallback(class_reference): return _deserialize( Dict[Any, Any], data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), )", "to # handle it if is_typing_type(class_reference): # The data should", "> 0: raise UnhandledFieldException( f\"The following field was unhandled: {list(remaining_properties)[0]}", "and not isinstance(data, list): raise InvalidBaseTypeException( \"Only lists and dictionaries", "from deserialize.decorators import key, _get_key from deserialize.decorators import parser, _get_parser", "def finalize(value: Optional[Any]) -> Optional[Any]: \"\"\"Run through any finalization steps", "entries are not defined, do not deserialize return data key_type,", "through each item in the data, and iterate. # #", "data to that and show any errors. The other option", "in union_types( attribute_type, debug_name ): raise DeserializeException( f\"Unexpected missing value", "-> \"RawStorageMode\": \"\"\"Determine the mode for child parsing. When we", "= data[camel_case(property_key)] handled_fields.add(camel_case(property_key)) property_value = parser_function(value) elif _uses_auto_snake(class_reference) and pascal_case(property_key)", "_get_downcast_field(class_reference) if class_reference_downcast_field: downcast_value = data[class_reference_downcast_field] new_reference = _get_downcast_class(class_reference, downcast_value)", "child raw storage mode \"\"\" if self == RawStorageMode.none: return", "snake cased. Error on: {debug_name}.{attribute_name}\" ) using_default = False if", "in unhandled if not _should_allow_unhandled(class_reference, key) ] if len(filtered_unhandled) >", "using_default = False if property_key in data: value = data[property_key]", "] if len(filtered_unhandled) > 0: raise UnhandledFieldException( f\"Unhandled field: {list(filtered_unhandled)[0]}", "we can't go for a list directly to a #", "DeserializeException( f\"ClassVars cannot be set: {debug_name}.{attribute_name}\" ) continue if _uses_auto_snake(class_reference)", "value for '{debug_name}'. Expected value of type '{class_reference}'\" ) raise", ") list_content_type_value = list_content_type(class_reference, debug_name) output = [] for index,", "deserialized_value = _get_default(class_reference, attribute_name) using_default = True else: if not", "for index, item in enumerate(list_data): deserialized = _deserialize( list_content_type_value, item,", "and use some \"heuristics\" to deserialize. We have 2 main", "return # early, since we can't deserialize directly to those", "value of type '{class_reference}'\" ) raise DeserializeException( f\"Unsupported deserialization type:", "a type from the typing module, we don't know how", "into {class_reference} due to lack of type hints ({debug_name})\" )", "new_reference class_instance = class_reference.__new__(class_reference) handled_fields = set() hints = typing.get_type_hints(class_reference)", "output.append(deserialized) return output def _deserialize_dict( class_reference, data, debug_name, *, throw_on_unhandled:", "know how to # handle it if is_typing_type(class_reference): # The", "set(data.keys()) if not isinstance(data, dict): raise DeserializeException( f\"Data was not", ") for exception in exceptions: exception_lines = exception.split(\"\\n\") sub_message =", "we don't know how to # handle it if is_typing_type(class_reference):", "specific type checks first, # then handle collection data, then", "# Store on all objects (WARNING: This can use a", "the types and deserialize that # way. We do a", "This can use a significant amount of memory) all =", "handle collection data, then any other types afterwards. That's not", "DeserializeException(f\"Unexpected raw storage mode: {self}\") # pylint: disable=function-redefined def deserialize(class_reference,", "finalization steps before returning the value.\"\"\" # Set raw data", "Expected value of type '{class_reference}'\" ) raise DeserializeException( f\"Unsupported deserialization", "f\"{debug_name}.{dict_key}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) remaining_properties.remove(dict_key) if throw_on_unhandled and len(remaining_properties) >", "list): return finalize( _deserialize_list( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, )", "name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) # pylint: enable=function-redefined # pylint:disable=too-many-return-statements def", "_get_default(class_reference, attribute_name) using_default = True else: if not is_union(attribute_type) or", "RawStorageMode.all raise DeserializeException(f\"Unexpected raw storage mode: {self}\") # pylint: disable=function-redefined", "each object. If a store mode is set, the data", "raw_storage_mode: RawStorageMode, ): if not isinstance(list_data, list): raise DeserializeException( f\"Cannot", "by unions above, so if we are here, it's a", "handled by unions above, so if we are here, it's", "For the first, we can take the expected type and", "None: return finalize(None) if is_union(class_reference): valid_types = union_types(class_reference, debug_name) exceptions", "True else: if not is_union(attribute_type) or type(None) not in union_types(", "enumerate(list_data): deserialized = _deserialize( list_content_type_value, item, f\"{debug_name}[{index}]\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), )", "# to take the data, and try and determine the", "None (since things like Union[int, Optional[str]] become # Union[int, str,", "if it's None (since things like Union[int, Optional[str]] become #", "the root node root = \"root\" # Store on all", "raise DeserializeException( f\"Unsupported deserialization type: {class_reference} for {debug_name}\" ) #", "data to a Python object.\"\"\" if not isinstance(data, dict) and", "throw_on_unhandled and len(remaining_properties) > 0: raise UnhandledFieldException( f\"The following field", "== type(None) and data is None: return finalize(None) if is_union(class_reference):", "we try and use some \"heuristics\" to deserialize. We have", "not isinstance(data, dict) and not isinstance(data, list): raise InvalidBaseTypeException( \"Only", "or invalid if isinstance(data, class_reference): return finalize(data) raise DeserializeException( f\"Cannot", "raise DeserializeException( f\"Could not deserialize key {dict_key} to type {key_type}", "'{class_reference}' for '{debug_name}' ->\" ) for exception in exceptions: exception_lines", "Check if it's None (since things like Union[int, Optional[str]] become", "If we get an unexpected storage mode :returns: The child", "to take the data, and try and determine the types", "deserialize.type_checks import * class RawStorageMode(enum.Enum): \"\"\"The storage mode for the", "missing value for: {debug_name}.{attribute_name}\" ) property_value = parser_function(None) if not", "_uses_auto_snake(class_reference) and pascal_case(property_key) in data: value = data[pascal_case(property_key)] handled_fields.add(pascal_case(property_key)) property_value", "throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) output.append(deserialized) return output def _deserialize_dict( class_reference, data,", "parser_function(value) elif _uses_auto_snake(class_reference) and pascal_case(property_key) in data: value = data[pascal_case(property_key)]", "for the raw data on each object. If a store", "None] so we end up iterating against it) if class_reference", "be set: {debug_name}.{attribute_name}\" ) continue if _uses_auto_snake(class_reference) and attribute_name.lower() !=", "left now is either correct, or invalid if isinstance(data, class_reference):", "# then handle collection data, then any other types afterwards.", "dict: # If types of dictionary entries are not defined,", "Union[int, Optional[str]] become # Union[int, str, None] so we end", "DeserializeException as ex: exceptions.append(str(ex)) exception_message = ( f\"Cannot deserialize '{type(data)}'", "not is_union(attribute_type) or type(None) not in union_types( attribute_type, debug_name ):", "cases. For instance, if we only store the root node,", "= \"root\" # Store on all objects (WARNING: This can", "for instance: {class_reference} for {debug_name}\" ) if is_dict(class_reference): if class_reference", "None if we have a type that got here. Optionals", "have 2 main # options to do this. For the", "if class_reference is dict: # If types of dictionary entries", "a list for {debug_name}.\" ) if not is_list(class_reference): raise DeserializeException(", "was unhandled: {list(remaining_properties)[0]} for {debug_name}\" ) return result # It", "hasattr(value, \"__dict__\"): setattr(value, \"__deserialize_raw__\", data) return value if class_reference ==", "raise DeserializeException( f\"Cannot deserialize '{type(data)}' to '{class_reference}' for '{debug_name}'\" )", "{debug_name}\" ) # Whatever we have left now is either", "\"none\" # Only store the data on the root node", "Store on all objects (WARNING: This can use a significant", "{class_reference} due to lack of type hints ({debug_name})\" ) for", "For example, we check if we have an any type", "'{class_reference}' for {debug_name}\" ) list_content_type_value = list_content_type(class_reference, debug_name) output =", "= data[property_key] handled_fields.add(property_key) property_value = parser_function(value) elif _uses_auto_snake(class_reference) and camel_case(property_key)", "attribute_type, debug_name ): raise DeserializeException( f\"Unexpected missing value for: {debug_name}.{attribute_name}\"", "\"__deserialize_raw__\", data) return value if class_reference == Any: return finalize(data)", "deserialize mode class_instance = None class_reference_downcast_field = _get_downcast_field(class_reference) if class_reference_downcast_field:", "# Set raw data where applicable if raw_storage_mode in [RawStorageMode.root,", "{debug_name}\" ) class_reference = new_reference class_instance = class_reference.__new__(class_reference) handled_fields =", "import ( DeserializeException, InvalidBaseTypeException, NoDefaultSpecifiedException, UndefinedDowncastException, UnhandledFieldException, ) from deserialize.type_checks", "store the data on the root node root = \"root\"", "example, we check if we have an any type or", "for '{debug_name}'\" ) # pylint:enable=too-many-return-statements def _deserialize_list( class_reference, list_data, debug_name,", "is to try and do specific type checks first, #", "name = str(class_reference) return _deserialize( class_reference, data, name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode,", ") using_default = False if property_key in data: value =", "DeserializeException( f\"Unexpected missing value for: {debug_name}.{attribute_name}\" ) property_value = parser_function(None)", "DeserializeException, InvalidBaseTypeException, NoDefaultSpecifiedException, UndefinedDowncastException, UnhandledFieldException, ) from deserialize.type_checks import *", "f\"Cannot deserialize '{type(data)}' to '{class_reference}' for '{debug_name}' ->\" ) for", "_get_downcast_class(class_reference, downcast_value) if new_reference is None: if _allows_downcast_fallback(class_reference): return _deserialize(", "debug_name ): raise DeserializeException( f\"Unexpected missing value for: {debug_name}.{attribute_name}\" )", "module for deserializing data to Python objects.\"\"\" # pylint: disable=unidiomatic-typecheck", "_deserialize( class_reference, data, name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) # pylint: enable=function-redefined", "filtered_unhandled = [ key for key in unhandled if not", "_deserialize_dict( class_reference, data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ):", "throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) # pylint: enable=function-redefined # pylint:disable=too-many-return-statements def _deserialize(", "to work is to try and do specific type checks", "are in deserialize mode class_instance = None class_reference_downcast_field = _get_downcast_field(class_reference)", "mode class_instance = None class_reference_downcast_field = _get_downcast_field(class_reference) if class_reference_downcast_field: downcast_value", "not isinstance(dict_key, key_type): raise DeserializeException( f\"Could not deserialize key {dict_key}", "downcast_value = data[class_reference_downcast_field] new_reference = _get_downcast_class(class_reference, downcast_value) if new_reference is", "iterate. # # This produces quite a complex interweaving of", "{debug_name}.{attribute_name}\" ) property_value = parser_function(None) if not using_default: deserialized_value =", "it's a non-optional # type and therefore should not be", "are supported as base raw data types\" ) if hasattr(class_reference,", "to a Python object, but allow base types\"\"\" # In", "has to be deserialized remaining_properties = set(data.keys()) if not isinstance(data,", "type and therefore should not be None. if data is", "data to a Python object, but allow base types\"\"\" #", "a Python object.\"\"\" if not isinstance(data, dict) and not isinstance(data,", "can take the expected type and try # and deserialize", "object.\"\"\" # Check if we are doing a straightforward dictionary", "and len(remaining_properties) > 0: raise UnhandledFieldException( f\"The following field was", "for: {debug_name}.{attribute_name}\" ) property_value = parser_function(None) if not using_default: deserialized_value", "child iteration, we need to change mode in some cases.", "any sense). But then later, we can't go for a", "steps before returning the value.\"\"\" # Set raw data where", "root node root = \"root\" # Store on all objects", "enum import functools import typing from typing import Any, Callable,", "not isinstance(list_data, list): raise DeserializeException( f\"Cannot deserialize '{type(list_data)}' as a", "if is_classvar(attribute_type): if property_key in data: raise DeserializeException( f\"ClassVars cannot", "`__deserialize_raw__` \"\"\" # Do not store the raw data at", "_allows_downcast_fallback, ) from deserialize.decorators import ignore, _should_ignore from deserialize.decorators import", "pylint: disable=unidiomatic-typecheck # pylint: disable=protected-access # pylint: disable=too-many-branches # pylint:", "and return # early, since we can't deserialize directly to", "DeserializeException( f\"Cannot deserialize '{type(list_data)}' as a list for {debug_name}.\" )", "stored in the attribute named: `__deserialize_raw__` \"\"\" # Do not", "isinstance(data, dict) and not isinstance(data, list): raise InvalidBaseTypeException( \"Only lists", "bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize data to a Python object,", "item, f\"{debug_name}[{index}]\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) output.append(deserialized) return output def _deserialize_dict(", "\"\"\"A module for deserializing data to Python objects.\"\"\" # pylint:", "to Python objects.\"\"\" # pylint: disable=unidiomatic-typecheck # pylint: disable=protected-access #", "item in enumerate(list_data): deserialized = _deserialize( list_content_type_value, item, f\"{debug_name}[{index}]\", throw_on_unhandled=throw_on_unhandled,", "unhandled = set(data.keys()) - handled_fields if throw_on_unhandled and len(unhandled) >", "therefore should not be None. if data is None: raise", "raw_storage_mode=raw_storage_mode.child_mode(), ) setattr(class_instance, attribute_name, deserialized_value) unhandled = set(data.keys()) - handled_fields", "{debug_name}.{attribute_name}\" ) using_default = False if property_key in data: value", "the mode for child parsing. When we move to the", "and show any errors. The other option is # to", "can use a significant amount of memory) all = \"all\"", "Union from deserialize.conversions import camel_case, pascal_case from deserialize.decorators import constructed,", "None: raise DeserializeException( f\"No value for '{debug_name}'. Expected value of", "import parser, _get_parser from deserialize.decorators import auto_snake, _uses_auto_snake from deserialize.decorators", "an unexpected storage mode :returns: The child raw storage mode", "pylint:disable=bare-except except: enum_by_name = getattr(class_reference, str(data), None) if enum_by_name: return", "all properties must be snake cased. Error on: {debug_name}.{attribute_name}\" )", "types afterwards. That's not # set in stone though. def", "properties must be snake cased. Error on: {debug_name}.{attribute_name}\" ) using_default", "hints.items(): if _should_ignore(class_reference, attribute_name): continue property_key = _get_key(class_reference, attribute_name) parser_function", "children to not be stored. :raises Exception: If we get", "0: filtered_unhandled = [ key for key in unhandled if", "Optional[Any]: \"\"\"Run through any finalization steps before returning the value.\"\"\"", "hasattr(class_reference, \"__name__\"): name = class_reference.__name__ else: name = str(class_reference) return", "debug_name) exceptions = [] for valid_type in valid_types: try: return", "attribute_name) parser_function = _get_parser(class_reference, property_key) if is_classvar(attribute_type): if property_key in", ") from deserialize.type_checks import * class RawStorageMode(enum.Enum): \"\"\"The storage mode", "{class_reference} for {debug_name}\" ) # Whatever we have left now", "all objects (WARNING: This can use a significant amount of", "'{class_reference}' for '{debug_name}'\" ) # pylint:enable=too-many-return-statements def _deserialize_list( class_reference, list_data,", ") ) except DeserializeException as ex: exceptions.append(str(ex)) exception_message = (", "module, we don't know how to # handle it if", "we check if we have an any type or None", "class_reference is dict: # If types of dictionary entries are", "types of dictionary entries are not defined, do not deserialize", "'{type(list_data)}' as a list for {debug_name}.\" ) if not is_list(class_reference):", "debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize a dictionary", "RawStorageMode = RawStorageMode.none): # type: ignore \"\"\"Deserialize data to a", "if we are doing a straightforward dictionary parse first, or", "if not isinstance(data, dict): raise DeserializeException( f\"Data was not dict", "if not is_list(class_reference): raise DeserializeException( f\"Cannot deserialize a list to", "): \"\"\"Deserialize a dictionary to a Python object.\"\"\" # Check", "# pylint:disable=bare-except except: enum_by_name = getattr(class_reference, str(data), None) if enum_by_name:", "the next child iteration, we need to change mode in", "deserialize '{type(list_data)}' as a list for {debug_name}.\" ) if not", "dict_key, dict_value in data.items(): if key_type != Any and not", "storage mode for the raw data on each object. If", "can't go for a list directly to a # type,", "valid_types: try: return finalize( _deserialize( valid_type, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(),", "f\"\\n\\t* {exception_lines[0]}\" for line in exception_lines[1:]: sub_message += f\"\\n\\t{line}\" exception_message", "\"\"\"Deserialize data to a Python object, but allow base types\"\"\"", "def _deserialize( class_reference, data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode", "# The data should not be None if we have", "downcast_value) if new_reference is None: if _allows_downcast_fallback(class_reference): return _deserialize( Dict[Any,", "other option is # to take the data, and try", "# options to do this. For the first, we can", "at all none = \"none\" # Only store the data", "raise InvalidBaseTypeException( \"Only lists and dictionaries are supported as base", "# make any sense). But then later, we can't go", "UnhandledFieldException, ) from deserialize.type_checks import * class RawStorageMode(enum.Enum): \"\"\"The storage", "0: raise DeserializeException( f\"Could not deserialize {data} into {class_reference} due", "be None if we have a type that got here.", "the data will be stored in the attribute named: `__deserialize_raw__`", "but allow base types\"\"\" # In here we try and", "_get_parser(class_reference, property_key) if is_classvar(attribute_type): if property_key in data: raise DeserializeException(", "try: return finalize( _deserialize( valid_type, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), )", "parser, _get_parser from deserialize.decorators import auto_snake, _uses_auto_snake from deserialize.decorators import", "Union[int, str, None] so we end up iterating against it)", "instance, if we only store the root node, then we", "throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) remaining_properties.remove(dict_key) if throw_on_unhandled and len(remaining_properties) > 0:", "> 0: filtered_unhandled = [ key for key in unhandled", "do specific type checks first, # then handle collection data,", "data[class_reference_downcast_field] new_reference = _get_downcast_class(class_reference, downcast_value) if new_reference is None: if", "len(hints) == 0: raise DeserializeException( f\"Could not deserialize {data} into", "handled at the end pass # If we still have", "DeserializeException(exception_message) if isinstance(data, dict): return finalize( _deserialize_dict( class_reference, data, debug_name,", "= [] for valid_type in valid_types: try: return finalize( _deserialize(", "'{type(data)}' to '{class_reference}' for '{debug_name}' ->\" ) for exception in", ") class_reference = new_reference class_instance = class_reference.__new__(class_reference) handled_fields = set()", ") if not is_typing_type(class_reference) and issubclass(class_reference, enum.Enum): try: return finalize(class_reference(data))", "= new_reference class_instance = class_reference.__new__(class_reference) handled_fields = set() hints =", "\"\"\"The storage mode for the raw data on each object.", "disable=unidiomatic-typecheck # pylint: disable=protected-access # pylint: disable=too-many-branches # pylint: disable=wildcard-import", "len(unhandled) > 0: filtered_unhandled = [ key for key in", "RawStorageMode, ): if not isinstance(list_data, list): raise DeserializeException( f\"Cannot deserialize", "Optionals # are handled by unions above, so if we", "in hints.items(): if _should_ignore(class_reference, attribute_name): continue property_key = _get_key(class_reference, attribute_name)", "Python objects.\"\"\" # pylint: disable=unidiomatic-typecheck # pylint: disable=protected-access # pylint:", "import * class RawStorageMode(enum.Enum): \"\"\"The storage mode for the raw", "option is # to take the data, and try and", "raw_storage_mode=raw_storage_mode, ) ) if not is_typing_type(class_reference) and issubclass(class_reference, enum.Enum): try:", "handle it if is_typing_type(class_reference): # The data should not be", "\"__name__\"): name = class_reference.__name__ else: name = str(class_reference) return _deserialize(", "against it) if class_reference == type(None) and data is None:", "a non-optional # type and therefore should not be None.", "constructed, _call_constructed from deserialize.decorators import default, _get_default, _has_default from deserialize.decorators", "pylint: enable=function-redefined # pylint:disable=too-many-return-statements def _deserialize( class_reference, data, debug_name, *,", "should not be None. if data is None: raise DeserializeException(", "# set in stone though. def finalize(value: Optional[Any]) -> Optional[Any]:", "= RawStorageMode.none): # type: ignore \"\"\"Deserialize data to a Python", "# type, so we have to go through each item", "lack of type hints ({debug_name})\" ) for attribute_name, attribute_type in", "the raw data on each object. If a store mode", "should not be None if we have a type that", "class_instance = None class_reference_downcast_field = _get_downcast_field(class_reference) if class_reference_downcast_field: downcast_value =", "f\"Unhandled field: {list(filtered_unhandled)[0]} for {debug_name}\" ) _call_constructed(class_reference, class_instance) return class_instance", "{debug_name}.\" ) if not is_list(class_reference): raise DeserializeException( f\"Cannot deserialize a", "exception in exceptions: exception_lines = exception.split(\"\\n\") sub_message = f\"\\n\\t* {exception_lines[0]}\"", "finalize(data) raise DeserializeException( f\"Cannot deserialize '{type(data)}' to '{class_reference}' for '{debug_name}'\"", "do a mix of both. # # For example, we", "field was unhandled: {list(remaining_properties)[0]} for {debug_name}\" ) return result #", "raise DeserializeException( f\"Cannot deserialize '{type(list_data)}' as a list for {debug_name}.\"", "for line in exception_lines[1:]: sub_message += f\"\\n\\t{line}\" exception_message += sub_message", "if we only store the root node, then we need", "- handled_fields if throw_on_unhandled and len(unhandled) > 0: filtered_unhandled =", "do not deserialize return data key_type, value_type = dict_content_types(class_reference, debug_name)", "of both. # # For example, we check if we", "deserialize.conversions import camel_case, pascal_case from deserialize.decorators import constructed, _call_constructed from", ") raise DeserializeException( f\"Unsupported deserialization type: {class_reference} for {debug_name}\" )", "import enum import functools import typing from typing import Any,", "we have to go through each item in the data,", "dictionary parse first, or if it # has to be", "if _should_ignore(class_reference, attribute_name): continue property_key = _get_key(class_reference, attribute_name) parser_function =", "in data: value = data[property_key] handled_fields.add(property_key) property_value = parser_function(value) elif", "get an unexpected storage mode :returns: The child raw storage", "identifier '{downcast_value}' for {debug_name}\" ) class_reference = new_reference class_instance =", "it if is_typing_type(class_reference): # The data should not be None", "end up iterating against it) if class_reference == type(None) and", "class_reference, data, name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) # pylint: enable=function-redefined #", "the attribute named: `__deserialize_raw__` \"\"\" # Do not store the", "for exception in exceptions: exception_lines = exception.split(\"\\n\") sub_message = f\"\\n\\t*", "handled_fields if throw_on_unhandled and len(unhandled) > 0: filtered_unhandled = [", "finalize(None) if is_union(class_reference): valid_types = union_types(class_reference, debug_name) exceptions = []", "the end pass # If we still have a type", "if hasattr(class_reference, \"__name__\"): name = class_reference.__name__ else: name = str(class_reference)", "debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) raise UndefinedDowncastException( f\"Could not find subclass", "data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) ) except DeserializeException as ex:", "to set all the children to not be stored. :raises", "key {dict_key} to type {key_type} for {debug_name}\" ) result[dict_key] =", "in data.items(): if key_type != Any and not isinstance(dict_key, key_type):", "on each object. If a store mode is set, the", "that and show any errors. The other option is #", ") if not is_list(class_reference): raise DeserializeException( f\"Cannot deserialize a list", "return RawStorageMode.none if self == RawStorageMode.all: return RawStorageMode.all raise DeserializeException(f\"Unexpected", "raise DeserializeException( f\"ClassVars cannot be set: {debug_name}.{attribute_name}\" ) continue if", "is # to take the data, and try and determine", "* class RawStorageMode(enum.Enum): \"\"\"The storage mode for the raw data", "a Python object.\"\"\" # Check if we are doing a", "camel_case(property_key) in data: value = data[camel_case(property_key)] handled_fields.add(camel_case(property_key)) property_value = parser_function(value)", "deserialized = _deserialize( list_content_type_value, item, f\"{debug_name}[{index}]\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) output.append(deserialized)", "remaining_properties.remove(dict_key) if throw_on_unhandled and len(remaining_properties) > 0: raise UnhandledFieldException( f\"The", "debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if not is_typing_type(class_reference) and issubclass(class_reference,", "if throw_on_unhandled and len(remaining_properties) > 0: raise UnhandledFieldException( f\"The following", "data is None: return finalize(None) if is_union(class_reference): valid_types = union_types(class_reference,", "_should_allow_unhandled(class_reference, key) ] if len(filtered_unhandled) > 0: raise UnhandledFieldException( f\"Unhandled", "parser_function = _get_parser(class_reference, property_key) if is_classvar(attribute_type): if property_key in data:", "supported as base raw data types\" ) if hasattr(class_reference, \"__name__\"):", "f\"No value for '{debug_name}'. Expected value of type '{class_reference}'\" )", "# pylint: disable=wildcard-import import enum import functools import typing from", "if hasattr(value, \"__dict__\"): setattr(value, \"__deserialize_raw__\", data) return value if class_reference", "It wasn't a straight forward dictionary, so we are in", "isinstance(dict_key, key_type): raise DeserializeException( f\"Could not deserialize key {dict_key} to", "dict) and not isinstance(data, list): raise InvalidBaseTypeException( \"Only lists and", "take the data, and try and determine the types and", "exception_lines = exception.split(\"\\n\") sub_message = f\"\\n\\t* {exception_lines[0]}\" for line in", "if not isinstance(data, dict) and not isinstance(data, list): raise InvalidBaseTypeException(", "# In here we try and use some \"heuristics\" to", "output def _deserialize_dict( class_reference, data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode:", "to lack of type hints ({debug_name})\" ) for attribute_name, attribute_type", "we have left now is either correct, or invalid if", "In here we try and use some \"heuristics\" to deserialize.", "data types\" ) if hasattr(class_reference, \"__name__\"): name = class_reference.__name__ else:", "if data is None: raise DeserializeException( f\"No value for '{debug_name}'.", "= _get_key(class_reference, attribute_name) parser_function = _get_parser(class_reference, property_key) if is_classvar(attribute_type): if", "data, name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) # pylint: enable=function-redefined # pylint:disable=too-many-return-statements", "if not using_default: deserialized_value = _deserialize( attribute_type, property_value, f\"{debug_name}.{attribute_name}\", throw_on_unhandled=throw_on_unhandled,", "*, throw_on_unhandled: bool = False, raw_storage_mode: RawStorageMode = RawStorageMode.none): #", "non-optional # type and therefore should not be None. if", "default, _get_default, _has_default from deserialize.decorators import ( downcast_field, _get_downcast_field, downcast_identifier,", "general # approach I've found to work is to try", "is_typing_type(class_reference): # The data should not be None if we", "raw_storage_mode=raw_storage_mode.child_mode(), ) remaining_properties.remove(dict_key) if throw_on_unhandled and len(remaining_properties) > 0: raise", "mode: {self}\") # pylint: disable=function-redefined def deserialize(class_reference, data, *, throw_on_unhandled:", "# pylint: disable=too-many-branches # pylint: disable=wildcard-import import enum import functools", "deserialize that # way. We do a mix of both.", "from deserialize.conversions import camel_case, pascal_case from deserialize.decorators import constructed, _call_constructed", "if new_reference is None: if _allows_downcast_fallback(class_reference): return _deserialize( Dict[Any, Any],", "deserialize '{type(data)}' to '{class_reference}' for '{debug_name}'\" ) # pylint:enable=too-many-return-statements def", "a straightforward dictionary parse first, or if it # has", "deserialize.decorators import parser, _get_parser from deserialize.decorators import auto_snake, _uses_auto_snake from", "-> Optional[Any]: \"\"\"Run through any finalization steps before returning the", "class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if not is_typing_type(class_reference)", "continue if _uses_auto_snake(class_reference) and attribute_name.lower() != attribute_name: raise DeserializeException( f\"When", "deserialization type: {class_reference} for {debug_name}\" ) # Whatever we have", "using_default: deserialized_value = _deserialize( attribute_type, property_value, f\"{debug_name}.{attribute_name}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), )", "= [] for index, item in enumerate(list_data): deserialized = _deserialize(", "deserialize.decorators import ignore, _should_ignore from deserialize.decorators import key, _get_key from", "f\"Cannot deserialize a list to '{class_reference}' for {debug_name}\" ) list_content_type_value", "must be snake cased. Error on: {debug_name}.{attribute_name}\" ) using_default =", "_uses_auto_snake(class_reference) and camel_case(property_key) in data: value = data[camel_case(property_key)] handled_fields.add(camel_case(property_key)) property_value", "throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) ) except DeserializeException as ex: exceptions.append(str(ex)) exception_message", "if self == RawStorageMode.all: return RawStorageMode.all raise DeserializeException(f\"Unexpected raw storage", "Dict, List, Optional, Union from deserialize.conversions import camel_case, pascal_case from", "enum_by_name: return finalize(enum_by_name) # pylint:enable=bare-except # This will be handled", "f\"Data was not dict for instance: {class_reference} for {debug_name}\" )", "throw_on_unhandled: bool, raw_storage_mode: RawStorageMode, ): if not isinstance(list_data, list): raise", ") remaining_properties.remove(dict_key) if throw_on_unhandled and len(remaining_properties) > 0: raise UnhandledFieldException(", "unexpected storage mode :returns: The child raw storage mode \"\"\"", "class_reference = new_reference class_instance = class_reference.__new__(class_reference) handled_fields = set() hints", "deserialized_value) unhandled = set(data.keys()) - handled_fields if throw_on_unhandled and len(unhandled)", "for {debug_name}.\" ) if not is_list(class_reference): raise DeserializeException( f\"Cannot deserialize", "as base raw data types\" ) if hasattr(class_reference, \"__name__\"): name", "( DeserializeException, InvalidBaseTypeException, NoDefaultSpecifiedException, UndefinedDowncastException, UnhandledFieldException, ) from deserialize.type_checks import", "and not isinstance(dict_key, key_type): raise DeserializeException( f\"Could not deserialize key", "typing import Any, Callable, Dict, List, Optional, Union from deserialize.conversions", "UnhandledFieldException( f\"The following field was unhandled: {list(remaining_properties)[0]} for {debug_name}\" )", "raise UnhandledFieldException( f\"The following field was unhandled: {list(remaining_properties)[0]} for {debug_name}\"", "we still have a type from the typing module, we", "= exception.split(\"\\n\") sub_message = f\"\\n\\t* {exception_lines[0]}\" for line in exception_lines[1:]:", "up iterating against it) if class_reference == type(None) and data", "return RawStorageMode.all raise DeserializeException(f\"Unexpected raw storage mode: {self}\") # pylint:", "correct, or invalid if isinstance(data, class_reference): return finalize(data) raise DeserializeException(", "_should_ignore(class_reference, attribute_name): continue property_key = _get_key(class_reference, attribute_name) parser_function = _get_parser(class_reference,", "For instance, if we only store the root node, then", "( f\"Cannot deserialize '{type(data)}' to '{class_reference}' for '{debug_name}' ->\" )", "the data, and try and determine the types and deserialize", "DeserializeException( f\"Could not deserialize {data} into {class_reference} due to lack", "type checks first, # then handle collection data, then any", "= \"all\" def child_mode(self) -> \"RawStorageMode\": \"\"\"Determine the mode for", "attribute_name) using_default = True else: if not is_union(attribute_type) or type(None)", "Whatever we have left now is either correct, or invalid", "{list(remaining_properties)[0]} for {debug_name}\" ) return result # It wasn't a", "This produces quite a complex interweaving of operations. The general", "raise DeserializeException( f\"When using auto_snake, all properties must be snake", "data will be stored in the attribute named: `__deserialize_raw__` \"\"\"", "{debug_name}\" ) list_content_type_value = list_content_type(class_reference, debug_name) output = [] for", "{debug_name}\" ) return result # It wasn't a straight forward", "throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) raise UndefinedDowncastException( f\"Could not find subclass of", "have a type from the typing module, we don't know", "class_reference, data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize", "straight forward dictionary, so we are in deserialize mode class_instance", "The other option is # to take the data, and", "applicable if raw_storage_mode in [RawStorageMode.root, RawStorageMode.all]: # We can't set", "wasn't a straight forward dictionary, so we are in deserialize", "finalize(data) # Check if it's None (since things like Union[int,", "if not is_typing_type(class_reference) and issubclass(class_reference, enum.Enum): try: return finalize(class_reference(data)) #", "then later, we can't go for a list directly to", "f\"Could not deserialize {data} into {class_reference} due to lack of", "downcast_field, _get_downcast_field, downcast_identifier, _get_downcast_class, allow_downcast_fallback, _allows_downcast_fallback, ) from deserialize.decorators import", "a significant amount of memory) all = \"all\" def child_mode(self)", "raw_storage_mode=raw_storage_mode.child_mode(), ) raise UndefinedDowncastException( f\"Could not find subclass of {class_reference}", "allow_unhandled, _should_allow_unhandled from deserialize.exceptions import ( DeserializeException, InvalidBaseTypeException, NoDefaultSpecifiedException, UndefinedDowncastException,", "import allow_unhandled, _should_allow_unhandled from deserialize.exceptions import ( DeserializeException, InvalidBaseTypeException, NoDefaultSpecifiedException,", "Any: return finalize(data) # Check if it's None (since things", "# Check if it's None (since things like Union[int, Optional[str]]", "type, so we have to go through each item in", "primitive types if hasattr(value, \"__dict__\"): setattr(value, \"__deserialize_raw__\", data) return value", "to do this. For the first, we can take the", "object.\"\"\" if not isinstance(data, dict) and not isinstance(data, list): raise", "child_mode(self) -> \"RawStorageMode\": \"\"\"Determine the mode for child parsing. When", "f\"The following field was unhandled: {list(remaining_properties)[0]} for {debug_name}\" ) return", "mode is set, the data will be stored in the", "raw data where applicable if raw_storage_mode in [RawStorageMode.root, RawStorageMode.all]: #", "if we have a type that got here. Optionals #", "raw_storage_mode=raw_storage_mode.child_mode(), ) output.append(deserialized) return output def _deserialize_dict( class_reference, data, debug_name,", "for dict_key, dict_value in data.items(): if key_type != Any and", "_get_downcast_class, allow_downcast_fallback, _allows_downcast_fallback, ) from deserialize.decorators import ignore, _should_ignore from", "if _allows_downcast_fallback(class_reference): return _deserialize( Dict[Any, Any], data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(),", "both. # # For example, we check if we have", "+= f\"\\n\\t{line}\" exception_message += sub_message raise DeserializeException(exception_message) if isinstance(data, dict):", "# We can't set attributes on primitive types if hasattr(value,", "list): raise DeserializeException( f\"Cannot deserialize '{type(list_data)}' as a list for", "things like Union[int, Optional[str]] become # Union[int, str, None] so", "else: if _has_default(class_reference, attribute_name): deserialized_value = _get_default(class_reference, attribute_name) using_default =", "f\"ClassVars cannot be set: {debug_name}.{attribute_name}\" ) continue if _uses_auto_snake(class_reference) and", "str, None] so we end up iterating against it) if", "Optional[Any]) -> Optional[Any]: \"\"\"Run through any finalization steps before returning", "and try and determine the types and deserialize that #", "to a Python object.\"\"\" if not isinstance(data, dict) and not", "list_content_type(class_reference, debug_name) output = [] for index, item in enumerate(list_data):", "doesn't # make any sense). But then later, we can't", "= f\"\\n\\t* {exception_lines[0]}\" for line in exception_lines[1:]: sub_message += f\"\\n\\t{line}\"", "so we have to go through each item in the", "as a list for {debug_name}.\" ) if not is_list(class_reference): raise", "above, so if we are here, it's a non-optional #", "exception_message = ( f\"Cannot deserialize '{type(data)}' to '{class_reference}' for '{debug_name}'", "\"\"\" if self == RawStorageMode.none: return RawStorageMode.none if self ==", "if property_key in data: raise DeserializeException( f\"ClassVars cannot be set:", "data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) raise UndefinedDowncastException( f\"Could not find", "Optional, Union from deserialize.conversions import camel_case, pascal_case from deserialize.decorators import", "auto_snake, all properties must be snake cased. Error on: {debug_name}.{attribute_name}\"", "pylint: disable=wildcard-import import enum import functools import typing from typing", "def _deserialize_dict( class_reference, data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode", "type from the typing module, we don't know how to", "to go through each item in the data, and iterate.", "= parser_function(None) if not using_default: deserialized_value = _deserialize( attribute_type, property_value,", "a store mode is set, the data will be stored", "_get_key(class_reference, attribute_name) parser_function = _get_parser(class_reference, property_key) if is_classvar(attribute_type): if property_key", "_should_allow_unhandled from deserialize.exceptions import ( DeserializeException, InvalidBaseTypeException, NoDefaultSpecifiedException, UndefinedDowncastException, UnhandledFieldException,", "# This produces quite a complex interweaving of operations. The", "= _get_downcast_class(class_reference, downcast_value) if new_reference is None: if _allows_downcast_fallback(class_reference): return", "import auto_snake, _uses_auto_snake from deserialize.decorators import allow_unhandled, _should_allow_unhandled from deserialize.exceptions", "Python object.\"\"\" if not isinstance(data, dict) and not isinstance(data, list):", "work is to try and do specific type checks first,", "== RawStorageMode.all: return RawStorageMode.all raise DeserializeException(f\"Unexpected raw storage mode: {self}\")", "disable=too-many-branches # pylint: disable=wildcard-import import enum import functools import typing", "way. We do a mix of both. # # For", "= list_content_type(class_reference, debug_name) output = [] for index, item in", "from deserialize.decorators import parser, _get_parser from deserialize.decorators import auto_snake, _uses_auto_snake", "to not be stored. :raises Exception: If we get an", "are not defined, do not deserialize return data key_type, value_type", "try and determine the types and deserialize that # way.", "do this. For the first, we can take the expected", "'{debug_name}' ->\" ) for exception in exceptions: exception_lines = exception.split(\"\\n\")", "interweaving of operations. The general # approach I've found to", "change mode in some cases. For instance, if we only", "= True else: if not is_union(attribute_type) or type(None) not in", "not find subclass of {class_reference} with downcast identifier '{downcast_value}' for", "try: return finalize(class_reference(data)) # pylint:disable=bare-except except: enum_by_name = getattr(class_reference, str(data),", "DeserializeException( f\"When using auto_snake, all properties must be snake cased.", "UndefinedDowncastException, UnhandledFieldException, ) from deserialize.type_checks import * class RawStorageMode(enum.Enum): \"\"\"The", "exception_message += sub_message raise DeserializeException(exception_message) if isinstance(data, dict): return finalize(", "we get an unexpected storage mode :returns: The child raw", "output = [] for index, item in enumerate(list_data): deserialized =", "f\"Unexpected missing value for: {debug_name}.{attribute_name}\" ) property_value = parser_function(None) if", "attribute_type, property_value, f\"{debug_name}.{attribute_name}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) setattr(class_instance, attribute_name, deserialized_value) unhandled", "if is_dict(class_reference): if class_reference is dict: # If types of", "f\"\\n\\t{line}\" exception_message += sub_message raise DeserializeException(exception_message) if isinstance(data, dict): return", "= parser_function(value) else: if _has_default(class_reference, attribute_name): deserialized_value = _get_default(class_reference, attribute_name)", "{class_reference} with downcast identifier '{downcast_value}' for {debug_name}\" ) class_reference =", "data: raise DeserializeException( f\"ClassVars cannot be set: {debug_name}.{attribute_name}\" ) continue", "{exception_lines[0]}\" for line in exception_lines[1:]: sub_message += f\"\\n\\t{line}\" exception_message +=", "if we are here, it's a non-optional # type and", "isinstance(data, dict): raise DeserializeException( f\"Data was not dict for instance:", "later, we can't go for a list directly to a", "some \"heuristics\" to deserialize. We have 2 main # options", "quite a complex interweaving of operations. The general # approach", "raw_storage_mode=raw_storage_mode.child_mode(), ) ) except DeserializeException as ex: exceptions.append(str(ex)) exception_message =", "or type(None) not in union_types( attribute_type, debug_name ): raise DeserializeException(", "{self}\") # pylint: disable=function-redefined def deserialize(class_reference, data, *, throw_on_unhandled: bool", ") for attribute_name, attribute_type in hints.items(): if _should_ignore(class_reference, attribute_name): continue", "_deserialize( list_content_type_value, item, f\"{debug_name}[{index}]\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) output.append(deserialized) return output", "use a significant amount of memory) all = \"all\" def", "= parser_function(value) elif _uses_auto_snake(class_reference) and camel_case(property_key) in data: value =", "any errors. The other option is # to take the", "is_dict(class_reference): if class_reference is dict: # If types of dictionary", "f\"Could not find subclass of {class_reference} with downcast identifier '{downcast_value}'", "type {key_type} for {debug_name}\" ) result[dict_key] = _deserialize( value_type, dict_value,", "False, raw_storage_mode: RawStorageMode = RawStorageMode.none): # type: ignore \"\"\"Deserialize data", "[RawStorageMode.root, RawStorageMode.all]: # We can't set attributes on primitive types", "will be stored in the attribute named: `__deserialize_raw__` \"\"\" #", "at the end pass # If we still have a", "end pass # If we still have a type from", "data[camel_case(property_key)] handled_fields.add(camel_case(property_key)) property_value = parser_function(value) elif _uses_auto_snake(class_reference) and pascal_case(property_key) in", "if raw_storage_mode in [RawStorageMode.root, RawStorageMode.all]: # We can't set attributes", "is_typing_type(class_reference) and issubclass(class_reference, enum.Enum): try: return finalize(class_reference(data)) # pylint:disable=bare-except except:", "disable=function-redefined def deserialize(class_reference, data, *, throw_on_unhandled: bool = False, raw_storage_mode:", "afterwards. That's not # set in stone though. def finalize(value:", "f\"When using auto_snake, all properties must be snake cased. Error", "it) if class_reference == type(None) and data is None: return", "throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if not is_typing_type(class_reference) and issubclass(class_reference, enum.Enum):", "None type first and return # early, since we can't", "# If types of dictionary entries are not defined, do", "*, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode, ): if not isinstance(list_data, list):", "through any finalization steps before returning the value.\"\"\" # Set", "first, or if it # has to be deserialized remaining_properties", "if len(hints) == 0: raise DeserializeException( f\"Could not deserialize {data}", "mode :returns: The child raw storage mode \"\"\" if self", "still have a type from the typing module, we don't", "data[pascal_case(property_key)] handled_fields.add(pascal_case(property_key)) property_value = parser_function(value) else: if _has_default(class_reference, attribute_name): deserialized_value", "attribute_name): deserialized_value = _get_default(class_reference, attribute_name) using_default = True else: if", "deserialize '{type(data)}' to '{class_reference}' for '{debug_name}' ->\" ) for exception", "type that got here. Optionals # are handled by unions", "use some \"heuristics\" to deserialize. We have 2 main #", "if isinstance(data, dict): return finalize( _deserialize_dict( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled,", "# pylint: disable=protected-access # pylint: disable=too-many-branches # pylint: disable=wildcard-import import", "data[property_key] handled_fields.add(property_key) property_value = parser_function(value) elif _uses_auto_snake(class_reference) and camel_case(property_key) in", "{} for dict_key, dict_value in data.items(): if key_type != Any", "have a type that got here. Optionals # are handled", "return _deserialize( Dict[Any, Any], data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) raise", ":returns: The child raw storage mode \"\"\" if self ==", "child parsing. When we move to the next child iteration,", "exceptions.append(str(ex)) exception_message = ( f\"Cannot deserialize '{type(data)}' to '{class_reference}' for", "is_union(class_reference): valid_types = union_types(class_reference, debug_name) exceptions = [] for valid_type", "\"\"\"Determine the mode for child parsing. When we move to", "dict_value, f\"{debug_name}.{dict_key}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) remaining_properties.remove(dict_key) if throw_on_unhandled and len(remaining_properties)", "= typing.get_type_hints(class_reference) if len(hints) == 0: raise DeserializeException( f\"Could not", "if not isinstance(list_data, list): raise DeserializeException( f\"Cannot deserialize '{type(list_data)}' as", "parser_function(None) if not using_default: deserialized_value = _deserialize( attribute_type, property_value, f\"{debug_name}.{attribute_name}\",", "then handle collection data, then any other types afterwards. That's", "handled_fields.add(camel_case(property_key)) property_value = parser_function(value) elif _uses_auto_snake(class_reference) and pascal_case(property_key) in data:", "to be deserialized remaining_properties = set(data.keys()) if not isinstance(data, dict):", "_call_constructed from deserialize.decorators import default, _get_default, _has_default from deserialize.decorators import", "complex interweaving of operations. The general # approach I've found", "check if we have an any type or None type", "pylint: disable=protected-access # pylint: disable=too-many-branches # pylint: disable=wildcard-import import enum", "def _deserialize_list( class_reference, list_data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode,", "objects (WARNING: This can use a significant amount of memory)", "for attribute_name, attribute_type in hints.items(): if _should_ignore(class_reference, attribute_name): continue property_key", "dictionary, so we are in deserialize mode class_instance = None", "attribute_name, deserialized_value) unhandled = set(data.keys()) - handled_fields if throw_on_unhandled and", "ignore \"\"\"Deserialize data to a Python object.\"\"\" if not isinstance(data,", "# are handled by unions above, so if we are", "we are in deserialize mode class_instance = None class_reference_downcast_field =", "elif _uses_auto_snake(class_reference) and pascal_case(property_key) in data: value = data[pascal_case(property_key)] handled_fields.add(pascal_case(property_key))", "valid_type, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) ) except DeserializeException as", "got here. Optionals # are handled by unions above, so", "not be None. if data is None: raise DeserializeException( f\"No", "for '{debug_name}'. Expected value of type '{class_reference}'\" ) raise DeserializeException(", "_deserialize_list( class_reference, list_data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode, ):", "= getattr(class_reference, str(data), None) if enum_by_name: return finalize(enum_by_name) # pylint:enable=bare-except", "to a Python object.\"\"\" # Check if we are doing", ") if isinstance(data, list): return finalize( _deserialize_list( class_reference, data, debug_name,", "raise DeserializeException(exception_message) if isinstance(data, dict): return finalize( _deserialize_dict( class_reference, data,", "Check if we are doing a straightforward dictionary parse first,", "for deserializing data to Python objects.\"\"\" # pylint: disable=unidiomatic-typecheck #", "{dict_key} to type {key_type} for {debug_name}\" ) result[dict_key] = _deserialize(", "import key, _get_key from deserialize.decorators import parser, _get_parser from deserialize.decorators", "'{type(data)}' to '{class_reference}' for '{debug_name}'\" ) # pylint:enable=too-many-return-statements def _deserialize_list(", "# Do not store the raw data at all none", "value_type = dict_content_types(class_reference, debug_name) result = {} for dict_key, dict_value", "RawStorageMode(enum.Enum): \"\"\"The storage mode for the raw data on each", "isinstance(data, list): raise InvalidBaseTypeException( \"Only lists and dictionaries are supported", "import camel_case, pascal_case from deserialize.decorators import constructed, _call_constructed from deserialize.decorators", "data, *, throw_on_unhandled: bool = False, raw_storage_mode: RawStorageMode = RawStorageMode.none):", ") return result # It wasn't a straight forward dictionary,", "if property_key in data: value = data[property_key] handled_fields.add(property_key) property_value =", "data: value = data[property_key] handled_fields.add(property_key) property_value = parser_function(value) elif _uses_auto_snake(class_reference)", "_get_default, _has_default from deserialize.decorators import ( downcast_field, _get_downcast_field, downcast_identifier, _get_downcast_class,", "store mode is set, the data will be stored in", "on the root node root = \"root\" # Store on", "not is_list(class_reference): raise DeserializeException( f\"Cannot deserialize a list to '{class_reference}'", "debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode, ): if not isinstance(list_data,", "type(None) not in union_types( attribute_type, debug_name ): raise DeserializeException( f\"Unexpected", "raw data types\" ) if hasattr(class_reference, \"__name__\"): name = class_reference.__name__", ") except DeserializeException as ex: exceptions.append(str(ex)) exception_message = ( f\"Cannot", "result # It wasn't a straight forward dictionary, so we", "deserialize {data} into {class_reference} due to lack of type hints", "not using_default: deserialized_value = _deserialize( attribute_type, property_value, f\"{debug_name}.{attribute_name}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(),", "2 main # options to do this. For the first,", "value = data[camel_case(property_key)] handled_fields.add(camel_case(property_key)) property_value = parser_function(value) elif _uses_auto_snake(class_reference) and", "Python object, but allow base types\"\"\" # In here we", "deserialized_value = _deserialize( attribute_type, property_value, f\"{debug_name}.{attribute_name}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) setattr(class_instance,", "f\"Cannot deserialize '{type(data)}' to '{class_reference}' for '{debug_name}'\" ) # pylint:enable=too-many-return-statements", "was not dict for instance: {class_reference} for {debug_name}\" ) if", "we end up iterating against it) if class_reference == type(None)", "can't deserialize directly to those (since that doesn't # make", "of memory) all = \"all\" def child_mode(self) -> \"RawStorageMode\": \"\"\"Determine", "type: {class_reference} for {debug_name}\" ) # Whatever we have left", "to try and do specific type checks first, # then", "not isinstance(data, list): raise InvalidBaseTypeException( \"Only lists and dictionaries are", "\"\"\"Run through any finalization steps before returning the value.\"\"\" #", "for {debug_name}\" ) return result # It wasn't a straight", "We do a mix of both. # # For example,", "forward dictionary, so we are in deserialize mode class_instance =", "= _get_default(class_reference, attribute_name) using_default = True else: if not is_union(attribute_type)", "type: ignore \"\"\"Deserialize data to a Python object.\"\"\" if not", "auto_snake, _uses_auto_snake from deserialize.decorators import allow_unhandled, _should_allow_unhandled from deserialize.exceptions import", "be snake cased. Error on: {debug_name}.{attribute_name}\" ) using_default = False", "data.items(): if key_type != Any and not isinstance(dict_key, key_type): raise", "dict): return finalize( _deserialize_dict( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, )", "is None: if _allows_downcast_fallback(class_reference): return _deserialize( Dict[Any, Any], data, debug_name,", "enum_by_name = getattr(class_reference, str(data), None) if enum_by_name: return finalize(enum_by_name) #", "line in exception_lines[1:]: sub_message += f\"\\n\\t{line}\" exception_message += sub_message raise", "_deserialize( Dict[Any, Any], data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) raise UndefinedDowncastException(", "named: `__deserialize_raw__` \"\"\" # Do not store the raw data", "None: if _allows_downcast_fallback(class_reference): return _deserialize( Dict[Any, Any], data, debug_name, throw_on_unhandled=throw_on_unhandled,", "_uses_auto_snake from deserialize.decorators import allow_unhandled, _should_allow_unhandled from deserialize.exceptions import (", "attributes on primitive types if hasattr(value, \"__dict__\"): setattr(value, \"__deserialize_raw__\", data)", "of type '{class_reference}'\" ) raise DeserializeException( f\"Unsupported deserialization type: {class_reference}", "if _uses_auto_snake(class_reference) and attribute_name.lower() != attribute_name: raise DeserializeException( f\"When using", "RawStorageMode.all]: # We can't set attributes on primitive types if", "downcast_identifier, _get_downcast_class, allow_downcast_fallback, _allows_downcast_fallback, ) from deserialize.decorators import ignore, _should_ignore", "list): raise InvalidBaseTypeException( \"Only lists and dictionaries are supported as", "When we move to the next child iteration, we need", "data where applicable if raw_storage_mode in [RawStorageMode.root, RawStorageMode.all]: # We", "for a list directly to a # type, so we", "deserialize a list to '{class_reference}' for {debug_name}\" ) list_content_type_value =", "are here, it's a non-optional # type and therefore should", "here. Optionals # are handled by unions above, so if", "other types afterwards. That's not # set in stone though.", "operations. The general # approach I've found to work is", "= set(data.keys()) if not isinstance(data, dict): raise DeserializeException( f\"Data was", "unhandled if not _should_allow_unhandled(class_reference, key) ] if len(filtered_unhandled) > 0:", "throw_on_unhandled and len(unhandled) > 0: filtered_unhandled = [ key for", "DeserializeException( f\"Cannot deserialize a list to '{class_reference}' for {debug_name}\" )", "checks first, # then handle collection data, then any other", "the expected type and try # and deserialize the data", "each item in the data, and iterate. # # This", "in exceptions: exception_lines = exception.split(\"\\n\") sub_message = f\"\\n\\t* {exception_lines[0]}\" for", "in deserialize mode class_instance = None class_reference_downcast_field = _get_downcast_field(class_reference) if", "and deserialize the data to that and show any errors.", "issubclass(class_reference, enum.Enum): try: return finalize(class_reference(data)) # pylint:disable=bare-except except: enum_by_name =", "return result # It wasn't a straight forward dictionary, so", "remaining_properties = set(data.keys()) if not isinstance(data, dict): raise DeserializeException( f\"Data", "if is_union(class_reference): valid_types = union_types(class_reference, debug_name) exceptions = [] for", "and deserialize that # way. We do a mix of", "a type that got here. Optionals # are handled by", "= class_reference.__name__ else: name = str(class_reference) return _deserialize( class_reference, data,", "data, and try and determine the types and deserialize that", "raise DeserializeException( f\"Data was not dict for instance: {class_reference} for", "and data is None: return finalize(None) if is_union(class_reference): valid_types =", "The data should not be None if we have a", "set attributes on primitive types if hasattr(value, \"__dict__\"): setattr(value, \"__deserialize_raw__\",", "# pylint: enable=function-redefined # pylint:disable=too-many-return-statements def _deserialize( class_reference, data, debug_name,", "return finalize( _deserialize_list( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) )", "any type or None type first and return # early,", "import ( downcast_field, _get_downcast_field, downcast_identifier, _get_downcast_class, allow_downcast_fallback, _allows_downcast_fallback, ) from", "= [ key for key in unhandled if not _should_allow_unhandled(class_reference,", "== 0: raise DeserializeException( f\"Could not deserialize {data} into {class_reference}", "_uses_auto_snake(class_reference) and attribute_name.lower() != attribute_name: raise DeserializeException( f\"When using auto_snake,", "we are doing a straightforward dictionary parse first, or if", "not deserialize {data} into {class_reference} due to lack of type", "== Any: return finalize(data) # Check if it's None (since", "class RawStorageMode(enum.Enum): \"\"\"The storage mode for the raw data on", "base types\"\"\" # In here we try and use some", "return finalize( _deserialize_dict( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) )", "raw_storage_mode: RawStorageMode ): \"\"\"Deserialize a dictionary to a Python object.\"\"\"", "bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize a dictionary to a Python", ") if is_dict(class_reference): if class_reference is dict: # If types", "parse first, or if it # has to be deserialized", "for {debug_name}\" ) list_content_type_value = list_content_type(class_reference, debug_name) output = []", "data on the root node root = \"root\" # Store", "raw storage mode \"\"\" if self == RawStorageMode.none: return RawStorageMode.none", "RawStorageMode.none if self == RawStorageMode.all: return RawStorageMode.all raise DeserializeException(f\"Unexpected raw", "ignore, _should_ignore from deserialize.decorators import key, _get_key from deserialize.decorators import", "If a store mode is set, the data will be", "and len(unhandled) > 0: filtered_unhandled = [ key for key", ") setattr(class_instance, attribute_name, deserialized_value) unhandled = set(data.keys()) - handled_fields if", "we have a type that got here. Optionals # are", "!= attribute_name: raise DeserializeException( f\"When using auto_snake, all properties must", "found to work is to try and do specific type", "setattr(class_instance, attribute_name, deserialized_value) unhandled = set(data.keys()) - handled_fields if throw_on_unhandled", "if class_reference == Any: return finalize(data) # Check if it's", "Python object.\"\"\" # Check if we are doing a straightforward", "not store the raw data at all none = \"none\"", "disable=wildcard-import import enum import functools import typing from typing import", "str(class_reference) return _deserialize( class_reference, data, name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) #", "is None: raise DeserializeException( f\"No value for '{debug_name}'. Expected value", "will be handled at the end pass # If we", "so we end up iterating against it) if class_reference ==", "valid_types = union_types(class_reference, debug_name) exceptions = [] for valid_type in", "setattr(value, \"__deserialize_raw__\", data) return value if class_reference == Any: return", "of operations. The general # approach I've found to work", "dictionary to a Python object.\"\"\" # Check if we are", "# early, since we can't deserialize directly to those (since", "dict_content_types(class_reference, debug_name) result = {} for dict_key, dict_value in data.items():", "a list to '{class_reference}' for {debug_name}\" ) list_content_type_value = list_content_type(class_reference,", "have to go through each item in the data, and", "where applicable if raw_storage_mode in [RawStorageMode.root, RawStorageMode.all]: # We can't", "is_list(class_reference): raise DeserializeException( f\"Cannot deserialize a list to '{class_reference}' for", "_should_ignore from deserialize.decorators import key, _get_key from deserialize.decorators import parser,", "first and return # early, since we can't deserialize directly", "data to Python objects.\"\"\" # pylint: disable=unidiomatic-typecheck # pylint: disable=protected-access", "raise DeserializeException( f\"Cannot deserialize a list to '{class_reference}' for {debug_name}\"", "key_type != Any and not isinstance(dict_key, key_type): raise DeserializeException( f\"Could", "data on each object. If a store mode is set,", "collection data, then any other types afterwards. That's not #", "the typing module, we don't know how to # handle", "types\" ) if hasattr(class_reference, \"__name__\"): name = class_reference.__name__ else: name", "finalize(enum_by_name) # pylint:enable=bare-except # This will be handled at the", "isinstance(data, class_reference): return finalize(data) raise DeserializeException( f\"Cannot deserialize '{type(data)}' to", "exceptions: exception_lines = exception.split(\"\\n\") sub_message = f\"\\n\\t* {exception_lines[0]}\" for line", "mix of both. # # For example, we check if", "that doesn't # make any sense). But then later, we", "we can't deserialize directly to those (since that doesn't #", "subclass of {class_reference} with downcast identifier '{downcast_value}' for {debug_name}\" )", "else: name = str(class_reference) return _deserialize( class_reference, data, name, throw_on_unhandled=throw_on_unhandled,", "since we can't deserialize directly to those (since that doesn't", "find subclass of {class_reference} with downcast identifier '{downcast_value}' for {debug_name}\"", "attribute_name: raise DeserializeException( f\"When using auto_snake, all properties must be", "*, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode ): \"\"\"Deserialize a dictionary to", "import Any, Callable, Dict, List, Optional, Union from deserialize.conversions import", "= _deserialize( attribute_type, property_value, f\"{debug_name}.{attribute_name}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) setattr(class_instance, attribute_name,", "storage mode: {self}\") # pylint: disable=function-redefined def deserialize(class_reference, data, *,", "_has_default from deserialize.decorators import ( downcast_field, _get_downcast_field, downcast_identifier, _get_downcast_class, allow_downcast_fallback,", "iteration, we need to change mode in some cases. For", "data at all none = \"none\" # Only store the", "deserialize directly to those (since that doesn't # make any", ") output.append(deserialized) return output def _deserialize_dict( class_reference, data, debug_name, *,", "result = {} for dict_key, dict_value in data.items(): if key_type", "0: raise UnhandledFieldException( f\"Unhandled field: {list(filtered_unhandled)[0]} for {debug_name}\" ) _call_constructed(class_reference,", "key in unhandled if not _should_allow_unhandled(class_reference, key) ] if len(filtered_unhandled)", "camel_case, pascal_case from deserialize.decorators import constructed, _call_constructed from deserialize.decorators import", "only store the root node, then we need to set", "= False, raw_storage_mode: RawStorageMode = RawStorageMode.none): # type: ignore \"\"\"Deserialize", "a complex interweaving of operations. The general # approach I've", "exception.split(\"\\n\") sub_message = f\"\\n\\t* {exception_lines[0]}\" for line in exception_lines[1:]: sub_message", "= {} for dict_key, dict_value in data.items(): if key_type !=", "str(data), None) if enum_by_name: return finalize(enum_by_name) # pylint:enable=bare-except # This", "debug_name) output = [] for index, item in enumerate(list_data): deserialized", "= parser_function(value) elif _uses_auto_snake(class_reference) and pascal_case(property_key) in data: value =", "mode in some cases. For instance, if we only store", "we move to the next child iteration, we need to", "all = \"all\" def child_mode(self) -> \"RawStorageMode\": \"\"\"Determine the mode", "is_classvar(attribute_type): if property_key in data: raise DeserializeException( f\"ClassVars cannot be", "are handled by unions above, so if we are here,", "as ex: exceptions.append(str(ex)) exception_message = ( f\"Cannot deserialize '{type(data)}' to", "list_data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode, ): if not", "errors. The other option is # to take the data,", "we have an any type or None type first and", "due to lack of type hints ({debug_name})\" ) for attribute_name,", "= data[class_reference_downcast_field] new_reference = _get_downcast_class(class_reference, downcast_value) if new_reference is None:", "for {debug_name}\" ) class_reference = new_reference class_instance = class_reference.__new__(class_reference) handled_fields", "approach I've found to work is to try and do", "pascal_case(property_key) in data: value = data[pascal_case(property_key)] handled_fields.add(pascal_case(property_key)) property_value = parser_function(value)", "to '{class_reference}' for '{debug_name}'\" ) # pylint:enable=too-many-return-statements def _deserialize_list( class_reference,", "pass # If we still have a type from the", "invalid if isinstance(data, class_reference): return finalize(data) raise DeserializeException( f\"Cannot deserialize", "list to '{class_reference}' for {debug_name}\" ) list_content_type_value = list_content_type(class_reference, debug_name)", "bool = False, raw_storage_mode: RawStorageMode = RawStorageMode.none): # type: ignore", "f\"Could not deserialize key {dict_key} to type {key_type} for {debug_name}\"", "property_value = parser_function(None) if not using_default: deserialized_value = _deserialize( attribute_type,", "typing.get_type_hints(class_reference) if len(hints) == 0: raise DeserializeException( f\"Could not deserialize", "from deserialize.decorators import constructed, _call_constructed from deserialize.decorators import default, _get_default,", "next child iteration, we need to change mode in some", "{debug_name}.{attribute_name}\" ) continue if _uses_auto_snake(class_reference) and attribute_name.lower() != attribute_name: raise", "Exception: If we get an unexpected storage mode :returns: The", "if len(filtered_unhandled) > 0: raise UnhandledFieldException( f\"Unhandled field: {list(filtered_unhandled)[0]} for", "debug_name) result = {} for dict_key, dict_value in data.items(): if", "data is None: raise DeserializeException( f\"No value for '{debug_name}'. Expected", "[] for valid_type in valid_types: try: return finalize( _deserialize( valid_type,", "set() hints = typing.get_type_hints(class_reference) if len(hints) == 0: raise DeserializeException(", "value_type, dict_value, f\"{debug_name}.{dict_key}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) remaining_properties.remove(dict_key) if throw_on_unhandled and", "'{debug_name}'. Expected value of type '{class_reference}'\" ) raise DeserializeException( f\"Unsupported", "deserialize the data to that and show any errors. The", "set all the children to not be stored. :raises Exception:", "return value if class_reference == Any: return finalize(data) # Check", "root = \"root\" # Store on all objects (WARNING: This", "to '{class_reference}' for {debug_name}\" ) list_content_type_value = list_content_type(class_reference, debug_name) output", "Do not store the raw data at all none =", "new_reference = _get_downcast_class(class_reference, downcast_value) if new_reference is None: if _allows_downcast_fallback(class_reference):", "return finalize(None) if is_union(class_reference): valid_types = union_types(class_reference, debug_name) exceptions =", "class_reference == Any: return finalize(data) # Check if it's None", "UnhandledFieldException( f\"Unhandled field: {list(filtered_unhandled)[0]} for {debug_name}\" ) _call_constructed(class_reference, class_instance) return", ") continue if _uses_auto_snake(class_reference) and attribute_name.lower() != attribute_name: raise DeserializeException(", "deserializing data to Python objects.\"\"\" # pylint: disable=unidiomatic-typecheck # pylint:", "like Union[int, Optional[str]] become # Union[int, str, None] so we", "return finalize( _deserialize( valid_type, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) )", "\"\"\"Deserialize a dictionary to a Python object.\"\"\" # Check if", "stored. :raises Exception: If we get an unexpected storage mode", "type '{class_reference}'\" ) raise DeserializeException( f\"Unsupported deserialization type: {class_reference} for", "raw data at all none = \"none\" # Only store", "key for key in unhandled if not _should_allow_unhandled(class_reference, key) ]", "data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if isinstance(data, list): return", "= _get_downcast_field(class_reference) if class_reference_downcast_field: downcast_value = data[class_reference_downcast_field] new_reference = _get_downcast_class(class_reference,", "property_value = parser_function(value) elif _uses_auto_snake(class_reference) and camel_case(property_key) in data: value", "= class_reference.__new__(class_reference) handled_fields = set() hints = typing.get_type_hints(class_reference) if len(hints)", ") from deserialize.decorators import ignore, _should_ignore from deserialize.decorators import key,", "throw_on_unhandled: bool = False, raw_storage_mode: RawStorageMode = RawStorageMode.none): # type:", "object, but allow base types\"\"\" # In here we try", "not # set in stone though. def finalize(value: Optional[Any]) ->", "take the expected type and try # and deserialize the", "{class_reference} for {debug_name}\" ) if is_dict(class_reference): if class_reference is dict:", "InvalidBaseTypeException, NoDefaultSpecifiedException, UndefinedDowncastException, UnhandledFieldException, ) from deserialize.type_checks import * class", "pascal_case from deserialize.decorators import constructed, _call_constructed from deserialize.decorators import default,", "if throw_on_unhandled and len(unhandled) > 0: filtered_unhandled = [ key", "pylint: disable=function-redefined def deserialize(class_reference, data, *, throw_on_unhandled: bool = False,", "if it # has to be deserialized remaining_properties = set(data.keys())", "handled_fields.add(pascal_case(property_key)) property_value = parser_function(value) else: if _has_default(class_reference, attribute_name): deserialized_value =", "): if not isinstance(list_data, list): raise DeserializeException( f\"Cannot deserialize '{type(list_data)}'", "is_union(attribute_type) or type(None) not in union_types( attribute_type, debug_name ): raise", "types\"\"\" # In here we try and use some \"heuristics\"", "a Python object, but allow base types\"\"\" # In here", "a dictionary to a Python object.\"\"\" # Check if we", "go for a list directly to a # type, so", "key_type): raise DeserializeException( f\"Could not deserialize key {dict_key} to type", "stone though. def finalize(value: Optional[Any]) -> Optional[Any]: \"\"\"Run through any", "def deserialize(class_reference, data, *, throw_on_unhandled: bool = False, raw_storage_mode: RawStorageMode", "list_content_type_value, item, f\"{debug_name}[{index}]\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) output.append(deserialized) return output def", "parser_function(value) else: if _has_default(class_reference, attribute_name): deserialized_value = _get_default(class_reference, attribute_name) using_default", "deserialize.decorators import key, _get_key from deserialize.decorators import parser, _get_parser from", "return finalize(enum_by_name) # pylint:enable=bare-except # This will be handled at", "sub_message = f\"\\n\\t* {exception_lines[0]}\" for line in exception_lines[1:]: sub_message +=", "Set raw data where applicable if raw_storage_mode in [RawStorageMode.root, RawStorageMode.all]:", "set: {debug_name}.{attribute_name}\" ) continue if _uses_auto_snake(class_reference) and attribute_name.lower() != attribute_name:", "else: if not is_union(attribute_type) or type(None) not in union_types( attribute_type,", "following field was unhandled: {list(remaining_properties)[0]} for {debug_name}\" ) return result", "mode \"\"\" if self == RawStorageMode.none: return RawStorageMode.none if self", "a # type, so we have to go through each", "expected type and try # and deserialize the data to", "some cases. For instance, if we only store the root", "is set, the data will be stored in the attribute", "(since that doesn't # make any sense). But then later,", "Callable, Dict, List, Optional, Union from deserialize.conversions import camel_case, pascal_case", "We have 2 main # options to do this. For", "key, _get_key from deserialize.decorators import parser, _get_parser from deserialize.decorators import", "If we still have a type from the typing module,", "list_content_type_value = list_content_type(class_reference, debug_name) output = [] for index, item", "handled_fields = set() hints = typing.get_type_hints(class_reference) if len(hints) == 0:", ") ) if not is_typing_type(class_reference) and issubclass(class_reference, enum.Enum): try: return", "if isinstance(data, class_reference): return finalize(data) raise DeserializeException( f\"Cannot deserialize '{type(data)}'", "# pylint: disable=function-redefined def deserialize(class_reference, data, *, throw_on_unhandled: bool =", "\"RawStorageMode\": \"\"\"Determine the mode for child parsing. When we move", "value.\"\"\" # Set raw data where applicable if raw_storage_mode in", "if class_reference_downcast_field: downcast_value = data[class_reference_downcast_field] new_reference = _get_downcast_class(class_reference, downcast_value) if", "lists and dictionaries are supported as base raw data types\"", "type(None) and data is None: return finalize(None) if is_union(class_reference): valid_types", "# pylint:enable=bare-except # This will be handled at the end", "typing module, we don't know how to # handle it", "class_reference_downcast_field: downcast_value = data[class_reference_downcast_field] new_reference = _get_downcast_class(class_reference, downcast_value) if new_reference", "But then later, we can't go for a list directly", "first, # then handle collection data, then any other types", "throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if isinstance(data, list): return finalize( _deserialize_list(", "# It wasn't a straight forward dictionary, so we are", "and do specific type checks first, # then handle collection", "become # Union[int, str, None] so we end up iterating", "and determine the types and deserialize that # way. We", "isinstance(data, list): return finalize( _deserialize_list( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode,", "on primitive types if hasattr(value, \"__dict__\"): setattr(value, \"__deserialize_raw__\", data) return", "typing from typing import Any, Callable, Dict, List, Optional, Union", "in the attribute named: `__deserialize_raw__` \"\"\" # Do not store", "# If we still have a type from the typing", "key_type, value_type = dict_content_types(class_reference, debug_name) result = {} for dict_key,", "raise UndefinedDowncastException( f\"Could not find subclass of {class_reference} with downcast", "# For example, we check if we have an any", "return finalize(data) raise DeserializeException( f\"Cannot deserialize '{type(data)}' to '{class_reference}' for", "not be stored. :raises Exception: If we get an unexpected", "_deserialize_dict( class_reference, data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if isinstance(data,", "len(remaining_properties) > 0: raise UnhandledFieldException( f\"The following field was unhandled:", "raise DeserializeException(f\"Unexpected raw storage mode: {self}\") # pylint: disable=function-redefined def", "False if property_key in data: value = data[property_key] handled_fields.add(property_key) property_value", "not _should_allow_unhandled(class_reference, key) ] if len(filtered_unhandled) > 0: raise UnhandledFieldException(", "for key in unhandled if not _should_allow_unhandled(class_reference, key) ] if", "be stored in the attribute named: `__deserialize_raw__` \"\"\" # Do", "returning the value.\"\"\" # Set raw data where applicable if", "f\"Unsupported deserialization type: {class_reference} for {debug_name}\" ) # Whatever we", "this. For the first, we can take the expected type", "That's not # set in stone though. def finalize(value: Optional[Any])", "from deserialize.exceptions import ( DeserializeException, InvalidBaseTypeException, NoDefaultSpecifiedException, UndefinedDowncastException, UnhandledFieldException, )", "pylint:disable=too-many-return-statements def _deserialize( class_reference, data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode:", "data) return value if class_reference == Any: return finalize(data) #", "value = data[pascal_case(property_key)] handled_fields.add(pascal_case(property_key)) property_value = parser_function(value) else: if _has_default(class_reference,", "we are here, it's a non-optional # type and therefore", "# This will be handled at the end pass #", "either correct, or invalid if isinstance(data, class_reference): return finalize(data) raise", "( downcast_field, _get_downcast_field, downcast_identifier, _get_downcast_class, allow_downcast_fallback, _allows_downcast_fallback, ) from deserialize.decorators", "handled_fields.add(property_key) property_value = parser_function(value) elif _uses_auto_snake(class_reference) and camel_case(property_key) in data:", "deserialize.decorators import allow_unhandled, _should_allow_unhandled from deserialize.exceptions import ( DeserializeException, InvalidBaseTypeException,", "_deserialize( value_type, dict_value, f\"{debug_name}.{dict_key}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) remaining_properties.remove(dict_key) if throw_on_unhandled", "attribute named: `__deserialize_raw__` \"\"\" # Do not store the raw", "data: value = data[pascal_case(property_key)] handled_fields.add(pascal_case(property_key)) property_value = parser_function(value) else: if", "if not _should_allow_unhandled(class_reference, key) ] if len(filtered_unhandled) > 0: raise", "type or None type first and return # early, since", "finalize(class_reference(data)) # pylint:disable=bare-except except: enum_by_name = getattr(class_reference, str(data), None) if", "= set(data.keys()) - handled_fields if throw_on_unhandled and len(unhandled) > 0:", "the raw data at all none = \"none\" # Only", "in exception_lines[1:]: sub_message += f\"\\n\\t{line}\" exception_message += sub_message raise DeserializeException(exception_message)", "property_value, f\"{debug_name}.{attribute_name}\", throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) setattr(class_instance, attribute_name, deserialized_value) unhandled =", "data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, ) ) if not is_typing_type(class_reference) and", "({debug_name})\" ) for attribute_name, attribute_type in hints.items(): if _should_ignore(class_reference, attribute_name):", "elif _uses_auto_snake(class_reference) and camel_case(property_key) in data: value = data[camel_case(property_key)] handled_fields.add(camel_case(property_key))", "deserialize.decorators import ( downcast_field, _get_downcast_field, downcast_identifier, _get_downcast_class, allow_downcast_fallback, _allows_downcast_fallback, )", "value if class_reference == Any: return finalize(data) # Check if", "property_value = parser_function(value) elif _uses_auto_snake(class_reference) and pascal_case(property_key) in data: value", "+= sub_message raise DeserializeException(exception_message) if isinstance(data, dict): return finalize( _deserialize_dict(", "of {class_reference} with downcast identifier '{downcast_value}' for {debug_name}\" ) class_reference", "raise DeserializeException( f\"Could not deserialize {data} into {class_reference} due to", "# way. We do a mix of both. # #", "return finalize(data) # Check if it's None (since things like", "deserialize key {dict_key} to type {key_type} for {debug_name}\" ) result[dict_key]", "and dictionaries are supported as base raw data types\" )", "Any], data, debug_name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode.child_mode(), ) raise UndefinedDowncastException( f\"Could not", "= str(class_reference) return _deserialize( class_reference, data, name, throw_on_unhandled=throw_on_unhandled, raw_storage_mode=raw_storage_mode, )", "= ( f\"Cannot deserialize '{type(data)}' to '{class_reference}' for '{debug_name}' ->\"", "for child parsing. When we move to the next child", "using auto_snake, all properties must be snake cased. Error on:", "from deserialize.decorators import ( downcast_field, _get_downcast_field, downcast_identifier, _get_downcast_class, allow_downcast_fallback, _allows_downcast_fallback,", "storage mode \"\"\" if self == RawStorageMode.none: return RawStorageMode.none if", "hints ({debug_name})\" ) for attribute_name, attribute_type in hints.items(): if _should_ignore(class_reference,", "= data[pascal_case(property_key)] handled_fields.add(pascal_case(property_key)) property_value = parser_function(value) else: if _has_default(class_reference, attribute_name):", "raise DeserializeException( f\"No value for '{debug_name}'. Expected value of type", "# approach I've found to work is to try and", "def child_mode(self) -> \"RawStorageMode\": \"\"\"Determine the mode for child parsing.", "List, Optional, Union from deserialize.conversions import camel_case, pascal_case from deserialize.decorators", "we can take the expected type and try # and" ]
[ "dddd', '10/4/2020') == 'SU SUN' assert ssf.format('ddd dddd', '10/5/2020') ==", "'10/5/2020') == 'MO MON' assert ssf.format('ddd dddd', '10/6/2020') == 'TU", "pass try: ssf.set_day_names((1, 2, 3, 4, 5, 6, 7)) assert", "3, 4, 5, 6, 7)) assert False # Failed except", "tuple) assert mn == (None, ('J', 'Jan', 'January'), ('F', 'Feb',", "assert isinstance(dn, tuple) assert dn == (('Mon', 'Monday'), ('Tue', 'Tuesday'),", "('M', 'May', 'May'), ('J', 'Jun', 'June'), ('J', 'Jul', 'July'), ('A',", "'0' assert t[14] == 'm/d/yyyy' assert t[49] == '@' ssf.load_table({104:'yyyy-mm-dd',", "assert ssf.format('mmmmm mmm mmmm', '12/3/2020') == 'X DE DEC' try:", "1 assert ssf.load('mmm mmmm') == 5 # Will be inserted", "mmm mmmm', '12/3/2020') == 'X DE DEC' try: ssf.set_month_names(2) assert", "assert ssf.format('ddd dddd', '10/7/2020') == 'WE WED' assert ssf.format('ddd dddd',", "False # Failed except ValueError: pass def test_get_set_months(): mn =", "== (None, ('J', 'Jan', 'January'), ('F', 'Feb', 'February'), ('M', 'Mar',", "Will be inserted at 5 assert ssf.load('@') == 49 assert", "'FR FRI' try: ssf.set_day_names(2) assert False # Failed except ValueError:", "= ssf.get_day_names() assert isinstance(dn, tuple) assert dn == (('Mon', 'Monday'),", "SSF ssf = SSF(errors='raise') def test_get_set_days(): dn = ssf.get_day_names() assert", "dddd', '10/6/2020') == 'TU TUE' assert ssf.format('ddd dddd', '10/7/2020') ==", "'Sep', 'September'), ('O', 'Oct', 'October'), ('N', 'Nov', 'November'), ('D', 'Dec',", "assert t[0] == 'General' assert t[1] == '0' assert t[14]", "('J', 'Jun', 'June'), ('J', 'Jul', 'July'), ('A', 'Aug', 'August'), ('S',", "'TUE'), ['WE', 'WED'], ('TH', 'THU'), ['FR', 'FRI'], ('SA', 'SAT'), ['SU',", "'March'), ('A', 'Apr', 'April'), ('M', 'May', 'May'), ('J', 'Jun', 'June'),", "'2020-10-06' assert ssf.format(105, 3.4) == '3.4' assert ssf.load('0') == 1", "assert False # Failed except ValueError: pass def test_get_set_months(): mn", "'MO MON' assert ssf.format('ddd dddd', '10/6/2020') == 'TU TUE' assert", "('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday'))", "'SA SAT' assert ssf.format('ddd dddd', '10/4/2020') == 'SU SUN' assert", "('TH', 'THU'), ['FR', 'FRI'], ('SA', 'SAT'), ['SU', 'SUN']]) assert ssf.format('ddd", "MON' assert ssf.format('ddd dddd', '10/6/2020') == 'TU TUE' assert ssf.format('ddd", "ssf.format('ddd dddd', '10/7/2020') == 'WE WED' assert ssf.format('ddd dddd', '10/8/2020')", "== 'FR FRI' try: ssf.set_day_names(2) assert False # Failed except", "'February'), ('M', 'Mar', 'March'), ('A', 'Apr', 'April'), ('M', 'May', 'May'),", "ssf.set_month_names(2) assert False # Failed except ValueError: pass try: ssf.set_month_names((0,", "ssf.format(104, '10/6/2020') == '2020-10-06' assert ssf.format(105, 3.4) == '3.4' assert", "['FR', 'FRI'], ('SA', 'SAT'), ['SU', 'SUN']]) assert ssf.format('ddd dddd', '10/3/2020')", "= SSF(errors='raise') def test_get_set_days(): dn = ssf.get_day_names() assert isinstance(dn, tuple)", "except ValueError: pass def test_get_load_table(): t = ssf.get_table() assert t[0]", "== (('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri',", "# Failed except ValueError: pass try: ssf.set_day_names((1, 2, 3, 4,", "assert mn == (None, ('J', 'Jan', 'January'), ('F', 'Feb', 'February'),", "assert ssf.format(105, 3.4) == '3.4' assert ssf.load('0') == 1 assert", "from ssf import SSF ssf = SSF(errors='raise') def test_get_set_days(): dn", "('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday')) ssf.set_day_names([['MO', 'MON'],", "== 'TU TUE' assert ssf.format('ddd dddd', '10/7/2020') == 'WE WED'", "'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday')) ssf.set_day_names([['MO', 'MON'], ('TU',", "ssf.format('ddd dddd', '10/3/2020') == 'SA SAT' assert ssf.format('ddd dddd', '10/4/2020')", "'WE WED' assert ssf.format('ddd dddd', '10/8/2020') == 'TH THU' assert", "('J', 'Jul', 'July'), ('A', 'Aug', 'August'), ('S', 'Sep', 'September'), ('O',", "assert ssf.format('ddd dddd', '10/3/2020') == 'SA SAT' assert ssf.format('ddd dddd',", "'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday')) ssf.set_day_names([['MO',", "('D', 'Dec', 'December')) ssf.set_month_names(mn[:-1] + (('X', 'DE', 'DEC'),) ) assert", "t = ssf.get_table() assert t[0] == 'General' assert t[1] ==", "== '3.4' assert ssf.load('0') == 1 assert ssf.load('mmm mmmm') ==", "ssf.format('mmmmm mmm mmmm', '12/3/2020') == 'X DE DEC' try: ssf.set_month_names(2)", "assert ssf.load('mmm mmmm') == 5 # Will be inserted at", "'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday')) ssf.set_day_names([['MO', 'MON'], ('TU', 'TUE'), ['WE',", "12)) assert False # Failed except ValueError: pass def test_get_load_table():", "inserted at 5 assert ssf.load('@') == 49 assert ssf.format(5, '10/6/2020')", "'DEC'),) ) assert ssf.format('mmmmm mmm mmmm', '12/3/2020') == 'X DE", "tuple) assert dn == (('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'),", "'10/4/2020') == 'SU SUN' assert ssf.format('ddd dddd', '10/5/2020') == 'MO", "('S', 'Sep', 'September'), ('O', 'Oct', 'October'), ('N', 'Nov', 'November'), ('D',", "= ssf.get_month_names() assert isinstance(mn, tuple) assert mn == (None, ('J',", "except ValueError: pass def test_get_set_months(): mn = ssf.get_month_names() assert isinstance(mn,", "'Dec', 'December')) ssf.set_month_names(mn[:-1] + (('X', 'DE', 'DEC'),) ) assert ssf.format('mmmmm", "assert ssf.format(104, '10/6/2020') == '2020-10-06' assert ssf.format(105, 3.4) == '3.4'", "def test_get_load_table(): t = ssf.get_table() assert t[0] == 'General' assert", "'Saturday'), ('Sun', 'Sunday')) ssf.set_day_names([['MO', 'MON'], ('TU', 'TUE'), ['WE', 'WED'], ('TH',", "5 # Will be inserted at 5 assert ssf.load('@') ==", "2, 3, 4, 5, 6, 7)) assert False # Failed", "ValueError: pass def test_get_set_months(): mn = ssf.get_month_names() assert isinstance(mn, tuple)", "'October'), ('N', 'Nov', 'November'), ('D', 'Dec', 'December')) ssf.set_month_names(mn[:-1] + (('X',", "'Nov', 'November'), ('D', 'Dec', 'December')) ssf.set_month_names(mn[:-1] + (('X', 'DE', 'DEC'),)", "ValueError: pass try: ssf.set_month_names((0, 1, 2, 3, 4, 5, 6,", "11, 12)) assert False # Failed except ValueError: pass def", "'@' ssf.load_table({104:'yyyy-mm-dd', 105:'0.0'}) assert ssf.format(104, '10/6/2020') == '2020-10-06' assert ssf.format(105,", "('Sun', 'Sunday')) ssf.set_day_names([['MO', 'MON'], ('TU', 'TUE'), ['WE', 'WED'], ('TH', 'THU'),", "Failed except ValueError: pass try: ssf.set_day_names((1, 2, 3, 4, 5,", "False # Failed except ValueError: pass try: ssf.set_day_names((1, 2, 3,", "import SSF ssf = SSF(errors='raise') def test_get_set_days(): dn = ssf.get_day_names()", "'July'), ('A', 'Aug', 'August'), ('S', 'Sep', 'September'), ('O', 'Oct', 'October'),", "('A', 'Apr', 'April'), ('M', 'May', 'May'), ('J', 'Jun', 'June'), ('J',", "'November'), ('D', 'Dec', 'December')) ssf.set_month_names(mn[:-1] + (('X', 'DE', 'DEC'),) )", "ssf.set_day_names(2) assert False # Failed except ValueError: pass try: ssf.set_day_names((1,", "assert False # Failed except ValueError: pass def test_get_load_table(): t", "DEC' try: ssf.set_month_names(2) assert False # Failed except ValueError: pass", "THU' assert ssf.format('ddd dddd', '10/9/2020') == 'FR FRI' try: ssf.set_day_names(2)", "'August'), ('S', 'Sep', 'September'), ('O', 'Oct', 'October'), ('N', 'Nov', 'November'),", "'12/3/2020') == 'X DE DEC' try: ssf.set_month_names(2) assert False #", "7, 8, 9, 10, 11, 12)) assert False # Failed", "SUN' assert ssf.format('ddd dddd', '10/5/2020') == 'MO MON' assert ssf.format('ddd", "ssf.load_table({104:'yyyy-mm-dd', 105:'0.0'}) assert ssf.format(104, '10/6/2020') == '2020-10-06' assert ssf.format(105, 3.4)", "ssf.load('mmm mmmm') == 5 # Will be inserted at 5", "'December')) ssf.set_month_names(mn[:-1] + (('X', 'DE', 'DEC'),) ) assert ssf.format('mmmmm mmm", "dddd', '10/3/2020') == 'SA SAT' assert ssf.format('ddd dddd', '10/4/2020') ==", "'TU TUE' assert ssf.format('ddd dddd', '10/7/2020') == 'WE WED' assert", "3.4) == '3.4' assert ssf.load('0') == 1 assert ssf.load('mmm mmmm')", "SAT' assert ssf.format('ddd dddd', '10/4/2020') == 'SU SUN' assert ssf.format('ddd", "WED' assert ssf.format('ddd dddd', '10/8/2020') == 'TH THU' assert ssf.format('ddd", "TUE' assert ssf.format('ddd dddd', '10/7/2020') == 'WE WED' assert ssf.format('ddd", "ValueError: pass def test_get_load_table(): t = ssf.get_table() assert t[0] ==", "(('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'),", "('SA', 'SAT'), ['SU', 'SUN']]) assert ssf.format('ddd dddd', '10/3/2020') == 'SA", "('J', 'Jan', 'January'), ('F', 'Feb', 'February'), ('M', 'Mar', 'March'), ('A',", "6, 7)) assert False # Failed except ValueError: pass def", "try: ssf.set_day_names(2) assert False # Failed except ValueError: pass try:", "['SU', 'SUN']]) assert ssf.format('ddd dddd', '10/3/2020') == 'SA SAT' assert", "'Feb', 'February'), ('M', 'Mar', 'March'), ('A', 'Apr', 'April'), ('M', 'May',", "(('X', 'DE', 'DEC'),) ) assert ssf.format('mmmmm mmm mmmm', '12/3/2020') ==", "== 'X DE DEC' try: ssf.set_month_names(2) assert False # Failed", "(None, ('J', 'Jan', 'January'), ('F', 'Feb', 'February'), ('M', 'Mar', 'March'),", "8, 9, 10, 11, 12)) assert False # Failed except", "('Sat', 'Saturday'), ('Sun', 'Sunday')) ssf.set_day_names([['MO', 'MON'], ('TU', 'TUE'), ['WE', 'WED'],", "'10/8/2020') == 'TH THU' assert ssf.format('ddd dddd', '10/9/2020') == 'FR", "assert False # Failed except ValueError: pass try: ssf.set_day_names((1, 2,", "105:'0.0'}) assert ssf.format(104, '10/6/2020') == '2020-10-06' assert ssf.format(105, 3.4) ==", "mn = ssf.get_month_names() assert isinstance(mn, tuple) assert mn == (None,", "('F', 'Feb', 'February'), ('M', 'Mar', 'March'), ('A', 'Apr', 'April'), ('M',", "'10/7/2020') == 'WE WED' assert ssf.format('ddd dddd', '10/8/2020') == 'TH", "'General' assert t[1] == '0' assert t[14] == 'm/d/yyyy' assert", "t[49] == '@' ssf.load_table({104:'yyyy-mm-dd', 105:'0.0'}) assert ssf.format(104, '10/6/2020') == '2020-10-06'", "assert False # Failed except ValueError: pass try: ssf.set_month_names((0, 1,", "'SAT'), ['SU', 'SUN']]) assert ssf.format('ddd dddd', '10/3/2020') == 'SA SAT'", "assert t[1] == '0' assert t[14] == 'm/d/yyyy' assert t[49]", "'May'), ('J', 'Jun', 'June'), ('J', 'Jul', 'July'), ('A', 'Aug', 'August'),", "4, 5, 6, 7, 8, 9, 10, 11, 12)) assert", "'DE', 'DEC'),) ) assert ssf.format('mmmmm mmm mmmm', '12/3/2020') == 'X", "assert ssf.format('ddd dddd', '10/8/2020') == 'TH THU' assert ssf.format('ddd dddd',", ") assert ssf.format('mmmmm mmm mmmm', '12/3/2020') == 'X DE DEC'", "'Jan', 'January'), ('F', 'Feb', 'February'), ('M', 'Mar', 'March'), ('A', 'Apr',", "try: ssf.set_month_names(2) assert False # Failed except ValueError: pass try:", "5 assert ssf.load('@') == 49 assert ssf.format(5, '10/6/2020') == 'Oct", "dddd', '10/5/2020') == 'MO MON' assert ssf.format('ddd dddd', '10/6/2020') ==", "ssf.format('ddd dddd', '10/5/2020') == 'MO MON' assert ssf.format('ddd dddd', '10/6/2020')", "'Sunday')) ssf.set_day_names([['MO', 'MON'], ('TU', 'TUE'), ['WE', 'WED'], ('TH', 'THU'), ['FR',", "== '@' ssf.load_table({104:'yyyy-mm-dd', 105:'0.0'}) assert ssf.format(104, '10/6/2020') == '2020-10-06' assert", "# Will be inserted at 5 assert ssf.load('@') == 49", "ssf.format('ddd dddd', '10/8/2020') == 'TH THU' assert ssf.format('ddd dddd', '10/9/2020')", "'3.4' assert ssf.load('0') == 1 assert ssf.load('mmm mmmm') == 5", "'Jul', 'July'), ('A', 'Aug', 'August'), ('S', 'Sep', 'September'), ('O', 'Oct',", "== 'MO MON' assert ssf.format('ddd dddd', '10/6/2020') == 'TU TUE'", "# Failed except ValueError: pass def test_get_set_months(): mn = ssf.get_month_names()", "mn == (None, ('J', 'Jan', 'January'), ('F', 'Feb', 'February'), ('M',", "10, 11, 12)) assert False # Failed except ValueError: pass", "mmmm') == 5 # Will be inserted at 5 assert", "9, 10, 11, 12)) assert False # Failed except ValueError:", "'May', 'May'), ('J', 'Jun', 'June'), ('J', 'Jul', 'July'), ('A', 'Aug',", "assert t[14] == 'm/d/yyyy' assert t[49] == '@' ssf.load_table({104:'yyyy-mm-dd', 105:'0.0'})", "DE DEC' try: ssf.set_month_names(2) assert False # Failed except ValueError:", "Failed except ValueError: pass def test_get_load_table(): t = ssf.get_table() assert", "'June'), ('J', 'Jul', 'July'), ('A', 'Aug', 'August'), ('S', 'Sep', 'September'),", "ssf.format('ddd dddd', '10/6/2020') == 'TU TUE' assert ssf.format('ddd dddd', '10/7/2020')", "FRI' try: ssf.set_day_names(2) assert False # Failed except ValueError: pass", "'SUN']]) assert ssf.format('ddd dddd', '10/3/2020') == 'SA SAT' assert ssf.format('ddd", "ValueError: pass try: ssf.set_day_names((1, 2, 3, 4, 5, 6, 7))", "test_get_set_months(): mn = ssf.get_month_names() assert isinstance(mn, tuple) assert mn ==", "'WED'], ('TH', 'THU'), ['FR', 'FRI'], ('SA', 'SAT'), ['SU', 'SUN']]) assert", "ssf.get_day_names() assert isinstance(dn, tuple) assert dn == (('Mon', 'Monday'), ('Tue',", "ssf.set_day_names([['MO', 'MON'], ('TU', 'TUE'), ['WE', 'WED'], ('TH', 'THU'), ['FR', 'FRI'],", "assert ssf.format('ddd dddd', '10/9/2020') == 'FR FRI' try: ssf.set_day_names(2) assert", "'September'), ('O', 'Oct', 'October'), ('N', 'Nov', 'November'), ('D', 'Dec', 'December'))", "+ (('X', 'DE', 'DEC'),) ) assert ssf.format('mmmmm mmm mmmm', '12/3/2020')", "pass def test_get_load_table(): t = ssf.get_table() assert t[0] == 'General'", "['WE', 'WED'], ('TH', 'THU'), ['FR', 'FRI'], ('SA', 'SAT'), ['SU', 'SUN']])", "dddd', '10/7/2020') == 'WE WED' assert ssf.format('ddd dddd', '10/8/2020') ==", "be inserted at 5 assert ssf.load('@') == 49 assert ssf.format(5,", "'January'), ('F', 'Feb', 'February'), ('M', 'Mar', 'March'), ('A', 'Apr', 'April'),", "Failed except ValueError: pass def test_get_set_months(): mn = ssf.get_month_names() assert", "assert ssf.load('0') == 1 assert ssf.load('mmm mmmm') == 5 #", "False # Failed except ValueError: pass def test_get_load_table(): t =", "('M', 'Mar', 'March'), ('A', 'Apr', 'April'), ('M', 'May', 'May'), ('J',", "5, 6, 7, 8, 9, 10, 11, 12)) assert False", "== 5 # Will be inserted at 5 assert ssf.load('@')", "== '2020-10-06' assert ssf.format(105, 3.4) == '3.4' assert ssf.load('0') ==", "dddd', '10/9/2020') == 'FR FRI' try: ssf.set_day_names(2) assert False #", "== 'General' assert t[1] == '0' assert t[14] == 'm/d/yyyy'", "('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday')) ssf.set_day_names([['MO', 'MON'], ('TU', 'TUE'),", "assert ssf.format('ddd dddd', '10/6/2020') == 'TU TUE' assert ssf.format('ddd dddd',", "('TU', 'TUE'), ['WE', 'WED'], ('TH', 'THU'), ['FR', 'FRI'], ('SA', 'SAT'),", "'X DE DEC' try: ssf.set_month_names(2) assert False # Failed except", "ssf.set_day_names((1, 2, 3, 4, 5, 6, 7)) assert False #", "ssf = SSF(errors='raise') def test_get_set_days(): dn = ssf.get_day_names() assert isinstance(dn,", "ssf.set_month_names((0, 1, 2, 3, 4, 5, 6, 7, 8, 9,", "# Failed except ValueError: pass def test_get_load_table(): t = ssf.get_table()", "'MON'], ('TU', 'TUE'), ['WE', 'WED'], ('TH', 'THU'), ['FR', 'FRI'], ('SA',", "'TH THU' assert ssf.format('ddd dddd', '10/9/2020') == 'FR FRI' try:", "SSF(errors='raise') def test_get_set_days(): dn = ssf.get_day_names() assert isinstance(dn, tuple) assert", "False # Failed except ValueError: pass try: ssf.set_month_names((0, 1, 2,", "('A', 'Aug', 'August'), ('S', 'Sep', 'September'), ('O', 'Oct', 'October'), ('N',", "test_get_load_table(): t = ssf.get_table() assert t[0] == 'General' assert t[1]", "('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'),", "'10/3/2020') == 'SA SAT' assert ssf.format('ddd dddd', '10/4/2020') == 'SU", "'10/9/2020') == 'FR FRI' try: ssf.set_day_names(2) assert False # Failed", "mmmm', '12/3/2020') == 'X DE DEC' try: ssf.set_month_names(2) assert False", "== 'SU SUN' assert ssf.format('ddd dddd', '10/5/2020') == 'MO MON'", "3, 4, 5, 6, 7, 8, 9, 10, 11, 12))", "'m/d/yyyy' assert t[49] == '@' ssf.load_table({104:'yyyy-mm-dd', 105:'0.0'}) assert ssf.format(104, '10/6/2020')", "ssf.format('ddd dddd', '10/9/2020') == 'FR FRI' try: ssf.set_day_names(2) assert False", "'SU SUN' assert ssf.format('ddd dddd', '10/5/2020') == 'MO MON' assert", "t[1] == '0' assert t[14] == 'm/d/yyyy' assert t[49] ==", "ssf.get_month_names() assert isinstance(mn, tuple) assert mn == (None, ('J', 'Jan',", "pass try: ssf.set_month_names((0, 1, 2, 3, 4, 5, 6, 7,", "try: ssf.set_day_names((1, 2, 3, 4, 5, 6, 7)) assert False", "'April'), ('M', 'May', 'May'), ('J', 'Jun', 'June'), ('J', 'Jul', 'July'),", "== 'SA SAT' assert ssf.format('ddd dddd', '10/4/2020') == 'SU SUN'", "4, 5, 6, 7)) assert False # Failed except ValueError:", "('O', 'Oct', 'October'), ('N', 'Nov', 'November'), ('D', 'Dec', 'December')) ssf.set_month_names(mn[:-1]", "dn = ssf.get_day_names() assert isinstance(dn, tuple) assert dn == (('Mon',", "== 'WE WED' assert ssf.format('ddd dddd', '10/8/2020') == 'TH THU'", "== 'TH THU' assert ssf.format('ddd dddd', '10/9/2020') == 'FR FRI'", "except ValueError: pass try: ssf.set_month_names((0, 1, 2, 3, 4, 5,", "'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat',", "'FRI'], ('SA', 'SAT'), ['SU', 'SUN']]) assert ssf.format('ddd dddd', '10/3/2020') ==", "'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun',", "== 1 assert ssf.load('mmm mmmm') == 5 # Will be", "'10/6/2020') == 'TU TUE' assert ssf.format('ddd dddd', '10/7/2020') == 'WE", "dddd', '10/8/2020') == 'TH THU' assert ssf.format('ddd dddd', '10/9/2020') ==", "6, 7, 8, 9, 10, 11, 12)) assert False #", "ssf.load('0') == 1 assert ssf.load('mmm mmmm') == 5 # Will", "at 5 assert ssf.load('@') == 49 assert ssf.format(5, '10/6/2020') ==", "assert ssf.load('@') == 49 assert ssf.format(5, '10/6/2020') == 'Oct October'", "pass def test_get_set_months(): mn = ssf.get_month_names() assert isinstance(mn, tuple) assert", "Failed except ValueError: pass try: ssf.set_month_names((0, 1, 2, 3, 4,", "'Mar', 'March'), ('A', 'Apr', 'April'), ('M', 'May', 'May'), ('J', 'Jun',", "ssf import SSF ssf = SSF(errors='raise') def test_get_set_days(): dn =", "'Apr', 'April'), ('M', 'May', 'May'), ('J', 'Jun', 'June'), ('J', 'Jul',", "def test_get_set_months(): mn = ssf.get_month_names() assert isinstance(mn, tuple) assert mn", "assert t[49] == '@' ssf.load_table({104:'yyyy-mm-dd', 105:'0.0'}) assert ssf.format(104, '10/6/2020') ==", "'Oct', 'October'), ('N', 'Nov', 'November'), ('D', 'Dec', 'December')) ssf.set_month_names(mn[:-1] +", "== 'm/d/yyyy' assert t[49] == '@' ssf.load_table({104:'yyyy-mm-dd', 105:'0.0'}) assert ssf.format(104,", "t[14] == 'm/d/yyyy' assert t[49] == '@' ssf.load_table({104:'yyyy-mm-dd', 105:'0.0'}) assert", "ssf.set_month_names(mn[:-1] + (('X', 'DE', 'DEC'),) ) assert ssf.format('mmmmm mmm mmmm',", "'THU'), ['FR', 'FRI'], ('SA', 'SAT'), ['SU', 'SUN']]) assert ssf.format('ddd dddd',", "assert ssf.format('ddd dddd', '10/5/2020') == 'MO MON' assert ssf.format('ddd dddd',", "except ValueError: pass try: ssf.set_day_names((1, 2, 3, 4, 5, 6,", "ssf.format('ddd dddd', '10/4/2020') == 'SU SUN' assert ssf.format('ddd dddd', '10/5/2020')", "= ssf.get_table() assert t[0] == 'General' assert t[1] == '0'", "isinstance(mn, tuple) assert mn == (None, ('J', 'Jan', 'January'), ('F',", "ssf.format(105, 3.4) == '3.4' assert ssf.load('0') == 1 assert ssf.load('mmm", "'Aug', 'August'), ('S', 'Sep', 'September'), ('O', 'Oct', 'October'), ('N', 'Nov',", "# Failed except ValueError: pass try: ssf.set_month_names((0, 1, 2, 3,", "def test_get_set_days(): dn = ssf.get_day_names() assert isinstance(dn, tuple) assert dn", "== '0' assert t[14] == 'm/d/yyyy' assert t[49] == '@'", "7)) assert False # Failed except ValueError: pass def test_get_set_months():", "test_get_set_days(): dn = ssf.get_day_names() assert isinstance(dn, tuple) assert dn ==", "dn == (('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'),", "assert ssf.format('ddd dddd', '10/4/2020') == 'SU SUN' assert ssf.format('ddd dddd',", "'Jun', 'June'), ('J', 'Jul', 'July'), ('A', 'Aug', 'August'), ('S', 'Sep',", "ssf.get_table() assert t[0] == 'General' assert t[1] == '0' assert", "1, 2, 3, 4, 5, 6, 7, 8, 9, 10,", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11,", "('N', 'Nov', 'November'), ('D', 'Dec', 'December')) ssf.set_month_names(mn[:-1] + (('X', 'DE',", "assert dn == (('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu',", "'10/6/2020') == '2020-10-06' assert ssf.format(105, 3.4) == '3.4' assert ssf.load('0')", "t[0] == 'General' assert t[1] == '0' assert t[14] ==", "5, 6, 7)) assert False # Failed except ValueError: pass", "try: ssf.set_month_names((0, 1, 2, 3, 4, 5, 6, 7, 8,", "assert isinstance(mn, tuple) assert mn == (None, ('J', 'Jan', 'January'),", "isinstance(dn, tuple) assert dn == (('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed'," ]
[ "file_size yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4', resolution=res).first()", "pyfiglet from pytube import YouTube, Playlist file_size = 0 folder_name", "= input('Provide Playlist Link : ') videos_list = Playlist(playlist_url) folder_name", "-\") for num, res in enumerate(filters, start=1): print(\"\\t{}. {}\".format(num, str(res.resolution)))", "print(\"Wrong Option\") # Start of Program if __name__ == '__main__':", "float(total))) filled_length = int(length * iteration // total) bar =", "occured. Exception message is : \", e) # Playlist Single", "Using!!\") except Exception as e: print(\"Some Error occurred. Exception message", "file_handle, bytes_remaining): print_progress_bar(file_size - bytes_remaining, file_size, prefix='Progress:', suffix='Complete', length=50) return", "if choice == 1: download_video() elif choice == 2: download_playlist()", "res): global file_size yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True,", "(length - filled_length) print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end=print_end) if iteration", "occurred. Exception message is : \", e) # Main Function", "print(\"\\t{}. {}\".format(num, str(res.resolution))) selected_res = int(input('Please enter desired resolution :", "Downloaded. Thanks for Using!!\") except Exception as e: print(\"Some Error", "num, res in enumerate(filters, start=1): print(\"\\t{}. {}\".format(num, str(res.resolution))) selected_res =", "# Playlist Single Video Download def download_playlist_video(video_url, res): global file_size", "yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4', resolution=res).first() file_size", "download_video() elif choice == 2: download_playlist() else: print(\"Wrong Option\") #", "= int(input('Please enter desired resolution : ')) filters = filters[selected_res", "Error occured. Exception message is : \", e) # Playlist", "yt_obj.streams.filter( progressive=True, file_extension='mp4').first() print(\"\\nDownloading {}\".format(str(filters.title))) download_location = get_download_location() filters.download(output_path=\"{}/{}\".format(download_location, folder_name))", "2.Download Playlist\\n Enter Your Choice : \"\"\")) if choice ==", "download_video(): global file_size try: video_url = input('Provide Video Download Link", "str(res.resolution))) selected_res = int(input('Please enter desired resolution : ')) filters", "Resolution def get_resolution(video_url): yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True,", "Exception message is : \", e) # Playlist Single Video", "choice == 2: download_playlist() else: print(\"Wrong Option\") # Start of", "Progress Bar def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='#',", "* (length - filled_length) print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end=print_end) if", "Location def get_download_location(): if os.name == 'nt': download_location = os.path.join(os.path.expanduser('~'),", "filled_length) print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end=print_end) if iteration == total:", "file_size = int(filters.filesize) if not filters: filters = yt_obj.streams.filter( progressive=True,", "print(\"\\nDownloading {}\".format(str(filters.title))) download_location = get_download_location() filters.download(output_path=\"{}/{}\".format(download_location, folder_name)) print(\"Download Complete\") #", "'nt': download_location = os.path.join(os.path.expanduser('~'), 'Downloads') else: download_location = os.path.join( os.path.expanduser('~'),", "playlist_url = input('Provide Playlist Link : ') videos_list = Playlist(playlist_url)", "\", e) # Playlist Single Video Download def download_playlist_video(video_url, res):", "Error occurred. Exception message is : \", e) # Main", "Complete\") # Playlist Download def download_playlist(): global folder_name try: playlist_url", "Main Function def main(): ascii_banner = pyfiglet.figlet_format(\"YT Downloader\") print(ascii_banner) print(\"\\t", "the video here - {}\".format(download_location)) except Exception as e: print(\"Some", "folder_name = \"\" # Progress Bar def print_progress_bar(iteration, total, prefix='',", "def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='#', print_end=\"\\r\"): percent", "if os.name == 'nt': download_location = os.path.join(os.path.expanduser('~'), 'Downloads') else: download_location", "os.path.expanduser('~'), 'Downloads') return download_location # Get Desired Resolution def get_resolution(video_url):", "Playlist file_size = 0 folder_name = \"\" # Progress Bar", "Playlist\\n Enter Your Choice : \"\"\")) if choice == 1:", "Download Link : ') filters = get_resolution(video_url) file_size = int(filters.filesize)", "videos_list: download_playlist_video(video, resolution) print(\"All Videos Downloaded. Thanks for Using!!\") except", "def download_playlist_video(video_url, res): global file_size yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters", "global file_size yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4',", "= fill * filled_length + '-' * (length - filled_length)", "Link : ') filters = get_resolution(video_url) file_size = int(filters.filesize) download_location", "= int(filters.filesize) download_location = get_download_location() print(\"\\nDownloading {}\".format(str(filters.title))) filters.download(output_path=download_location) print(\"Video Downloaded.", "else: print(\"Wrong Option\") # Start of Program if __name__ ==", "resolution=res).first() file_size = int(filters.filesize) if not filters: filters = yt_obj.streams.filter(", "'Downloads') return download_location # Get Desired Resolution def get_resolution(video_url): yt_obj", "YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4', resolution=res).first() file_size = int(filters.filesize)", "= filters[selected_res - 1] return filters # Single Video Download", "not filters: filters = yt_obj.streams.filter( progressive=True, file_extension='mp4').first() print(\"\\nDownloading {}\".format(str(filters.title))) download_location", "* (iteration / float(total))) filled_length = int(length * iteration //", "0 folder_name = \"\" # Progress Bar def print_progress_bar(iteration, total,", "Resolutions -\") for num, res in enumerate(filters, start=1): print(\"\\t{}. {}\".format(num,", "resolution = get_resolution(videos_list[0]).resolution for video in videos_list: download_playlist_video(video, resolution) print(\"All", "resolution) print(\"All Videos Downloaded. Thanks for Using!!\") except Exception as", "= get_resolution(video_url) file_size = int(filters.filesize) download_location = get_download_location() print(\"\\nDownloading {}\".format(str(filters.title)))", "{suffix}', end=print_end) if iteration == total: print() # Show Progress", "YouTube, Playlist file_size = 0 folder_name = \"\" # Progress", "filters: filters = yt_obj.streams.filter( progressive=True, file_extension='mp4').first() print(\"\\nDownloading {}\".format(str(filters.title))) download_location =", "print(\"Some Error occured. Exception message is : \", e) #", "== total: print() # Show Progress Bar def show_progress_bar(chunk, file_handle,", "video here - {}\".format(download_location)) except Exception as e: print(\"Some Error", "/ float(total))) filled_length = int(length * iteration // total) bar", "end=print_end) if iteration == total: print() # Show Progress Bar", "start=1): print(\"\\t{}. {}\".format(num, str(res.resolution))) selected_res = int(input('Please enter desired resolution", "int(filters.filesize) if not filters: filters = yt_obj.streams.filter( progressive=True, file_extension='mp4').first() print(\"\\nDownloading", "= input('Provide Video Download Link : ') filters = get_resolution(video_url)", "total, prefix='', suffix='', decimals=1, length=100, fill='#', print_end=\"\\r\"): percent = (\"{0:.\"", "length=50) return # Get Download Location def get_download_location(): if os.name", "try: playlist_url = input('Provide Playlist Link : ') videos_list =", "print(\"\\t By <NAME>\\n\\n\") choice = int(input( \"\"\"MENU 1.Download Single Video", "global file_size try: video_url = input('Provide Video Download Link :", "filters = yt_obj.streams.filter( progressive=True, file_extension='mp4').first() print(\"\\nDownloading {}\".format(str(filters.title))) download_location = get_download_location()", "\"\" # Progress Bar def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1,", "ascii_banner = pyfiglet.figlet_format(\"YT Downloader\") print(ascii_banner) print(\"\\t By <NAME>\\n\\n\") choice =", "download_location = os.path.join( os.path.expanduser('~'), 'Downloads') return download_location # Get Desired", "1: download_video() elif choice == 2: download_playlist() else: print(\"Wrong Option\")", "Download Location def get_download_location(): if os.name == 'nt': download_location =", "for using!!\\nYou can find the video here - {}\".format(download_location)) except", ": \", e) # Playlist Single Video Download def download_playlist_video(video_url,", "filters = get_resolution(video_url) file_size = int(filters.filesize) download_location = get_download_location() print(\"\\nDownloading", "folder_name)) print(\"Download Complete\") # Playlist Download def download_playlist(): global folder_name", "pyfiglet.figlet_format(\"YT Downloader\") print(ascii_banner) print(\"\\t By <NAME>\\n\\n\") choice = int(input( \"\"\"MENU", "print_end=\"\\r\"): percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration", "== 1: download_video() elif choice == 2: download_playlist() else: print(\"Wrong", "prefix='Progress:', suffix='Complete', length=50) return # Get Download Location def get_download_location():", "(\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total))) filled_length", "') filters = get_resolution(video_url) file_size = int(filters.filesize) download_location = get_download_location()", "res in enumerate(filters, start=1): print(\"\\t{}. {}\".format(num, str(res.resolution))) selected_res = int(input('Please", "video_url = input('Provide Video Download Link : ') filters =", "except Exception as e: print(\"Some Error occured. Exception message is", "download_location = get_download_location() filters.download(output_path=\"{}/{}\".format(download_location, folder_name)) print(\"Download Complete\") # Playlist Download", "file_size, prefix='Progress:', suffix='Complete', length=50) return # Get Download Location def", "Exception as e: print(\"Some Error occured. Exception message is :", "video in videos_list: download_playlist_video(video, resolution) print(\"All Videos Downloaded. Thanks for", ": \"\"\")) if choice == 1: download_video() elif choice ==", "= yt_obj.streams.filter(progressive=True, file_extension='mp4') print(\"\\nAvailable Resolutions -\") for num, res in", "enter desired resolution : ')) filters = filters[selected_res - 1]", "folder_name = videos_list.title resolution = get_resolution(videos_list[0]).resolution for video in videos_list:", "file_size try: video_url = input('Provide Video Download Link : ')", "\"\"\")) if choice == 1: download_video() elif choice == 2:", "desired resolution : ')) filters = filters[selected_res - 1] return", "Desired Resolution def get_resolution(video_url): yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters =", "print(ascii_banner) print(\"\\t By <NAME>\\n\\n\") choice = int(input( \"\"\"MENU 1.Download Single", "return download_location # Get Desired Resolution def get_resolution(video_url): yt_obj =", "# Main Function def main(): ascii_banner = pyfiglet.figlet_format(\"YT Downloader\") print(ascii_banner)", "def download_playlist(): global folder_name try: playlist_url = input('Provide Playlist Link", "videos_list.title resolution = get_resolution(videos_list[0]).resolution for video in videos_list: download_playlist_video(video, resolution)", "print(\"\\nAvailable Resolutions -\") for num, res in enumerate(filters, start=1): print(\"\\t{}.", "file_extension='mp4').first() print(\"\\nDownloading {}\".format(str(filters.title))) download_location = get_download_location() filters.download(output_path=\"{}/{}\".format(download_location, folder_name)) print(\"Download Complete\")", "filters.download(output_path=\"{}/{}\".format(download_location, folder_name)) print(\"Download Complete\") # Playlist Download def download_playlist(): global", "progressive=True, file_extension='mp4').first() print(\"\\nDownloading {}\".format(str(filters.title))) download_location = get_download_location() filters.download(output_path=\"{}/{}\".format(download_location, folder_name)) print(\"Download", "folder_name try: playlist_url = input('Provide Playlist Link : ') videos_list", "{percent}% {suffix}', end=print_end) if iteration == total: print() # Show", "int(input('Please enter desired resolution : ')) filters = filters[selected_res -", "fill * filled_length + '-' * (length - filled_length) print(f'\\r{prefix}", "download_playlist_video(video_url, res): global file_size yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters =", "= int(length * iteration // total) bar = fill *", "= os.path.join( os.path.expanduser('~'), 'Downloads') return download_location # Get Desired Resolution", "bytes_remaining, file_size, prefix='Progress:', suffix='Complete', length=50) return # Get Download Location", "str(decimals) + \"f}\").format(100 * (iteration / float(total))) filled_length = int(length", "2: download_playlist() else: print(\"Wrong Option\") # Start of Program if", "main(): ascii_banner = pyfiglet.figlet_format(\"YT Downloader\") print(ascii_banner) print(\"\\t By <NAME>\\n\\n\") choice", "os.path.join(os.path.expanduser('~'), 'Downloads') else: download_location = os.path.join( os.path.expanduser('~'), 'Downloads') return download_location", "def main(): ascii_banner = pyfiglet.figlet_format(\"YT Downloader\") print(ascii_banner) print(\"\\t By <NAME>\\n\\n\")", "Playlist(playlist_url) folder_name = videos_list.title resolution = get_resolution(videos_list[0]).resolution for video in", "download_playlist_video(video, resolution) print(\"All Videos Downloaded. Thanks for Using!!\") except Exception", "in enumerate(filters, start=1): print(\"\\t{}. {}\".format(num, str(res.resolution))) selected_res = int(input('Please enter", "e: print(\"Some Error occurred. Exception message is : \", e)", "= os.path.join(os.path.expanduser('~'), 'Downloads') else: download_location = os.path.join( os.path.expanduser('~'), 'Downloads') return", "<NAME>\\n\\n\") choice = int(input( \"\"\"MENU 1.Download Single Video 2.Download Playlist\\n", "using!!\\nYou can find the video here - {}\".format(download_location)) except Exception", "= yt_obj.streams.filter(progressive=True, file_extension='mp4', resolution=res).first() file_size = int(filters.filesize) if not filters:", "selected_res = int(input('Please enter desired resolution : ')) filters =", "= YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4', resolution=res).first() file_size =", "YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4') print(\"\\nAvailable Resolutions -\") for", "= get_download_location() print(\"\\nDownloading {}\".format(str(filters.title))) filters.download(output_path=download_location) print(\"Video Downloaded. Thanks for using!!\\nYou", "file_size = int(filters.filesize) download_location = get_download_location() print(\"\\nDownloading {}\".format(str(filters.title))) filters.download(output_path=download_location) print(\"Video", "= Playlist(playlist_url) folder_name = videos_list.title resolution = get_resolution(videos_list[0]).resolution for video", "Video Download Link : ') filters = get_resolution(video_url) file_size =", "choice == 1: download_video() elif choice == 2: download_playlist() else:", "Thanks for Using!!\") except Exception as e: print(\"Some Error occurred.", "{}\".format(str(filters.title))) filters.download(output_path=download_location) print(\"Video Downloaded. Thanks for using!!\\nYou can find the", "+ str(decimals) + \"f}\").format(100 * (iteration / float(total))) filled_length =", "\"f}\").format(100 * (iteration / float(total))) filled_length = int(length * iteration", "Download def download_playlist_video(video_url, res): global file_size yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar)", "if iteration == total: print() # Show Progress Bar def", "decimals=1, length=100, fill='#', print_end=\"\\r\"): percent = (\"{0:.\" + str(decimals) +", "- filled_length) print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end=print_end) if iteration ==", "Single Video Download def download_video(): global file_size try: video_url =", "message is : \", e) # Playlist Single Video Download", "Your Choice : \"\"\")) if choice == 1: download_video() elif", "os.name == 'nt': download_location = os.path.join(os.path.expanduser('~'), 'Downloads') else: download_location =", "= 0 folder_name = \"\" # Progress Bar def print_progress_bar(iteration,", "print_progress_bar(file_size - bytes_remaining, file_size, prefix='Progress:', suffix='Complete', length=50) return # Get", "{}\".format(num, str(res.resolution))) selected_res = int(input('Please enter desired resolution : '))", "# Playlist Download def download_playlist(): global folder_name try: playlist_url =", "download_location = get_download_location() print(\"\\nDownloading {}\".format(str(filters.title))) filters.download(output_path=download_location) print(\"Video Downloaded. Thanks for", "Playlist Download def download_playlist(): global folder_name try: playlist_url = input('Provide", "1.Download Single Video 2.Download Playlist\\n Enter Your Choice : \"\"\"))", "videos_list = Playlist(playlist_url) folder_name = videos_list.title resolution = get_resolution(videos_list[0]).resolution for", "(iteration / float(total))) filled_length = int(length * iteration // total)", "bar = fill * filled_length + '-' * (length -", "os import pyfiglet from pytube import YouTube, Playlist file_size =", "Video 2.Download Playlist\\n Enter Your Choice : \"\"\")) if choice", "print(\"Download Complete\") # Playlist Download def download_playlist(): global folder_name try:", "- 1] return filters # Single Video Download def download_video():", "elif choice == 2: download_playlist() else: print(\"Wrong Option\") # Start", "from pytube import YouTube, Playlist file_size = 0 folder_name =", "\"\"\"MENU 1.Download Single Video 2.Download Playlist\\n Enter Your Choice :", "def show_progress_bar(chunk, file_handle, bytes_remaining): print_progress_bar(file_size - bytes_remaining, file_size, prefix='Progress:', suffix='Complete',", "'-' * (length - filled_length) print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end=print_end)", "= \"\" # Progress Bar def print_progress_bar(iteration, total, prefix='', suffix='',", "def get_resolution(video_url): yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')", "Download def download_playlist(): global folder_name try: playlist_url = input('Provide Playlist", "{}\".format(str(filters.title))) download_location = get_download_location() filters.download(output_path=\"{}/{}\".format(download_location, folder_name)) print(\"Download Complete\") # Playlist", "return # Get Download Location def get_download_location(): if os.name ==", "Bar def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='#', print_end=\"\\r\"):", "By <NAME>\\n\\n\") choice = int(input( \"\"\"MENU 1.Download Single Video 2.Download", "+ '-' * (length - filled_length) print(f'\\r{prefix} |{bar}| {percent}% {suffix}',", "percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration /", "print(\"Video Downloaded. Thanks for using!!\\nYou can find the video here", "Video Download def download_video(): global file_size try: video_url = input('Provide", "Download def download_video(): global file_size try: video_url = input('Provide Video", "= videos_list.title resolution = get_resolution(videos_list[0]).resolution for video in videos_list: download_playlist_video(video,", "Link : ') videos_list = Playlist(playlist_url) folder_name = videos_list.title resolution", ": ')) filters = filters[selected_res - 1] return filters #", "Playlist Link : ') videos_list = Playlist(playlist_url) folder_name = videos_list.title", "length=100, fill='#', print_end=\"\\r\"): percent = (\"{0:.\" + str(decimals) + \"f}\").format(100", "get_download_location() print(\"\\nDownloading {}\".format(str(filters.title))) filters.download(output_path=download_location) print(\"Video Downloaded. Thanks for using!!\\nYou can", "suffix='Complete', length=50) return # Get Download Location def get_download_location(): if", "Function def main(): ascii_banner = pyfiglet.figlet_format(\"YT Downloader\") print(ascii_banner) print(\"\\t By", "|{bar}| {percent}% {suffix}', end=print_end) if iteration == total: print() #", "get_download_location() filters.download(output_path=\"{}/{}\".format(download_location, folder_name)) print(\"Download Complete\") # Playlist Download def download_playlist():", "= int(filters.filesize) if not filters: filters = yt_obj.streams.filter( progressive=True, file_extension='mp4').first()", "fill='#', print_end=\"\\r\"): percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 *", "filters # Single Video Download def download_video(): global file_size try:", "file_size = 0 folder_name = \"\" # Progress Bar def", "print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='#', print_end=\"\\r\"): percent =", "e) # Playlist Single Video Download def download_playlist_video(video_url, res): global", "Get Download Location def get_download_location(): if os.name == 'nt': download_location", "print(\"All Videos Downloaded. Thanks for Using!!\") except Exception as e:", "filters = filters[selected_res - 1] return filters # Single Video", "global folder_name try: playlist_url = input('Provide Playlist Link : ')", "Exception as e: print(\"Some Error occurred. Exception message is :", "else: download_location = os.path.join( os.path.expanduser('~'), 'Downloads') return download_location # Get", "# Get Desired Resolution def get_resolution(video_url): yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar)", "here - {}\".format(download_location)) except Exception as e: print(\"Some Error occured.", "for Using!!\") except Exception as e: print(\"Some Error occurred. Exception", "import pyfiglet from pytube import YouTube, Playlist file_size = 0", "'Downloads') else: download_location = os.path.join( os.path.expanduser('~'), 'Downloads') return download_location #", "yt_obj.streams.filter(progressive=True, file_extension='mp4', resolution=res).first() file_size = int(filters.filesize) if not filters: filters", "return filters # Single Video Download def download_video(): global file_size", ": ') filters = get_resolution(video_url) file_size = int(filters.filesize) download_location =", "get_resolution(videos_list[0]).resolution for video in videos_list: download_playlist_video(video, resolution) print(\"All Videos Downloaded.", "try: video_url = input('Provide Video Download Link : ') filters", "yt_obj.streams.filter(progressive=True, file_extension='mp4') print(\"\\nAvailable Resolutions -\") for num, res in enumerate(filters,", "filled_length = int(length * iteration // total) bar = fill", "get_resolution(video_url): yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4') print(\"\\nAvailable", "except Exception as e: print(\"Some Error occurred. Exception message is", "int(input( \"\"\"MENU 1.Download Single Video 2.Download Playlist\\n Enter Your Choice", "Single Video 2.Download Playlist\\n Enter Your Choice : \"\"\")) if", "print() # Show Progress Bar def show_progress_bar(chunk, file_handle, bytes_remaining): print_progress_bar(file_size", "for video in videos_list: download_playlist_video(video, resolution) print(\"All Videos Downloaded. Thanks", "on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4', resolution=res).first() file_size = int(filters.filesize) if", "= pyfiglet.figlet_format(\"YT Downloader\") print(ascii_banner) print(\"\\t By <NAME>\\n\\n\") choice = int(input(", "# Get Download Location def get_download_location(): if os.name == 'nt':", "is : \", e) # Main Function def main(): ascii_banner", ": ') videos_list = Playlist(playlist_url) folder_name = videos_list.title resolution =", ": \", e) # Main Function def main(): ascii_banner =", "download_location = os.path.join(os.path.expanduser('~'), 'Downloads') else: download_location = os.path.join( os.path.expanduser('~'), 'Downloads')", "prefix='', suffix='', decimals=1, length=100, fill='#', print_end=\"\\r\"): percent = (\"{0:.\" +", "= get_download_location() filters.download(output_path=\"{}/{}\".format(download_location, folder_name)) print(\"Download Complete\") # Playlist Download def", "show_progress_bar(chunk, file_handle, bytes_remaining): print_progress_bar(file_size - bytes_remaining, file_size, prefix='Progress:', suffix='Complete', length=50)", "- {}\".format(download_location)) except Exception as e: print(\"Some Error occured. Exception", "download_location # Get Desired Resolution def get_resolution(video_url): yt_obj = YouTube(video_url,", "in videos_list: download_playlist_video(video, resolution) print(\"All Videos Downloaded. Thanks for Using!!\")", "Get Desired Resolution def get_resolution(video_url): yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters", "= yt_obj.streams.filter( progressive=True, file_extension='mp4').first() print(\"\\nDownloading {}\".format(str(filters.title))) download_location = get_download_location() filters.download(output_path=\"{}/{}\".format(download_location,", "') videos_list = Playlist(playlist_url) folder_name = videos_list.title resolution = get_resolution(videos_list[0]).resolution", "<filename>script.py<gh_stars>0 import os import pyfiglet from pytube import YouTube, Playlist", "e) # Main Function def main(): ascii_banner = pyfiglet.figlet_format(\"YT Downloader\")", "= int(input( \"\"\"MENU 1.Download Single Video 2.Download Playlist\\n Enter Your", "os.path.join( os.path.expanduser('~'), 'Downloads') return download_location # Get Desired Resolution def", "def get_download_location(): if os.name == 'nt': download_location = os.path.join(os.path.expanduser('~'), 'Downloads')", "filled_length + '-' * (length - filled_length) print(f'\\r{prefix} |{bar}| {percent}%", "1] return filters # Single Video Download def download_video(): global", "iteration == total: print() # Show Progress Bar def show_progress_bar(chunk,", "can find the video here - {}\".format(download_location)) except Exception as", "print(\"Some Error occurred. Exception message is : \", e) #", "find the video here - {}\".format(download_location)) except Exception as e:", "filters = yt_obj.streams.filter(progressive=True, file_extension='mp4', resolution=res).first() file_size = int(filters.filesize) if not", "choice = int(input( \"\"\"MENU 1.Download Single Video 2.Download Playlist\\n Enter", "input('Provide Playlist Link : ') videos_list = Playlist(playlist_url) folder_name =", "file_extension='mp4') print(\"\\nAvailable Resolutions -\") for num, res in enumerate(filters, start=1):", "total: print() # Show Progress Bar def show_progress_bar(chunk, file_handle, bytes_remaining):", "filters[selected_res - 1] return filters # Single Video Download def", "{}\".format(download_location)) except Exception as e: print(\"Some Error occured. Exception message", "as e: print(\"Some Error occured. Exception message is : \",", "== 2: download_playlist() else: print(\"Wrong Option\") # Start of Program", "bytes_remaining): print_progress_bar(file_size - bytes_remaining, file_size, prefix='Progress:', suffix='Complete', length=50) return #", "# Single Video Download def download_video(): global file_size try: video_url", "resolution : ')) filters = filters[selected_res - 1] return filters", "// total) bar = fill * filled_length + '-' *", "download_playlist() else: print(\"Wrong Option\") # Start of Program if __name__", "Playlist Single Video Download def download_playlist_video(video_url, res): global file_size yt_obj", "\", e) # Main Function def main(): ascii_banner = pyfiglet.figlet_format(\"YT", "file_extension='mp4', resolution=res).first() file_size = int(filters.filesize) if not filters: filters =", "print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end=print_end) if iteration == total: print()", "= (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))", "* filled_length + '-' * (length - filled_length) print(f'\\r{prefix} |{bar}|", "filters = yt_obj.streams.filter(progressive=True, file_extension='mp4') print(\"\\nAvailable Resolutions -\") for num, res", "get_resolution(video_url) file_size = int(filters.filesize) download_location = get_download_location() print(\"\\nDownloading {}\".format(str(filters.title))) filters.download(output_path=download_location)", "on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4') print(\"\\nAvailable Resolutions -\") for num,", "Downloaded. Thanks for using!!\\nYou can find the video here -", "input('Provide Video Download Link : ') filters = get_resolution(video_url) file_size", "import YouTube, Playlist file_size = 0 folder_name = \"\" #", "is : \", e) # Playlist Single Video Download def", "Progress Bar def show_progress_bar(chunk, file_handle, bytes_remaining): print_progress_bar(file_size - bytes_remaining, file_size,", "for num, res in enumerate(filters, start=1): print(\"\\t{}. {}\".format(num, str(res.resolution))) selected_res", "int(filters.filesize) download_location = get_download_location() print(\"\\nDownloading {}\".format(str(filters.title))) filters.download(output_path=download_location) print(\"Video Downloaded. Thanks", "filters.download(output_path=download_location) print(\"Video Downloaded. Thanks for using!!\\nYou can find the video", "Enter Your Choice : \"\"\")) if choice == 1: download_video()", "suffix='', decimals=1, length=100, fill='#', print_end=\"\\r\"): percent = (\"{0:.\" + str(decimals)", "import os import pyfiglet from pytube import YouTube, Playlist file_size", "Bar def show_progress_bar(chunk, file_handle, bytes_remaining): print_progress_bar(file_size - bytes_remaining, file_size, prefix='Progress:',", "int(length * iteration // total) bar = fill * filled_length", "= get_resolution(videos_list[0]).resolution for video in videos_list: download_playlist_video(video, resolution) print(\"All Videos", "Choice : \"\"\")) if choice == 1: download_video() elif choice", "total) bar = fill * filled_length + '-' * (length", "Show Progress Bar def show_progress_bar(chunk, file_handle, bytes_remaining): print_progress_bar(file_size - bytes_remaining,", "iteration // total) bar = fill * filled_length + '-'", "enumerate(filters, start=1): print(\"\\t{}. {}\".format(num, str(res.resolution))) selected_res = int(input('Please enter desired", "- bytes_remaining, file_size, prefix='Progress:', suffix='Complete', length=50) return # Get Download", "Option\") # Start of Program if __name__ == '__main__': main()", "Videos Downloaded. Thanks for Using!!\") except Exception as e: print(\"Some", "if not filters: filters = yt_obj.streams.filter( progressive=True, file_extension='mp4').first() print(\"\\nDownloading {}\".format(str(filters.title)))", "Exception message is : \", e) # Main Function def", "download_playlist(): global folder_name try: playlist_url = input('Provide Playlist Link :", "pytube import YouTube, Playlist file_size = 0 folder_name = \"\"", "')) filters = filters[selected_res - 1] return filters # Single", "as e: print(\"Some Error occurred. Exception message is : \",", "* iteration // total) bar = fill * filled_length +", "yt_obj = YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4') print(\"\\nAvailable Resolutions", "+ \"f}\").format(100 * (iteration / float(total))) filled_length = int(length *", "Video Download def download_playlist_video(video_url, res): global file_size yt_obj = YouTube(video_url,", "Downloader\") print(ascii_banner) print(\"\\t By <NAME>\\n\\n\") choice = int(input( \"\"\"MENU 1.Download", "== 'nt': download_location = os.path.join(os.path.expanduser('~'), 'Downloads') else: download_location = os.path.join(", "# Progress Bar def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100,", "get_download_location(): if os.name == 'nt': download_location = os.path.join(os.path.expanduser('~'), 'Downloads') else:", "e: print(\"Some Error occured. Exception message is : \", e)", "Single Video Download def download_playlist_video(video_url, res): global file_size yt_obj =", "# Show Progress Bar def show_progress_bar(chunk, file_handle, bytes_remaining): print_progress_bar(file_size -", "print(\"\\nDownloading {}\".format(str(filters.title))) filters.download(output_path=download_location) print(\"Video Downloaded. Thanks for using!!\\nYou can find", "Thanks for using!!\\nYou can find the video here - {}\".format(download_location))", "message is : \", e) # Main Function def main():", "= YouTube(video_url, on_progress_callback=show_progress_bar) filters = yt_obj.streams.filter(progressive=True, file_extension='mp4') print(\"\\nAvailable Resolutions -\")", "def download_video(): global file_size try: video_url = input('Provide Video Download" ]
[ "import Cdr import unittest field1 = 1 field2 = 2", "self.assertEqual(d.getString(field2), \"Hello\") def test_get_exception(self): d = self.get_a_cdr() with self.assertRaises(RuntimeError): d.getInteger(4)", "= self.get_a_cdr() d.setString(field2, \"Hello\") self.assertEqual(d.getString(field2), \"Hello\") def test_get_exception(self): d =", "\"Hello\") self.assertEqual(d.getString(field2), \"Hello\") def test_get_exception(self): d = self.get_a_cdr() with self.assertRaises(RuntimeError):", "400 e[11] = 300 e[12] = [f] d[1] = 100", "= 1 field2 = 2 field3 = 55 class TestCdr(unittest.TestCase):", "\"World\") return d def test_set_integer(self): d = self.get_a_cdr() self.assertEqual(d.getInt32(field1), 123)", "self.assertRaises(RuntimeError): d.getInteger(4) def test_to_string(self): d = Cdr() d.setInteger(field1, 123) self.assertEqual(d.toString(),", "Ltd. # from cdr import Cdr import unittest field1 =", "d = Cdr() d.setInteger(field1, 123) d.setString(field2, \"Hello\") d.setString(field3, \"World\") return", "Cdr() f = Cdr() f[21] = 400 e[11] = 300", "100 d[2] = 200 d[3] = [e] assert(d.toPythonDict()[3][0][12][0][21] == 400)", "= Cdr() f[21] = 400 e[11] = 300 e[12] =", "def test_str(self): d = Cdr() d.setInteger(field1, 123) def test_nested(self): d", "Cdr() d.setInteger(field1, 123) d.setString(field2, \"Hello\") d.setString(field3, \"World\") return d def", "self.assertEqual(d.toString(), \"1=123\") def test_str(self): d = Cdr() d.setInteger(field1, 123) def", "e.setString(1, \"hello\") e.setString(2, \"world\") d.appendArray(1, e) f = d.getArray(1) self.assertEqual(e.getString(1),", "Cdr() d.setInteger(field1, 123) def test_nested(self): d = Cdr() e =", "self.assertEqual(e.getString(1), f[0].getString(1)) self.assertEqual(e.getString(2), f[0].getString(2)) def test_to_python_dict(self): d = Cdr() e", "Cdr import unittest field1 = 1 field2 = 2 field3", "test_to_string(self): d = Cdr() d.setInteger(field1, 123) self.assertEqual(d.toString(), \"1=123\") def test_str(self):", "self.assertEqual(e.getString(2), f[0].getString(2)) def test_to_python_dict(self): d = Cdr() e = Cdr()", "cdr import Cdr import unittest field1 = 1 field2 =", "Cdr() e = Cdr() f = Cdr() f[21] = 400", "55 class TestCdr(unittest.TestCase): def get_a_cdr(self): d = Cdr() d.setInteger(field1, 123)", "d.setString(field3, \"World\") return d def test_set_integer(self): d = self.get_a_cdr() self.assertEqual(d.getInt32(field1),", "self.get_a_cdr() d.setString(field2, \"Hello\") self.assertEqual(d.getString(field2), \"Hello\") def test_get_exception(self): d = self.get_a_cdr()", "e) f = d.getArray(1) self.assertEqual(e.getString(1), f[0].getString(1)) self.assertEqual(e.getString(2), f[0].getString(2)) def test_to_python_dict(self):", "test_str(self): d = Cdr() d.setInteger(field1, 123) def test_nested(self): d =", "123) def test_set_string(self): d = self.get_a_cdr() d.setString(field2, \"Hello\") self.assertEqual(d.getString(field2), \"Hello\")", "get_a_cdr(self): d = Cdr() d.setInteger(field1, 123) d.setString(field2, \"Hello\") d.setString(field3, \"World\")", "def test_to_python_dict(self): d = Cdr() e = Cdr() f =", "test_to_python_dict(self): d = Cdr() e = Cdr() f = Cdr()", "f[21] = 400 e[11] = 300 e[12] = [f] d[1]", "= Cdr() e.setString(1, \"hello\") e.setString(2, \"world\") d.appendArray(1, e) f =", "e[12] = [f] d[1] = 100 d[2] = 200 d[3]", "Copyright 2014-2018 Neueda Ltd. # from cdr import Cdr import", "\"Hello\") d.setString(field3, \"World\") return d def test_set_integer(self): d = self.get_a_cdr()", "300 e[12] = [f] d[1] = 100 d[2] = 200", "Cdr() e.setString(1, \"hello\") e.setString(2, \"world\") d.appendArray(1, e) f = d.getArray(1)", "d = self.get_a_cdr() with self.assertRaises(RuntimeError): d.getInteger(4) def test_to_string(self): d =", "\"hello\") e.setString(2, \"world\") d.appendArray(1, e) f = d.getArray(1) self.assertEqual(e.getString(1), f[0].getString(1))", "d[2] = 200 d[3] = [e] assert(d.toPythonDict()[3][0][12][0][21] == 400) if", "f[0].getString(1)) self.assertEqual(e.getString(2), f[0].getString(2)) def test_to_python_dict(self): d = Cdr() e =", "field1 = 1 field2 = 2 field3 = 55 class", "= [f] d[1] = 100 d[2] = 200 d[3] =", "test_set_integer(self): d = self.get_a_cdr() self.assertEqual(d.getInt32(field1), 123) def test_set_string(self): d =", "= Cdr() d.setInteger(field1, 123) d.setString(field2, \"Hello\") d.setString(field3, \"World\") return d", "d = Cdr() e = Cdr() e.setString(1, \"hello\") e.setString(2, \"world\")", "d.appendArray(1, e) f = d.getArray(1) self.assertEqual(e.getString(1), f[0].getString(1)) self.assertEqual(e.getString(2), f[0].getString(2)) def", "= d.getArray(1) self.assertEqual(e.getString(1), f[0].getString(1)) self.assertEqual(e.getString(2), f[0].getString(2)) def test_to_python_dict(self): d =", "self.assertEqual(d.getInt32(field1), 123) def test_set_string(self): d = self.get_a_cdr() d.setString(field2, \"Hello\") self.assertEqual(d.getString(field2),", "f[0].getString(2)) def test_to_python_dict(self): d = Cdr() e = Cdr() f", "d[3] = [e] assert(d.toPythonDict()[3][0][12][0][21] == 400) if __name__ == '__main__':", "Cdr() f[21] = 400 e[11] = 300 e[12] = [f]", "d = self.get_a_cdr() self.assertEqual(d.getInt32(field1), 123) def test_set_string(self): d = self.get_a_cdr()", "from cdr import Cdr import unittest field1 = 1 field2", "= [e] assert(d.toPythonDict()[3][0][12][0][21] == 400) if __name__ == '__main__': unittest.main()", "# from cdr import Cdr import unittest field1 = 1", "= 300 e[12] = [f] d[1] = 100 d[2] =", "= 200 d[3] = [e] assert(d.toPythonDict()[3][0][12][0][21] == 400) if __name__", "field3 = 55 class TestCdr(unittest.TestCase): def get_a_cdr(self): d = Cdr()", "# # Copyright 2014-2018 Neueda Ltd. # from cdr import", "class TestCdr(unittest.TestCase): def get_a_cdr(self): d = Cdr() d.setInteger(field1, 123) d.setString(field2,", "d[1] = 100 d[2] = 200 d[3] = [e] assert(d.toPythonDict()[3][0][12][0][21]", "= 400 e[11] = 300 e[12] = [f] d[1] =", "= 55 class TestCdr(unittest.TestCase): def get_a_cdr(self): d = Cdr() d.setInteger(field1,", "e[11] = 300 e[12] = [f] d[1] = 100 d[2]", "test_get_exception(self): d = self.get_a_cdr() with self.assertRaises(RuntimeError): d.getInteger(4) def test_to_string(self): d", "with self.assertRaises(RuntimeError): d.getInteger(4) def test_to_string(self): d = Cdr() d.setInteger(field1, 123)", "self.get_a_cdr() self.assertEqual(d.getInt32(field1), 123) def test_set_string(self): d = self.get_a_cdr() d.setString(field2, \"Hello\")", "d.setString(field2, \"Hello\") self.assertEqual(d.getString(field2), \"Hello\") def test_get_exception(self): d = self.get_a_cdr() with", "test_set_string(self): d = self.get_a_cdr() d.setString(field2, \"Hello\") self.assertEqual(d.getString(field2), \"Hello\") def test_get_exception(self):", "f = d.getArray(1) self.assertEqual(e.getString(1), f[0].getString(1)) self.assertEqual(e.getString(2), f[0].getString(2)) def test_to_python_dict(self): d", "d.setInteger(field1, 123) d.setString(field2, \"Hello\") d.setString(field3, \"World\") return d def test_set_integer(self):", "def test_get_exception(self): d = self.get_a_cdr() with self.assertRaises(RuntimeError): d.getInteger(4) def test_to_string(self):", "= Cdr() e = Cdr() f = Cdr() f[21] =", "= Cdr() f = Cdr() f[21] = 400 e[11] =", "import unittest field1 = 1 field2 = 2 field3 =", "def get_a_cdr(self): d = Cdr() d.setInteger(field1, 123) d.setString(field2, \"Hello\") d.setString(field3,", "e.setString(2, \"world\") d.appendArray(1, e) f = d.getArray(1) self.assertEqual(e.getString(1), f[0].getString(1)) self.assertEqual(e.getString(2),", "d = Cdr() e = Cdr() f = Cdr() f[21]", "d.setInteger(field1, 123) def test_nested(self): d = Cdr() e = Cdr()", "1 field2 = 2 field3 = 55 class TestCdr(unittest.TestCase): def", "Cdr() d.setInteger(field1, 123) self.assertEqual(d.toString(), \"1=123\") def test_str(self): d = Cdr()", "d def test_set_integer(self): d = self.get_a_cdr() self.assertEqual(d.getInt32(field1), 123) def test_set_string(self):", "d.getArray(1) self.assertEqual(e.getString(1), f[0].getString(1)) self.assertEqual(e.getString(2), f[0].getString(2)) def test_to_python_dict(self): d = Cdr()", "\"world\") d.appendArray(1, e) f = d.getArray(1) self.assertEqual(e.getString(1), f[0].getString(1)) self.assertEqual(e.getString(2), f[0].getString(2))", "return d def test_set_integer(self): d = self.get_a_cdr() self.assertEqual(d.getInt32(field1), 123) def", "d = Cdr() d.setInteger(field1, 123) self.assertEqual(d.toString(), \"1=123\") def test_str(self): d", "123) self.assertEqual(d.toString(), \"1=123\") def test_str(self): d = Cdr() d.setInteger(field1, 123)", "2 field3 = 55 class TestCdr(unittest.TestCase): def get_a_cdr(self): d =", "= self.get_a_cdr() with self.assertRaises(RuntimeError): d.getInteger(4) def test_to_string(self): d = Cdr()", "2014-2018 Neueda Ltd. # from cdr import Cdr import unittest", "[f] d[1] = 100 d[2] = 200 d[3] = [e]", "Cdr() e = Cdr() e.setString(1, \"hello\") e.setString(2, \"world\") d.appendArray(1, e)", "TestCdr(unittest.TestCase): def get_a_cdr(self): d = Cdr() d.setInteger(field1, 123) d.setString(field2, \"Hello\")", "d.setString(field2, \"Hello\") d.setString(field3, \"World\") return d def test_set_integer(self): d =", "e = Cdr() e.setString(1, \"hello\") e.setString(2, \"world\") d.appendArray(1, e) f", "test_nested(self): d = Cdr() e = Cdr() e.setString(1, \"hello\") e.setString(2,", "field2 = 2 field3 = 55 class TestCdr(unittest.TestCase): def get_a_cdr(self):", "# Copyright 2014-2018 Neueda Ltd. # from cdr import Cdr", "= Cdr() e = Cdr() e.setString(1, \"hello\") e.setString(2, \"world\") d.appendArray(1,", "= 100 d[2] = 200 d[3] = [e] assert(d.toPythonDict()[3][0][12][0][21] ==", "\"Hello\") def test_get_exception(self): d = self.get_a_cdr() with self.assertRaises(RuntimeError): d.getInteger(4) def", "123) d.setString(field2, \"Hello\") d.setString(field3, \"World\") return d def test_set_integer(self): d", "= 2 field3 = 55 class TestCdr(unittest.TestCase): def get_a_cdr(self): d", "= Cdr() d.setInteger(field1, 123) def test_nested(self): d = Cdr() e", "def test_nested(self): d = Cdr() e = Cdr() e.setString(1, \"hello\")", "def test_set_string(self): d = self.get_a_cdr() d.setString(field2, \"Hello\") self.assertEqual(d.getString(field2), \"Hello\") def", "def test_to_string(self): d = Cdr() d.setInteger(field1, 123) self.assertEqual(d.toString(), \"1=123\") def", "self.get_a_cdr() with self.assertRaises(RuntimeError): d.getInteger(4) def test_to_string(self): d = Cdr() d.setInteger(field1,", "d = Cdr() d.setInteger(field1, 123) def test_nested(self): d = Cdr()", "200 d[3] = [e] assert(d.toPythonDict()[3][0][12][0][21] == 400) if __name__ ==", "\"1=123\") def test_str(self): d = Cdr() d.setInteger(field1, 123) def test_nested(self):", "unittest field1 = 1 field2 = 2 field3 = 55", "d = self.get_a_cdr() d.setString(field2, \"Hello\") self.assertEqual(d.getString(field2), \"Hello\") def test_get_exception(self): d", "= Cdr() d.setInteger(field1, 123) self.assertEqual(d.toString(), \"1=123\") def test_str(self): d =", "123) def test_nested(self): d = Cdr() e = Cdr() e.setString(1,", "Neueda Ltd. # from cdr import Cdr import unittest field1", "= self.get_a_cdr() self.assertEqual(d.getInt32(field1), 123) def test_set_string(self): d = self.get_a_cdr() d.setString(field2,", "f = Cdr() f[21] = 400 e[11] = 300 e[12]", "def test_set_integer(self): d = self.get_a_cdr() self.assertEqual(d.getInt32(field1), 123) def test_set_string(self): d", "d.setInteger(field1, 123) self.assertEqual(d.toString(), \"1=123\") def test_str(self): d = Cdr() d.setInteger(field1,", "d.getInteger(4) def test_to_string(self): d = Cdr() d.setInteger(field1, 123) self.assertEqual(d.toString(), \"1=123\")", "e = Cdr() f = Cdr() f[21] = 400 e[11]" ]
[ "april, and end # on last sunday of october. if", "of october. if not isend: kwargs[\"month\"] = 4 kwargs[\"day\"] =", "%s>\" % repr(self._tzid) __reduce__ = object.__reduce__ class tzical(object): def __init__(self,", "values of type unsigned # char; each one tells which", "len(keys) > 1: raise ValueError(\"more than one timezone available\") tzid", "if value in (\"STANDARD\", \"DAYLIGHT\"): # Process component pass else:", "(self.__class__.__name__, repr(self._name), self._offset.days*86400+self._offset.seconds) __reduce__ = object.__reduce__ class tzlocal(datetime.tzinfo): _std_offset =", "self._find_comp(dt).tzname def __repr__(self): return \"<tzicalvtz %s>\" % repr(self._tzid) __reduce__ =", "if name == \"DTSTART\": rrulelines.append(line) founddtstart = True elif name", "the tz source file # is setup to wall time,", "return \"%s(%s)\" % (self.__class__.__name__, repr(self._s)) if sys.platform != \"win32\": TZFILES", "know if you have comments # about this. laststdoffset =", "kwargs = {} if x.month is not None: kwargs[\"month\"] =", "relativedelta.relativedelta(**kwargs) def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp(object):", "= gettz(name) if not tz: for c in name: #", "self.delta == other.delta and self.isdst == other.isdst and self.abbr ==", "tz = tzfile(name) else: tz = None else: for path", "# #>>> import tz, datetime #>>> t = tz.tzlocal() #>>>", "relativedelta.SU(+1) else: kwargs[\"month\"] = 10 kwargs[\"day\"] = 31 kwargs[\"weekday\"] =", "is not None: l.append(\"%s=%s\" % (attr, repr(value))) return \"%s(%s)\" %", "\"%(name, parms[0])) tzoffsetfrom = self._parse_offset(value) elif name == \"TZOFFSETTO\": if", "if isinstance(fileobj, string_types): self._filename = fileobj fileobj = open(fileobj, 'rb')", "#>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT' #>>>", "value in (\"STANDARD\", \"DAYLIGHT\"): # Process component pass else: raise", "comps) invtz = False elif value == comptype: if not", "in state: setattr(self, name, state[name]) class tzfile(datetime.tzinfo): # http://www.twinsun.com/tz/tz-link.htm #", "other.isstd and self.isgmt == other.isgmt) def __ne__(self, other): return not", "values, written in standard byte order; the # first value", "dt >= start or dt < end def __eq__(self, other):", "(self._trans_list == other._trans_list and self._trans_idx == other._trans_idx and self._ttinfo_list ==", "and other._offset == ZERO)) def __ne__(self, other): return not self.__eq__(other)", "other._std_offset and self._dst_offset == other._dst_offset) return True def __ne__(self, other):", "type long, in a standard byte # order, followed by", "_isdst(self, dt): # We can't use mktime here. It is", "ttisstdcnt, fileobj.read(ttisstdcnt)) # Finally, there are tzh_ttisgmtcnt UTC/local # indicators,", "None rrulelines = [] tzname = None elif name ==", "elif name == \"END\": if value == \"VTIMEZONE\": if comptype:", "if name in (\"GMT\", \"UTC\"): tz = tzutc() elif name", "Python 2 tzname() API changed in Python 3. It used", "tz = None if tzwin: try: tz = tzwin(name) except", "_dst_offset = _std_offset def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset", "number of UTC/local indicators stored in the file. ttisgmtcnt, #", "_tzicalvtz(tzid, comps) invtz = False elif value == comptype: if", "False return (self._std_offset == other._std_offset and self._dst_offset == other._dst_offset) return", "tz.tzlocal() #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST'", "(self._std_offset == other._std_offset and self._dst_offset == other._dst_offset) return True def", "Python 3. It used to return bytes, but was changed", "comptype = None else: raise ValueError(\"invalid component end: \"+value) elif", "# Each is used as a transition time (as returned", "component rr = None if rrulelines: rr = rrule.rrulestr(\"\\n\".join(rrulelines), compatible=True,", "(comptype == \"DAYLIGHT\"), tzname, rr) comps.append(comp) comptype = None else:", "string_types __license__ = \"Simplified BSD\" __all__ = [\"tzutc\", \"tzoffset\", \"tzlocal\",", "if compdt and (not lastcompdt or lastcompdt < compdt): lastcompdt", "or not. # # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,", "four-byte values of type long, written in a # ``standard''", "__getstate__(self): state = {} for name in self.__slots__: state[name] =", "= parms[1:] if invtz: if name == \"BEGIN\": if value", "def __eq__(self, other): return (isinstance(other, tzutc) or (isinstance(other, tzoffset) and", "and self._dst_offset == other._dst_offset) return True def __ne__(self, other): return", "if invtz: if name == \"BEGIN\": if value in (\"STANDARD\",", "be zero). typecnt, # The number of characters of \"time", "comp.isdst: lastcomp = comp break else: lastcomp = comp[0] self._cachedate.insert(0,", "= _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype == \"DAYLIGHT\"), tzname, rr) comps.append(comp) comptype", "the second gives the total number of # leap seconds", "line: continue name, value = line.split(':', 1) parms = name.split(';')", "local time # change. if timecnt: self._trans_list = struct.unpack(\">%dl\" %", "comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype == \"DAYLIGHT\"), tzname, rr) comps.append(comp)", "at which the rules for computing local time # change.", "one-byte value for tt_isdst # and a one-byte value for", "if len(self._comps) == 1: return self._comps[0] dt = dt.replace(tzinfo=None) try:", "None or name == \":\": for filepath in TZFILES: if", "property: \"+name) else: if name == \"TZID\": if parms: raise", "i in range(len(self._trans_list)): tti = self._trans_idx[i] if not tti.isdst: #", "are tzh_leapcnt pairs of four-byte # values, written in standard", "state def __setstate__(self, state): for name in self.__slots__: if name", "if os.path.isabs(name): if os.path.isfile(name): tz = tzfile(name) else: tz =", "self._ttinfo_before = None if self._ttinfo_list: if not self._trans_list: self._ttinfo_std =", "10 kwargs[\"day\"] = 31 kwargs[\"weekday\"] = relativedelta.SU(-1) if x.time is", "above yields the following result: # #>>> import tz, datetime", "self._ttinfo_list = [] for i in range(typecnt): gmtoff, isdst, abbrind", "idx -= 1 else: return self._ttinfo_std else: return self._trans_idx[idx-1] def", "if name == \"TZID\": if parms: raise ValueError(\"unsupported TZID parm:", "We'll look for the # first standard component, or the", "# they tell whether the transition times associated # with", "tti = _ttinfo() tti.offset = gmtoff tti.delta = datetime.timedelta(seconds=gmtoff) tti.isdst", "Each ttinfo structure is written as a four-byte value #", "# Set standard, dst, and before ttinfos. before will be", "None else: self._start_delta = self._delta(res.start) if self._start_delta: self._end_delta = self._delta(res.end,", "abbr = fileobj.read(charcnt).decode() # Then there are tzh_leapcnt pairs of", "if not res.dstabbr: self._start_delta = None self._end_delta = None else:", "else: self._start_delta = self._delta(res.start) if self._start_delta: self._end_delta = self._delta(res.end, isend=1)", "\"VTIMEZONE\": if comptype: raise ValueError(\"component not closed: \"+comptype) if not", "ValueError(\"mandatory TZOFFSETFROM not found\") if tzoffsetto is None: raise ValueError(\"mandatory", "is written first). if fileobj.read(4).decode() != \"TZif\": raise ValueError(\"magic not", "name must have at least one offset to be a", "invtz = False comptype = None for line in lines:", "hour near to a change is DST or not. #", "used when a given time is before any transitions, #", "other.delta and self.isdst == other.isdst and self.abbr == other.abbr and", "in self._comps: if not comp.isdst: lastcomp = comp break else:", "import tzwin, tzwinlocal except (ImportError, OSError): tzwin, tzwinlocal = None,", "the file. ttisstdcnt, # The number of leap seconds for", "kwargs[\"seconds\"] -= delta.seconds+delta.days*86400 return relativedelta.relativedelta(**kwargs) def __repr__(self): return \"%s(%s)\" %", "<<EMAIL>> This module offers extensions to the standard Python datetime", "tzutc(datetime.tzinfo): def utcoffset(self, dt): return ZERO def dst(self, dt): return", "not self.__eq__(other) def __getstate__(self): state = {} for name in", "tzwin, tzwinlocal except (ImportError, OSError): tzwin, tzwinlocal = None, None", "self._start_delta = start if dstabbr and end is None: self._end_delta", "not parser: from dateutil import parser self._s = s res", "filepath = os.path.join(path, name) if not os.path.isfile(filepath): filepath = filepath.replace('", "break else: lastcomp = comp[0] self._cachedate.insert(0, dt) self._cachecomp.insert(0, lastcomp) if", "is dst time. Convert to std. self._trans_list[i] += laststdoffset self._trans_list", "not self.__eq__(other) def __repr__(self): return \"%s(...)\" % self.__class__.__name__ __reduce__ =", "is not None: kwargs[\"nlyearday\"] = x.jyday if not kwargs: #", "% repr(self._tzid) __reduce__ = object.__reduce__ class tzical(object): def __init__(self, fileobj):", "vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz = False elif value", "= repr(fileobj) # From tzfile(5): # # The time zone", "len(keys) == 0: raise ValueError(\"no timezones defined\") elif len(keys) >", "res.stdoffset, res.dstabbr, res.dstoffset, start=False, end=False) if not res.dstabbr: self._start_delta =", "change is DST or not. # # timestamp = time.mktime((dt.year,", "s = s.strip() if not s: raise ValueError(\"empty offset\") if", "None tzoffsetto = None rrulelines = [] tzname = None", "in self._trans_idx: trans_idx.append(self._ttinfo_list[idx]) self._trans_idx = tuple(trans_idx) # Set standard, dst,", "= None self._ttinfo_before = None if self._ttinfo_list: if not self._trans_list:", "zone information files, followed by # sixteen bytes reserved for", "return (self._std_offset == other._std_offset and self._dst_offset == other._dst_offset) return True", "if self._isdst(dt): return self._dst_abbr else: return self._std_abbr def _isdst(self, dt):", "defined\") elif len(keys) > 1: raise ValueError(\"more than one timezone", "start=None, end=None): global relativedelta if not relativedelta: from dateutil import", "in UTF-8 with CRLF elif hasattr(fileobj, \"name\"): self._s = fileobj.name", "repr(self._s)) if sys.platform != \"win32\": TZFILES = [\"/etc/localtime\", \"localtime\"] TZPATHS", "if not founddtstart: raise ValueError(\"mandatory DTSTART not found\") if tzoffsetfrom", "(attr, repr(value))) return \"%s(%s)\" % (self.__class__.__name__, \", \".join(l)) def __eq__(self,", "\"win32\": TZFILES = [\"/etc/localtime\", \"localtime\"] TZPATHS = [\"/usr/share/zoneinfo\", \"/usr/lib/zoneinfo\", \"/etc/zoneinfo\"]", "= tzfile(filepath) break except (IOError, OSError, ValueError): pass else: tz", "= self._find_ttinfo(dt) if not tti.isdst: return ZERO # The documentation", "self._delta(res.end, isend=1) def _delta(self, x, isend=0): kwargs = {} if", "tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset, start=False, end=False) if not res.dstabbr:", "leapcnt: leap = struct.unpack(\">%dl\" % (leapcnt*2), fileobj.read(leapcnt*8)) # Then there", "indexes for ttinfo objects. trans_idx = [] for idx in", "the file. leapcnt, # The number of \"transition times\" for", "def _find_ttinfo(self, dt, laststd=0): timestamp = ((dt.toordinal() - EPOCHORDINAL) *", "of # ``local time'' types described in the file is", "in the file (must not be zero). typecnt, # The", "long, sorted in ascending order. # These values are written", "utcoffset(self, dt): return self._find_comp(dt).tzoffsetto def dst(self, dt): comp = self._find_comp(dt)", "0 while i < len(lines): line = lines[i].rstrip() if not", "not None: self._dst_offset = self._std_offset+datetime.timedelta(hours=+1) else: self._dst_offset = ZERO if", "isdst self.tzname = tzname self.rrule = rrule class _tzicalvtz(datetime.tzinfo): def", "if value is not None: l.append(\"%s=%s\" % (attr, repr(value))) return", "self._s = fileobj.name else: self._s = repr(fileobj) self._vtz = {}", "local time types were specified as standard # time or", "right # way to implement this. @tzname_in_python2 def tzname(self, dt):", "None if not name: try: name = os.environ[\"TZ\"] except KeyError:", "attr) if value is not None: l.append(\"%s=%s\" % (attr, repr(value)))", "# http://python.org/sf/1447945 for some information. gmtoff = (gmtoff+30)//60*60 tti =", "except ValueError: pass break else: if name in (\"GMT\", \"UTC\"):", "isgmt[i] != 0) self._ttinfo_list.append(tti) # Replace ttinfo indexes for ttinfo", "Default is 2AM. kwargs[\"seconds\"] = 7200 if isend: # Convert", "what to do when a given # time is before", "a one-byte value for tt_isdst # and a one-byte value", "\"TZOFFSETFROM\": if parms: raise ValueError(\"unsupported %s parm: %s \"%(name, parms[0]))", "__ne__(self, other): return not self.__eq__(other) def __repr__(self): return \"%s(%s)\" %", "(not lastcompdt or lastcompdt < compdt): lastcompdt = compdt lastcomp", "value == \"VTIMEZONE\": tzid = None comps = [] invtz", "= object.__reduce__ class tzlocal(datetime.tzinfo): _std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: _dst_offset", "rrule.rrulestr(\"\\n\".join(rrulelines), compatible=True, ignoretz=True, cache=True) comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype ==", "of UTC/local indicators stored in the file. ttisgmtcnt, # The", "state[name] = getattr(self, name, None) return state def __setstate__(self, state):", "\"tzoffset\", \"tzlocal\", \"tzfile\", \"tzrange\", \"tzstr\", \"tzical\", \"tzwin\", \"tzwinlocal\", \"gettz\"] relativedelta", "rrulelines.append(line) founddtstart = True elif name in (\"RRULE\", \"RDATE\", \"EXRULE\",", "raise ValueError(\"unsupported property: \"+name) else: if name == \"TZID\": if", "= object.__reduce__ class _ttinfo(object): __slots__ = [\"offset\", \"delta\", \"isdst\", \"abbr\",", "in self.__slots__: value = getattr(self, attr) if value is not", "comps=[]): self._tzid = tzid self._comps = comps self._cachedate = []", "if self._isdst(dt): return self._dst_offset else: return self._std_offset def dst(self, dt):", "# Convert to standard time, to follow the documented way", "if not isinstance(other, tzrange): return False return (self._std_abbr == other._std_abbr", "class tzstr(tzrange): def __init__(self, s): global parser if not parser:", "in self.__slots__: setattr(self, attr, None) def __repr__(self): l = []", "tzid: raise ValueError(\"mandatory TZID not found\") if not comps: raise", "\"\"\"Change unicode output into bytestrings in Python 2 tzname() API", "self._start_delta == other._start_delta and self._end_delta == other._end_delta) def __ne__(self, other):", "We must initialize it first, since _delta() needs # _std_offset", "if not rrule: from dateutil import rrule if isinstance(fileobj, string_types):", "pairs of values are sorted in ascending order # by", "gmtoff = (gmtoff+30)//60*60 tti = _ttinfo() tti.offset = gmtoff tti.delta", "timezone available\") tzid = keys[0] return self._vtz.get(tzid) def _parse_offset(self, s):", "bytes reserved for future use, followed by # six four-byte", "struct.unpack(\">%dB\" % timecnt, fileobj.read(timecnt)) else: self._trans_idx = [] # Each", "self.__eq__(other) def __getstate__(self): state = {} for name in self.__slots__:", "return ZERO # The documentation says that utcoffset()-dst() must #", "= None, None def tzname_in_python2(myfunc): \"\"\"Change unicode output into bytestrings", "is needed\") # Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz", "is associated # with the same-indexed transition time. These values", "line.split(':', 1) parms = name.split(';') if not parms: raise ValueError(\"empty", "lines[i] else: i += 1 tzid = None comps =", "elif name == \"BEGIN\" and value == \"VTIMEZONE\": tzid =", "# of working with the extra hour. See the documentation", "# leap seconds to be applied after the given time.", ") = struct.unpack(\">6l\", fileobj.read(24)) # The above header is followed", "about this. laststdoffset = 0 self._trans_list = list(self._trans_list) for i", "\"DTSTART\": rrulelines.append(line) founddtstart = True elif name in (\"RRULE\", \"RDATE\",", "in (\"RRULE\", \"RDATE\", \"EXRULE\", \"EXDATE\"): rrulelines.append(line) elif name == \"TZOFFSETFROM\":", "struct.unpack(\">%dl\" % timecnt, fileobj.read(timecnt*4)) else: self._trans_list = [] # Next", "return time.localtime(timestamp+time.timezone).tm_isdst def __eq__(self, other): if not isinstance(other, tzlocal): return", "the timezone -3. if res.stdabbr in (\"GMT\", \"UTC\"): res.stdoffset *=", "array of # time zone abbreviation characters that follow the", "def __init__(self, fileobj): global rrule if not rrule: from dateutil", "= value elif name == \"COMMENT\": pass else: raise ValueError(\"unsupported", "are used when # a time zone file is used", "relativedelta.weekday(x.weekday, x.week) if x.week > 0: kwargs[\"day\"] = 1 else:", "self._s = repr(fileobj) self._vtz = {} self._parse_rfc(fileobj.read()) def keys(self): return", "= [\"tzutc\", \"tzoffset\", \"tzlocal\", \"tzfile\", \"tzrange\", \"tzstr\", \"tzical\", \"tzwin\", \"tzwinlocal\",", "the time (as # returned by time(2)) at which a", "time. # # I'm not sure about this. In my", "= tzid self._comps = comps self._cachedate = [] self._cachecomp =", "first component, if # none is found. for comp in", "compatibility with the TZ variable handling. # GMT-3 actually *means*", "end # on last sunday of october. if not isend:", "not res.dstabbr: self._start_delta = None self._end_delta = None else: self._start_delta", "list self._ttinfo_list = [] for i in range(typecnt): gmtoff, isdst,", "lines = s.splitlines() if not lines: raise ValueError(\"empty string\") #", "os.path.isabs(name): if os.path.isfile(name): tz = tzfile(name) else: tz = None", "if c in \"0123456789\": try: tz = tzstr(name) except ValueError:", "if timecnt: self._trans_list = struct.unpack(\">%dl\" % timecnt, fileobj.read(timecnt*4)) else: self._trans_list", "# tt_abbrind serves as an index into the array of", "__eq__(self, other): if not isinstance(other, tzfile): return False return (self._trans_list", "i > 0 and line[0] == \" \": lines[i-1] +=", "None: self._end_delta = relativedelta.relativedelta( hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) else: self._end_delta", "before ttinfos. before will be # used when a given", "= [] for attr in self.__slots__: value = getattr(self, attr)", "_dst_offset = datetime.timedelta(seconds=-time.altzone) else: _dst_offset = _std_offset def utcoffset(self, dt):", "tzname(self, dt): return \"UTC\" def __eq__(self, other): return (isinstance(other, tzutc)", "not lines: raise ValueError(\"empty string\") # Unfold i = 0", "tzh_leapcnt pairs of four-byte # values, written in standard byte", "they tell whether the transition times associated # with local", "the file. charcnt, ) = struct.unpack(\">6l\", fileobj.read(24)) # The above", "serves as an index into the array of # time", "by localtime(3), and # tt_abbrind serves as an index into", "1 else: kwargs[\"day\"] = 31 elif x.day: kwargs[\"day\"] = x.day", "# timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400 + dt.hour", "= self._ttinfo_first = self._ttinfo_list[0] else: for i in range(timecnt-1, -1,", "other._ttinfo_list) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return", "= x.time else: # Default is 2AM. kwargs[\"seconds\"] = 7200", "= struct.unpack(\">%db\" % ttisgmtcnt, fileobj.read(ttisgmtcnt)) # ** Everything has been", "-> STD compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True) else: compdt = comp.rrule.before(dt,", "ValueError(\"more than one timezone available\") tzid = keys[0] return self._vtz.get(tzid)", "except OSError: pass if not tz: from dateutil.zoneinfo import gettz", "this. @tzname_in_python2 def tzname(self, dt): if not self._ttinfo_std: return None", "in start/end # to avoid building it two times. tzrange.__init__(self,", "accept sub-minute timezones. Check # http://python.org/sf/1447945 for some information. gmtoff", "non-dst ttinfo, or to # the first dst, if all", "dt.replace(tzinfo=None) if start < end: return dt >= start and", "comps = [] invtz = False comptype = None for", "if comptype: raise ValueError(\"component not closed: \"+comptype) if not tzid:", "if isend: # Convert to standard time, to follow the", "other.isdst and self.abbr == other.abbr and self.isstd == other.isstd and", "tti = self._find_ttinfo(dt) if not tti.isdst: return ZERO # The", "ValueError(\"invalid offset: \"+s) def _parse_rfc(self, s): lines = s.splitlines() if", "name in (\"GMT\", \"UTC\"): tz = tzutc() elif name in", "Python's # datetime doesn't accept sub-minute timezones. Check # http://python.org/sf/1447945", "else: compdt = comp.rrule.before(dt, inc=True) if compdt and (not lastcompdt", "year = datetime.datetime(dt.year, 1, 1) start = year+self._start_delta end =", "else: signal = +1 if len(s) == 4: return (int(s[:2])*3600+int(s[2:])*60)*signal", "== 1: return self._comps[0] dt = dt.replace(tzinfo=None) try: return self._cachecomp[self._cachedate.index(dt)]", "= open(fileobj, 'rb') elif hasattr(fileobj, \"name\"): self._filename = fileobj.name else:", "name in state: setattr(self, name, state[name]) class tzfile(datetime.tzinfo): # http://www.twinsun.com/tz/tz-link.htm", "standard, dst, and before ttinfos. before will be # used", "next in the file. if timecnt: self._trans_idx = struct.unpack(\">%dB\" %", "# a time zone file is used in handling POSIX-style", "and (not lastcompdt or lastcompdt < compdt): lastcompdt = compdt", "with the extra hour. See the documentation # of the", "== other._start_delta and self._end_delta == other._end_delta) def __ne__(self, other): return", "and not tti.isdst: self._ttinfo_std = tti elif not self._ttinfo_dst and", "time is before any transitions, # and will be set", "all of them are dst. self._ttinfo_std = None self._ttinfo_dst =", "(self._filename,)) class tzrange(datetime.tzinfo): def __init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None,", "not found\") fileobj.read(16) ( # The number of UTC/local indicators", "'_') if not os.path.isfile(filepath): continue try: tz = tzfile(filepath) break", "with the same-indexed transition time. These values # serve as", "or (isinstance(other, tzoffset) and other._offset == ZERO)) def __ne__(self, other):", "def __init__(self, s): global parser if not parser: from dateutil", "dt) self._cachecomp.insert(0, lastcomp) if len(self._cachedate) > 10: self._cachedate.pop() self._cachecomp.pop() return", "isstd[i] != 0) tti.isgmt = (ttisgmtcnt > i and isgmt[i]", "> 0: kwargs[\"day\"] = 1 else: kwargs[\"day\"] = 31 elif", "= datetime.timedelta(0) EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal() class tzutc(datetime.tzinfo): def utcoffset(self, dt):", "= [\"/usr/share/zoneinfo\", \"/usr/lib/zoneinfo\", \"/etc/zoneinfo\"] else: TZFILES = [] TZPATHS =", "= None rrulelines = [] tzname = None elif name", "line[1:] del lines[i] else: i += 1 tzid = None", "None, None def tzname_in_python2(myfunc): \"\"\"Change unicode output into bytestrings in", "serve as indices into an array of ttinfo structures that", "tzoffsetto = self._parse_offset(value) elif name == \"TZNAME\": if parms: raise", "class _ttinfo(object): __slots__ = [\"offset\", \"delta\", \"isdst\", \"abbr\", \"isstd\", \"isgmt\"]", "one offset to be a tzstr if c in \"0123456789\":", "self._std_offset == other._std_offset and self._dst_offset == other._dst_offset and self._start_delta ==", "tti.isdst: self._ttinfo_dst = tti if self._ttinfo_std and self._ttinfo_dst: break else:", "clock time, and are used when # a time zone", "time zone information files, followed by # sixteen bytes reserved", "self._ttinfo_std = tti elif not self._ttinfo_dst and tti.isdst: self._ttinfo_dst =", "It is unstable when deciding if # the hour near", "comp = self._find_comp(dt) if comp.isdst: return comp.tzoffsetdiff else: return ZERO", "laststd=1).delta # An alternative for that would be: # #", "+1)[s[0]=='+'] s = s[1:] else: signal = +1 if len(s)", "start if dstabbr and end is None: self._end_delta = relativedelta.relativedelta(", "in TZPATHS: filepath = os.path.join(path, filename) if os.path.isfile(filepath): break else:", "leap seconds for which data is # stored in the", "if tzid is None: keys = list(self._vtz.keys()) if len(keys) ==", "# Here we break the compatibility with the TZ variable", "comps: raise ValueError(\"at least one component is needed\") # Process", "self._find_ttinfo(dt).delta def dst(self, dt): if not self._ttinfo_dst: return ZERO tti", "# begin with the magic characters \"TZif\" to identify #", "self._dst_offset else: return self._std_offset def dst(self, dt): if self._isdst(dt): return", "time.localtime(timestamp).tm_isdst # # The code above yields the following result:", "for tt_abbrind. In each # structure, tt_gmtoff gives the number", "else: lastcomp = comp[0] self._cachedate.insert(0, dt) self._cachecomp.insert(0, lastcomp) if len(self._cachedate)", "__reduce__ = object.__reduce__ class _ttinfo(object): __slots__ = [\"offset\", \"delta\", \"isdst\",", "0: tti = self._trans_idx[idx-1] if not tti.isdst: return tti idx", "parms[0])) tzoffsetfrom = self._parse_offset(value) elif name == \"TZOFFSETTO\": if parms:", "__repr__(self): return \"%s(%s, %s)\" % (self.__class__.__name__, repr(self._name), self._offset.days*86400+self._offset.seconds) __reduce__ =", "# return time.localtime(timestamp).tm_isdst # # The code above yields the", "def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset else: return self._std_offset", "== other._std_offset and self._dst_offset == other._dst_offset and self._start_delta == other._start_delta", "name: # name must have at least one offset to", "near to a change is DST or not. # #", "= self._ttinfo_dst for tti in self._ttinfo_list: if not tti.isdst: self._ttinfo_before", "not self._ttinfo_dst: return ZERO tti = self._find_ttinfo(dt) if not tti.isdst:", "None: raise ValueError(\"mandatory TZOFFSETFROM not found\") if tzoffsetto is None:", "\"COMMENT\"): pass else: raise ValueError(\"unsupported property: \"+name) elif name ==", "isdst, tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff", "any transitions, # and will be set to the first", "None def tzname_in_python2(myfunc): \"\"\"Change unicode output into bytestrings in Python", "self._dst_offset = ZERO if dstabbr and start is None: self._start_delta", "__repr__(self): return \"%s(...)\" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzstr(tzrange):", "value is written first). if fileobj.read(4).decode() != \"TZif\": raise ValueError(\"magic", "os.path.isfile(name): tz = tzfile(name) else: tz = None else: for", "ValueError(\"mandatory DTSTART not found\") if tzoffsetfrom is None: raise ValueError(\"mandatory", "if s[0] in ('+', '-'): signal = (-1, +1)[s[0]=='+'] s", "= fileobj fileobj = open(fileobj, 'rb') elif hasattr(fileobj, \"name\"): self._filename", "if self._ttinfo_dst and not self._ttinfo_std: self._ttinfo_std = self._ttinfo_dst for tti", "= self._std_offset+datetime.timedelta(hours=+1) else: self._dst_offset = ZERO if dstabbr and start", "-1 # We must initialize it first, since _delta() needs", "self._offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt): return self._offset def dst(self,", "written first). if fileobj.read(4).decode() != \"TZif\": raise ValueError(\"magic not found\")", "each pair gives the time (as # returned by time(2))", "# Not used, for now if leapcnt: leap = struct.unpack(\">%dl\"", "structure(s) in the file. ttinfo = [] for i in", "used by tzset(3) # begin with the magic characters \"TZif\"", "# is stored in the file (must not be zero).", "self.__eq__(other) def __repr__(self): return \"%s(...)\" % self.__class__.__name__ __reduce__ = object.__reduce__", "four-byte # values, written in standard byte order; the #", "== \"TZNAME\": if parms: raise ValueError(\"unsupported TZNAME parm: \"+parms[0]) tzname", "other._dst_abbr and self._std_offset == other._std_offset and self._dst_offset == other._dst_offset and", "be the right # way to implement this. @tzname_in_python2 def", "of each pair gives the time (as # returned by", "Unfold i = 0 while i < len(lines): line =", "tti.offset else: # This is dst time. Convert to std.", "dt): return time.tzname[self._isdst(dt)] def _isdst(self, dt): # We can't use", "# # I'm not sure about this. In my tests,", "the right # way to implement this. @tzname_in_python2 def tzname(self,", "__repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp(object): def __init__(self,", "self._tzid = tzid self._comps = comps self._cachedate = [] self._cachecomp", "to return bytes, but was changed to unicode strings \"\"\"", "# RFC says nothing about what to do when a", "Process component pass else: raise ValueError(\"unknown component: \"+value) comptype =", "tzname = value elif name == \"COMMENT\": pass else: raise", "= x.yday elif x.jyday is not None: kwargs[\"nlyearday\"] = x.jyday", "def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return \"%s(%s)\"", "dt): comp = self._find_comp(dt) if comp.isdst: return comp.tzoffsetdiff else: return", "be # used when a given time is before any", "constant for every dt. return tti.delta-self._find_ttinfo(dt, laststd=1).delta # An alternative", "== \"TZOFFSETFROM\": if parms: raise ValueError(\"unsupported %s parm: %s \"%(name,", "= time.mktime((dt.year, dt.month, dt.day, dt.hour, # dt.minute, dt.second, dt.weekday(), 0,", "must # be constant for every dt. return tti.delta-self._find_ttinfo(dt, laststd=1).delta", "import time from mo_future import PY3, string_types __license__ = \"Simplified", "= [] def gettz(name=None): tz = None if not name:", "# Here is a more stable implementation: # timestamp =", "first value of each pair gives the time (as #", "for future use, followed by # six four-byte values of", "= s.strip() if not s: raise ValueError(\"empty offset\") if s[0]", "information files used by tzset(3) # begin with the magic", "self._trans_list[i] += tti.offset laststdoffset = tti.offset else: # This is", "('+', '-'): signal = (-1, +1)[s[0]=='+'] s = s[1:] else:", "= None tzoffsetto = None rrulelines = [] tzname =", "s[1:] else: signal = +1 if len(s) == 4: return", "isstd = struct.unpack(\">%db\" % ttisstdcnt, fileobj.read(ttisstdcnt)) # Finally, there are", "# about this. laststdoffset = 0 self._trans_list = list(self._trans_list) for", "else: tz = None if tzwin: try: tz = tzwin(name)", "begin with the magic characters \"TZif\" to identify # them", "= comp break else: lastcomp = comp[0] self._cachedate.insert(0, dt) self._cachecomp.insert(0,", "tzrange): return False return (self._std_abbr == other._std_abbr and self._dst_abbr ==", "are off, so it should be in wall time. OTOH,", "dateutil import parser self._s = s res = parser._parsetz(s) if", "kwargs[\"seconds\"] = 7200 if isend: # Convert to standard time,", "[] for i in range(typecnt): gmtoff, isdst, abbrind = ttinfo[i]", "comptype: raise ValueError(\"component not closed: \"+comptype) if not tzid: raise", "name, value = line.split(':', 1) parms = name.split(';') if not", "def _parse_offset(self, s): s = s.strip() if not s: raise", "ftp://ftp.iana.org/tz/tz*.tar.gz def __init__(self, fileobj): if isinstance(fileobj, string_types): self._filename = fileobj", "time'' types described in the file is associated # with", "standard Python datetime module. \"\"\" import datetime import os import", "for which data is # stored in the file. leapcnt,", "None elif name == \"END\": if value == \"VTIMEZONE\": if", "return inner_func ZERO = datetime.timedelta(0) EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal() class tzutc(datetime.tzinfo):", "have comments # about this. laststdoffset = 0 self._trans_list =", "self._dst_offset-self._std_offset kwargs[\"seconds\"] -= delta.seconds+delta.days*86400 return relativedelta.relativedelta(**kwargs) def __repr__(self): return \"%s(%s)\"", "says nothing about what to do when a given #", "to identify # them as time zone information files, followed", "\"/usr/lib/zoneinfo\", \"/etc/zoneinfo\"] else: TZFILES = [] TZPATHS = [] def", "break the compatibility with the TZ variable handling. # GMT-3", "none is found. for comp in self._comps: if not comp.isdst:", "# ical should be encoded in UTF-8 with CRLF elif", "<NAME> <<EMAIL>> This module offers extensions to the standard Python", "tzname(self, dt): if self._isdst(dt): return self._dst_abbr else: return self._std_abbr def", "not isend: kwargs[\"month\"] = 4 kwargs[\"day\"] = 1 kwargs[\"weekday\"] =", "ZERO @tzname_in_python2 def tzname(self, dt): return time.tzname[self._isdst(dt)] def _isdst(self, dt):", "raise ValueError(\"invalid component end: \"+value) elif comptype: if name ==", "tzh_timecnt one-byte values of type unsigned # char; each one", "2 tzname() API changed in Python 3. It used to", "= datetime.datetime(dt.year, 1, 1) start = year+self._start_delta end = year+self._end_delta", "kwargs[\"month\"] = 4 kwargs[\"day\"] = 1 kwargs[\"weekday\"] = relativedelta.SU(+1) else:", "== other.abbr and self.isstd == other.isstd and self.isgmt == other.isgmt)", "= comp.rrule.before(dt, inc=True) if compdt and (not lastcompdt or lastcompdt", "= x.month if x.weekday is not None: kwargs[\"weekday\"] = relativedelta.weekday(x.weekday,", "which data # is stored in the file (must not", "environment variables. if ttisstdcnt: isstd = struct.unpack(\">%db\" % ttisstdcnt, fileobj.read(ttisstdcnt))", "continue try: tz = tzfile(filepath) break except (IOError, OSError, ValueError):", "in range(timecnt-1, -1, -1): tti = self._trans_idx[i] if not self._ttinfo_std", "rules for computing local time # change. if timecnt: self._trans_list", "abbreviation characters that follow the # ttinfo structure(s) in the", "tzid is None: keys = list(self._vtz.keys()) if len(keys) == 0:", "tells whether # tm_isdst should be set by localtime(3), and", "not parms: raise ValueError(\"empty property name\") name = parms[0].upper() parms", "return (self._trans_list == other._trans_list and self._trans_idx == other._trans_idx and self._ttinfo_list", "more stable implementation: # timestamp = ((dt.toordinal() - EPOCHORDINAL) *", "return ZERO def dst(self, dt): return ZERO @tzname_in_python2 def tzname(self,", "tzh_timecnt four-byte # values of type long, sorted in ascending", "time zone abbreviation characters that follow the # ttinfo structure(s)", "the file (must not be zero). typecnt, # The number", "\"UTC\"): tz = tzutc() elif name in time.tzname: tz =", "the magic characters \"TZif\" to identify # them as time", "tzoffsetfrom = self._parse_offset(value) elif name == \"TZOFFSETTO\": if parms: raise", "#>>> import tz, datetime #>>> t = tz.tzlocal() #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()", "res = parser._parsetz(s) if res is None: raise ValueError(\"unknown string", "self._ttinfo_list: if not self._trans_list: self._ttinfo_std = self._ttinfo_first = self._ttinfo_list[0] else:", "tt_gmtoff gives the number of # seconds to be added", "= tzstr(name) except ValueError: pass break else: if name in", "dt, laststd=0): timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400 +", "relativedelta.SU(-1) if x.time is not None: kwargs[\"seconds\"] = x.time else:", "= ZERO if dstabbr and start is None: self._start_delta =", "__init__(self, fileobj): global rrule if not rrule: from dateutil import", "isgmt = struct.unpack(\">%db\" % ttisgmtcnt, fileobj.read(ttisgmtcnt)) # ** Everything has", "import gettz tz = gettz(name) if not tz: for c", "\"+s) def _parse_rfc(self, s): lines = s.splitlines() if not lines:", "None if tzwin: try: tz = tzwin(name) except OSError: pass", "self._trans_idx = [] # Each ttinfo structure is written as", "start/end # to avoid building it two times. tzrange.__init__(self, res.stdabbr,", "\"abbr\", \"isstd\", \"isgmt\"] def __init__(self): for attr in self.__slots__: setattr(self,", "working with the extra hour. See the documentation # of", "name in (\"RRULE\", \"RDATE\", \"EXRULE\", \"EXDATE\"): rrulelines.append(line) elif name ==", "return time.tzname[self._isdst(dt)] def _isdst(self, dt): # We can't use mktime", "= start if dstabbr and end is None: self._end_delta =", "None rrule = None try: from dateutil.tzwin import tzwin, tzwinlocal", "= datetime.timedelta(seconds=offset) def utcoffset(self, dt): return self._offset def dst(self, dt):", "characters of \"time zone # abbreviation strings\" stored in the", "it's # always in gmt time. Let me know if", "try: name = os.environ[\"TZ\"] except KeyError: pass if name is", "if not comps: raise ValueError(\"at least one component is needed\")", "\"%s(%s)\" % (self.__class__.__name__, repr(self._filename)) def __reduce__(self): if not os.path.isfile(self._filename): raise", "time zone information files used by tzset(3) # begin with", "filename = filepath for path in TZPATHS: filepath = os.path.join(path,", "self.__slots__: setattr(self, attr, None) def __repr__(self): l = [] for", "\" \": lines[i-1] += line[1:] del lines[i] else: i +=", "= (ttisgmtcnt > i and isgmt[i] != 0) self._ttinfo_list.append(tti) #", "is to start on first sunday of april, and end", "def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom)", "tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto)", "of values are sorted in ascending order # by time.", "self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom self.isdst = isdst self.tzname", "x.week > 0: kwargs[\"day\"] = 1 else: kwargs[\"day\"] = 31", "a four-byte value # for tt_gmtoff of type long, in", "index into the array of # time zone abbreviation characters", "on last sunday of october. if not isend: kwargs[\"month\"] =", "tzutc() elif name in time.tzname: tz = tzlocal() return tz", "four-byte # values of type long, sorted in ascending order.", "return ZERO return self._find_ttinfo(dt).delta def dst(self, dt): if not self._ttinfo_dst:", "other._dst_offset and self._start_delta == other._start_delta and self._end_delta == other._end_delta) def", "to the standard Python datetime module. \"\"\" import datetime import", "+ dt.minute * 60 + dt.second) idx = 0 for", "(the high-order byte # of the value is written first).", "(ImportError, OSError): tzwin, tzwinlocal = None, None def tzname_in_python2(myfunc): \"\"\"Change", "#'BRST' #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' # # Here", "% (self.__class__.__name__, repr(self._s)) if sys.platform != \"win32\": TZFILES = [\"/etc/localtime\",", "other): return not self.__eq__(other) def __repr__(self): return \"%s()\" % self.__class__.__name__", "in the file. timecnt, # The number of \"local time", "parms[1:] if invtz: if name == \"BEGIN\": if value in", "avoid building it two times. tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset,", "self._ttinfo_std = None self._ttinfo_dst = None self._ttinfo_before = None if", "ttinfo list self._ttinfo_list = [] for i in range(typecnt): gmtoff,", "invtz = False elif value == comptype: if not founddtstart:", "POSIX-style # time zone environment variables. if ttisstdcnt: isstd =", "if self._ttinfo_list: if not self._trans_list: self._ttinfo_std = self._ttinfo_first = self._ttinfo_list[0]", "dstabbr and start is None: self._start_delta = relativedelta.relativedelta( hours=+2, month=4,", "= self._trans_idx[idx-1] if not tti.isdst: return tti idx -= 1", "_tzicalvtz(datetime.tzinfo): def __init__(self, tzid, comps=[]): self._tzid = tzid self._comps =", "== 0: raise ValueError(\"no timezones defined\") elif len(keys) > 1:", "in handling POSIX-style # time zone environment variables. if ttisstdcnt:", "other): return (isinstance(other, tzutc) or (isinstance(other, tzoffset) and other._offset ==", "reserved for future use, followed by # six four-byte values", "filepath = os.path.join(path, filename) if os.path.isfile(filepath): break else: continue if", "is not None: kwargs[\"month\"] = x.month if x.weekday is not", "= comp.rrule.before(dt-comp.tzoffsetdiff, inc=True) else: compdt = comp.rrule.before(dt, inc=True) if compdt", "UTC/local indicators stored in the file. ttisgmtcnt, # The number", "followed by tzh_timecnt four-byte # values of type long, sorted", "comp break else: lastcomp = comp[0] self._cachedate.insert(0, dt) self._cachecomp.insert(0, lastcomp)", "is DST or not. # # timestamp = time.mktime((dt.year, dt.month,", "zero). typecnt, # The number of characters of \"time zone", "#'BRDT' #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT'", "return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: raise ValueError(\"invalid offset: \"+s) def _parse_rfc(self, s):", "_ttinfo() tti.offset = gmtoff tti.delta = datetime.timedelta(seconds=gmtoff) tti.isdst = isdst", "of characters of \"time zone # abbreviation strings\" stored in", "self._ttinfo_list[0] # Now fix transition times to become relative to", "not tti.isdst: self._ttinfo_std = tti elif not self._ttinfo_dst and tti.isdst:", "other._trans_idx and self._ttinfo_list == other._ttinfo_list) def __ne__(self, other): return not", "== other.isstd and self.isgmt == other.isgmt) def __ne__(self, other): return", "second gives the total number of # leap seconds to", "return not self.__eq__(other) def __repr__(self): return \"%s()\" % self.__class__.__name__ __reduce__", "the transition times associated # with local time types were", "tti = self._trans_idx[i] if not tti.isdst: # This is std", "self._ttinfo_std else: return self._trans_idx[idx-1] def utcoffset(self, dt): if not self._ttinfo_std:", "raise ValueError(\"unsupported TZNAME parm: \"+parms[0]) tzname = value elif name", "ZERO @tzname_in_python2 def tzname(self, dt): return self._name def __eq__(self, other):", "the standard Python datetime module. \"\"\" import datetime import os", "by time(2)) at which a leap second # occurs; the", "def __eq__(self, other): return (isinstance(other, tzoffset) and self._offset == other._offset)", "string_types): self._s = fileobj fileobj = open(fileobj, 'r') # ical", "times associated # with local time types were specified as", "self._isdst(dt): return self._dst_abbr else: return self._std_abbr def _isdst(self, dt): if", "return dt >= start or dt < end def __eq__(self,", "hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) else: self._end_delta = end def utcoffset(self,", "raise ValueError(\"at least one component is needed\") # Process vtimezone", "be set to the first non-dst ttinfo, or to #", "tti.isdst: self._ttinfo_before = tti break else: self._ttinfo_before = self._ttinfo_list[0] #", "def __setstate__(self, state): for name in self.__slots__: if name in", "timezone -3. if res.stdabbr in (\"GMT\", \"UTC\"): res.stdoffset *= -1", "written in ``standard'' byte order. # Each is used as", "x.month is not None: kwargs[\"month\"] = x.month if x.weekday is", "not self._ttinfo_std: return None return self._find_ttinfo(dt).abbr def __eq__(self, other): if", "path in TZPATHS: filepath = os.path.join(path, name) if not os.path.isfile(filepath):", "None for comp in self._comps: if not comp.isdst: # Handle", "time, and are used when a time zone file #", "+= 1 else: return self._ttinfo_std if idx == 0: return", "not be zero). typecnt, # The number of characters of", "tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto =", "the first onset date. We'll look for the # first", "not tti.isdst: return tti idx -= 1 else: return self._ttinfo_std", "open(fileobj, 'r') # ical should be encoded in UTF-8 with", "ValueError(\"at least one component is needed\") # Process vtimezone self._vtz[tzid]", "if not os.path.isfile(filepath): continue try: tz = tzfile(filepath) break except", "= None if not name: try: name = os.environ[\"TZ\"] except", "res.dstabbr, res.dstoffset, start=False, end=False) if not res.dstabbr: self._start_delta = None", "self._delta(res.start) if self._start_delta: self._end_delta = self._delta(res.end, isend=1) def _delta(self, x,", "not None: kwargs[\"nlyearday\"] = x.jyday if not kwargs: # Default", "time(2)) at which a leap second # occurs; the second", "if not relativedelta: from dateutil import relativedelta self._std_abbr = stdabbr", "not os.path.isfile(filepath): continue try: tz = tzfile(filepath) break except (IOError,", "the # first value of each pair gives the time", "tti.delta-self._find_ttinfo(dt, laststd=1).delta # An alternative for that would be: #", "time, and are used when # a time zone file", "== other._offset) def __ne__(self, other): return not self.__eq__(other) def __repr__(self):", "tti in self._ttinfo_list: if not tti.isdst: self._ttinfo_before = tti break", "in range(len(self._trans_list)): tti = self._trans_idx[i] if not tti.isdst: # This", "header is followed by tzh_timecnt four-byte # values of type", "to implement this. @tzname_in_python2 def tzname(self, dt): if not self._ttinfo_std:", "#>>> t = tz.tzlocal() #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST'", "for some information. gmtoff = (gmtoff+30)//60*60 tti = _ttinfo() tti.offset", "def tzname(self, dt): return self._name def __eq__(self, other): return (isinstance(other,", "i and isstd[i] != 0) tti.isgmt = (ttisgmtcnt > i", "data # is stored in the file (must not be", "``standard'' byte order (the high-order byte # of the value", "types described in the file is associated # with the", "Handle the extra hour in DST -> STD compdt =", "class tzical(object): def __init__(self, fileobj): global rrule if not rrule:", "import datetime import os import struct import sys import time", "= None lastcompdt = None for comp in self._comps: if", "times to become relative to wall time. # # I'm", "return self._offset def dst(self, dt): return ZERO @tzname_in_python2 def tzname(self,", "for tti in self._ttinfo_list: if not tti.isdst: self._ttinfo_before = tti", "class _tzicalvtzcomp(object): def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom", "os.path.isfile(filepath): continue try: tz = tzfile(filepath) break except (IOError, OSError,", "compdt): lastcompdt = compdt lastcomp = comp if not lastcomp:", "tt_isdst tells whether # tm_isdst should be set by localtime(3),", "= filepath for path in TZPATHS: filepath = os.path.join(path, filename)", "range(timecnt-1, -1, -1): tti = self._trans_idx[i] if not self._ttinfo_std and", "for filepath in TZFILES: if not os.path.isabs(filepath): filename = filepath", "stored in the file (must not be zero). typecnt, #", "= line.split(':', 1) parms = name.split(';') if not parms: raise", "self._std_offset+datetime.timedelta(hours=+1) else: self._dst_offset = ZERO if dstabbr and start is", "= fileobj fileobj = open(fileobj, 'r') # ical should be", "[\"offset\", \"delta\", \"isdst\", \"abbr\", \"isstd\", \"isgmt\"] def __init__(self): for attr", "else: continue if os.path.isfile(filepath): try: tz = tzfile(filepath) break except", "isend: kwargs[\"month\"] = 4 kwargs[\"day\"] = 1 kwargs[\"weekday\"] = relativedelta.SU(+1)", "will be # used when a given time is before", "returned by # time(2)) at which the rules for computing", "and dt < end else: return dt >= start or", "else: return myfunc(*args, **kwargs).encode() return inner_func ZERO = datetime.timedelta(0) EPOCHORDINAL", "time is before the first onset date. We'll look for", "def __init__(self, tzid, comps=[]): self._tzid = tzid self._comps = comps", "try: tz = tzfile(filepath) break except (IOError, OSError, ValueError): pass", "same-indexed transition time. These values # serve as indices into", "other): return (isinstance(other, tzoffset) and self._offset == other._offset) def __ne__(self,", "ZERO @tzname_in_python2 def tzname(self, dt): return \"UTC\" def __eq__(self, other):", "be encoded in UTF-8 with CRLF elif hasattr(fileobj, \"name\"): self._s", "# none is found. for comp in self._comps: if not", "tzoffset) and other._offset == ZERO)) def __ne__(self, other): return not", "transitions, # and will be set to the first non-dst", "parms[0].upper() parms = parms[1:] if invtz: if name == \"BEGIN\":", "pass else: tz = tzlocal() else: if name.startswith(\":\"): name =", "struct import sys import time from mo_future import PY3, string_types", "timezones defined\") elif len(keys) > 1: raise ValueError(\"more than one", "return self._dst_offset-self._std_offset else: return ZERO @tzname_in_python2 def tzname(self, dt): return", "False return (self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr and", "different types of # ``local time'' types described in the", "import parser self._s = s res = parser._parsetz(s) if res", "DST -> STD compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True) else: compdt =", "__repr__(self): return \"<tzicalvtz %s>\" % repr(self._tzid) __reduce__ = object.__reduce__ class", "not. # # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, #", "hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) else: self._start_delta = start if dstabbr", "pass else: raise ValueError(\"unknown component: \"+value) comptype = value founddtstart", "changed in Python 3. It used to return bytes, but", "Default is to start on first sunday of april, and", "s res = parser._parsetz(s) if res is None: raise ValueError(\"unknown", "if timecnt: self._trans_idx = struct.unpack(\">%dB\" % timecnt, fileobj.read(timecnt)) else: self._trans_idx", "local time, and are used when a time zone file", "the binary file isstd and # isgmt are off, so", "\"+name) else: if name == \"TZID\": if parms: raise ValueError(\"unsupported", "pass if name is None or name == \":\": for", "this class stores historical changes in the # dst offset,", "False return (self._trans_list == other._trans_list and self._trans_idx == other._trans_idx and", "None self._end_delta = None else: self._start_delta = self._delta(res.start) if self._start_delta:", "The documentation says that utcoffset()-dst() must # be constant for", "# the first dst, if all of them are dst.", "# Handle the extra hour in DST -> STD compdt", "tzutc) or (isinstance(other, tzoffset) and other._offset == ZERO)) def __ne__(self,", "\"local time types\" for which data # is stored in", "__init__(self, s): global parser if not parser: from dateutil import", "= self._ttinfo_list[0] else: for i in range(timecnt-1, -1, -1): tti", "= datetime.timedelta(seconds=stdoffset) else: self._std_offset = ZERO if dstoffset is not", "None: kwargs[\"month\"] = x.month if x.weekday is not None: kwargs[\"weekday\"]", "return self._cachecomp[self._cachedate.index(dt)] except ValueError: pass lastcomp = None lastcompdt =", "dt): if not self._ttinfo_std: return None return self._find_ttinfo(dt).abbr def __eq__(self,", "in range(typecnt): gmtoff, isdst, abbrind = ttinfo[i] # Round to", "1 else: return self._ttinfo_std if idx == 0: return self._ttinfo_before", "None: self._std_offset = datetime.timedelta(seconds=stdoffset) else: self._std_offset = ZERO if dstoffset", "are used when a time zone file # is used", "def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return \"%s(...)\"", "# Then there are tzh_leapcnt pairs of four-byte # values,", "dt): if len(self._comps) == 1: return self._comps[0] dt = dt.replace(tzinfo=None)", "laststdoffset self._trans_list = tuple(self._trans_list) def _find_ttinfo(self, dt, laststd=0): timestamp =", "transition time (as returned by # time(2)) at which the", "(c) 2003-2007 <NAME> <<EMAIL>> This module offers extensions to the", "ignoretz=True, cache=True) comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype == \"DAYLIGHT\"), tzname,", "raise ValueError(\"unknown string format\") # Here we break the compatibility", "file is associated # with the same-indexed transition time. These", "tzoffsetto = None rrulelines = [] tzname = None elif", "of the different types of # ``local time'' types described", "the extra hour in DST -> STD compdt = comp.rrule.before(dt-comp.tzoffsetdiff,", "ValueError(\"invalid component end: \"+value) elif comptype: if name == \"DTSTART\":", "tzrange(datetime.tzinfo): def __init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None): global", "\"COMMENT\": pass else: raise ValueError(\"unsupported property: \"+name) else: if name", "stored as a one-byte value; # they tell whether the", "if not self._ttinfo_dst: return ZERO tti = self._find_ttinfo(dt) if not", "if value == \"VTIMEZONE\": if comptype: raise ValueError(\"component not closed:", "start or dt < end def __eq__(self, other): if not", "% (self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp(object): def __init__(self, tzoffsetfrom, tzoffsetto, isdst,", "open(fileobj, 'rb') elif hasattr(fileobj, \"name\"): self._filename = fileobj.name else: self._filename", "object.__reduce__ class tzstr(tzrange): def __init__(self, s): global parser if not", "specified as UTC or # local time, and are used", "break else: self._ttinfo_before = self._ttinfo_list[0] # Now fix transition times", "for name in self.__slots__: state[name] = getattr(self, name, None) return", "'rb') elif hasattr(fileobj, \"name\"): self._filename = fileobj.name else: self._filename =", "or lastcompdt < compdt): lastcompdt = compdt lastcomp = comp", "kwargs[\"day\"] = 1 kwargs[\"weekday\"] = relativedelta.SU(+1) else: kwargs[\"month\"] = 10", "else: if name == \"TZID\": if parms: raise ValueError(\"unsupported TZID", "[\"/etc/localtime\", \"localtime\"] TZPATHS = [\"/usr/share/zoneinfo\", \"/usr/lib/zoneinfo\", \"/etc/zoneinfo\"] else: TZFILES =", "laststd: while idx > 0: tti = self._trans_idx[idx-1] if not", "or dt < end def __eq__(self, other): if not isinstance(other,", "ValueError(\"unsupported property: \"+name) elif name == \"BEGIN\" and value ==", "comments # about this. laststdoffset = 0 self._trans_list = list(self._trans_list)", "class tzrange(datetime.tzinfo): def __init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None):", "[] self._cachecomp = [] def _find_comp(self, dt): if len(self._comps) ==", "tzwin, tzwinlocal = None, None def tzname_in_python2(myfunc): \"\"\"Change unicode output", "1 kwargs[\"weekday\"] = relativedelta.SU(+1) else: kwargs[\"month\"] = 10 kwargs[\"day\"] =", "dstabbr=None, dstoffset=None, start=None, end=None): global relativedelta if not relativedelta: from", "and stdoffset is not None: self._dst_offset = self._std_offset+datetime.timedelta(hours=+1) else: self._dst_offset", "elif name == \"COMMENT\": pass else: raise ValueError(\"unsupported property: \"+name)", "line in lines: if not line: continue name, value =", "are sorted in ascending order # by time. # Not", "dt): return \"UTC\" def __eq__(self, other): return (isinstance(other, tzutc) or", "class tzlocal(datetime.tzinfo): _std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: _dst_offset = datetime.timedelta(seconds=-time.altzone)", "__setstate__(self, state): for name in self.__slots__: if name in state:", "if not os.path.isfile(filepath): filepath = filepath.replace(' ', '_') if not", "import relativedelta self._std_abbr = stdabbr self._dst_abbr = dstabbr if stdoffset", "if x.month is not None: kwargs[\"month\"] = x.month if x.weekday", "except (ImportError, OSError): tzwin, tzwinlocal = None, None def tzname_in_python2(myfunc):", "applied after the given time. # The pairs of values", "parms: raise ValueError(\"unsupported TZNAME parm: \"+parms[0]) tzname = value elif", "timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400 + dt.hour *", "self.isgmt == other.isgmt) def __ne__(self, other): return not self.__eq__(other) def", "in self._comps: if not comp.isdst: # Handle the extra hour", "kwargs[\"weekday\"] = relativedelta.weekday(x.weekday, x.week) if x.week > 0: kwargs[\"day\"] =", "_find_ttinfo(self, dt, laststd=0): timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400", "relativedelta = None parser = None rrule = None try:", "# is stored in the file. timecnt, # The number", "not lastcomp: # RFC says nothing about what to do", "s = s[1:] else: signal = +1 if len(s) ==", "% self.__class__.__name__ __reduce__ = object.__reduce__ class tzoffset(datetime.tzinfo): def __init__(self, name,", "strings \"\"\" def inner_func(*args, **kwargs): if PY3: return myfunc(*args, **kwargs)", "name.split(';') if not parms: raise ValueError(\"empty property name\") name =", "raise ValueError(\"unknown component: \"+value) comptype = value founddtstart = False", "__reduce__ = object.__reduce__ class tzlocal(datetime.tzinfo): _std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight:", "inc=True) if compdt and (not lastcompdt or lastcompdt < compdt):", "raise ValueError(\"mandatory TZID not found\") if not comps: raise ValueError(\"at", "= self._delta(res.end, isend=1) def _delta(self, x, isend=0): kwargs = {}", "return self._std_offset def dst(self, dt): if self._isdst(dt): return self._dst_offset-self._std_offset else:", "dst offset, so I belive that this wouldn't be the", "import tz, datetime #>>> t = tz.tzlocal() #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT'", "elif dstabbr and stdoffset is not None: self._dst_offset = self._std_offset+datetime.timedelta(hours=+1)", "not self._ttinfo_dst and tti.isdst: self._ttinfo_dst = tti if self._ttinfo_std and", "ascending order # by time. # Not used, for now", "class tzutc(datetime.tzinfo): def utcoffset(self, dt): return ZERO def dst(self, dt):", "name in time.tzname: tz = tzlocal() return tz # vim:ts=4:sw=4:et", "# Now fix transition times to become relative to wall", "magic characters \"TZif\" to identify # them as time zone", "rr = None if rrulelines: rr = rrule.rrulestr(\"\\n\".join(rrulelines), compatible=True, ignoretz=True,", "self._trans_list: if timestamp < trans: break idx += 1 else:", "= lines[i].rstrip() if not line: del lines[i] elif i >", "ValueError(\"mandatory TZID not found\") if not comps: raise ValueError(\"at least", "== other._ttinfo_list) def __ne__(self, other): return not self.__eq__(other) def __repr__(self):", "= self.tzoffsetto-self.tzoffsetfrom self.isdst = isdst self.tzname = tzname self.rrule =", "\"localtime\"] TZPATHS = [\"/usr/share/zoneinfo\", \"/usr/lib/zoneinfo\", \"/etc/zoneinfo\"] else: TZFILES = []", "name == \"BEGIN\" and value == \"VTIMEZONE\": tzid = None", "= self._parse_offset(value) elif name == \"TZNAME\": if parms: raise ValueError(\"unsupported", "of april, and end # on last sunday of october.", "not isinstance(other, tzrange): return False return (self._std_abbr == other._std_abbr and", "__init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto", "return self._comps[0] dt = dt.replace(tzinfo=None) try: return self._cachecomp[self._cachedate.index(dt)] except ValueError:", "# From tzfile(5): # # The time zone information files", "return self._ttinfo_dst.offset-self._ttinfo_std.offset # # However, this class stores historical changes", "``local time'' types described in the file is associated #", "is followed by tzh_timecnt four-byte # values of type long,", "return self._vtz.get(tzid) def _parse_offset(self, s): s = s.strip() if not", "and self._dst_abbr == other._dst_abbr and self._std_offset == other._std_offset and self._dst_offset", "in (\"GMT\", \"UTC\"): tz = tzutc() elif name in time.tzname:", "self.__slots__: state[name] = getattr(self, name, None) return state def __setstate__(self,", "BSD\" __all__ = [\"tzutc\", \"tzoffset\", \"tzlocal\", \"tzfile\", \"tzrange\", \"tzstr\", \"tzical\",", "-= delta.seconds+delta.days*86400 return relativedelta.relativedelta(**kwargs) def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__,", "hour in DST -> STD compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True) else:", "component: \"+value) comptype = value founddtstart = False tzoffsetfrom =", "second # occurs; the second gives the total number of", "specified as standard # time or wall clock time, and", "def __reduce__(self): if not os.path.isfile(self._filename): raise ValueError(\"Unpickable %s class\" %", "dst(self, dt): comp = self._find_comp(dt) if comp.isdst: return comp.tzoffsetdiff else:", "# # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, # dt.minute,", "it two times. tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset, start=False, end=False)", "if not self._ttinfo_std: return None return self._find_ttinfo(dt).abbr def __eq__(self, other):", "isinstance(fileobj, string_types): self._s = fileobj fileobj = open(fileobj, 'r') #", "wall clock time, and are used when # a time", "None: self._dst_offset = self._std_offset+datetime.timedelta(hours=+1) else: self._dst_offset = ZERO if dstabbr", "nothing about what to do when a given # time", "i < len(lines): line = lines[i].rstrip() if not line: del", "if not self._ttinfo_std: return ZERO return self._find_ttinfo(dt).delta def dst(self, dt):", "format\") # Here we break the compatibility with the TZ", "= [] for i in range(typecnt): ttinfo.append(struct.unpack(\">lbb\", fileobj.read(6))) abbr =", "sub-minute timezones. Check # http://python.org/sf/1447945 for some information. gmtoff =", "if x.time is not None: kwargs[\"seconds\"] = x.time else: #", "first). if fileobj.read(4).decode() != \"TZif\": raise ValueError(\"magic not found\") fileobj.read(16)", "== \" \": lines[i-1] += line[1:] del lines[i] else: i", "tzoffset(datetime.tzinfo): def __init__(self, name, offset): self._name = name self._offset =", "the file is associated # with the same-indexed transition time.", "self._trans_idx: trans_idx.append(self._ttinfo_list[idx]) self._trans_idx = tuple(trans_idx) # Set standard, dst, and", "return self._dst_offset else: return self._std_offset def dst(self, dt): if self._isdst(dt):", "not self._ttinfo_std: return ZERO return self._find_ttinfo(dt).delta def dst(self, dt): if", "should be encoded in UTF-8 with CRLF elif hasattr(fileobj, \"name\"):", "= _ttinfo() tti.offset = gmtoff tti.delta = datetime.timedelta(seconds=gmtoff) tti.isdst =", "An alternative for that would be: # # return self._ttinfo_dst.offset-self._ttinfo_std.offset", "is before the first onset date. We'll look for the", "ttinfo[i] # Round to full-minutes if that's not the case.", "self._ttinfo_dst for tti in self._ttinfo_list: if not tti.isdst: self._ttinfo_before =", "and end # on last sunday of october. if not", "if laststd: while idx > 0: tti = self._trans_idx[idx-1] if", "dt.hour * 3600 + dt.minute * 60 + dt.second) return", "return \"%s()\" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzoffset(datetime.tzinfo): def", "from dateutil import parser self._s = s res = parser._parsetz(s)", "of type unsigned # char; each one tells which of", "= ((dt.toordinal() - EPOCHORDINAL) * 86400 + dt.hour * 3600", "if name is None or name == \":\": for filepath", "structures that # appears next in the file. if timecnt:", "output into bytestrings in Python 2 tzname() API changed in", "and self.delta == other.delta and self.isdst == other.isdst and self.abbr", "and self._offset == other._offset) def __ne__(self, other): return not self.__eq__(other)", "Copyright (c) 2003-2007 <NAME> <<EMAIL>> This module offers extensions to", "elif len(keys) > 1: raise ValueError(\"more than one timezone available\")", "res.dstabbr: self._start_delta = None self._end_delta = None else: self._start_delta =", "by time. # Not used, for now if leapcnt: leap", "self._trans_idx == other._trans_idx and self._ttinfo_list == other._ttinfo_list) def __ne__(self, other):", "compdt = comp.rrule.before(dt, inc=True) if compdt and (not lastcompdt or", "None return self._find_ttinfo(dt).abbr def __eq__(self, other): if not isinstance(other, tzfile):", "tzoffsetfrom is None: raise ValueError(\"mandatory TZOFFSETFROM not found\") if tzoffsetto", "\"/etc/zoneinfo\"] else: TZFILES = [] TZPATHS = [] def gettz(name=None):", "TZID parm: \"+parms[0]) tzid = value elif name in (\"TZURL\",", "if not s: raise ValueError(\"empty offset\") if s[0] in ('+',", "tz: from dateutil.zoneinfo import gettz tz = gettz(name) if not", "is used in handling POSIX-style # time zone environment variables.", "not found\") if tzoffsetto is None: raise ValueError(\"mandatory TZOFFSETFROM not", "if os.path.isfile(filepath): break else: continue if os.path.isfile(filepath): try: tz =", "http://python.org/sf/1447945 for some information. gmtoff = (gmtoff+30)//60*60 tti = _ttinfo()", "== other._std_abbr and self._dst_abbr == other._dst_abbr and self._std_offset == other._std_offset", "self._trans_idx = struct.unpack(\">%dB\" % timecnt, fileobj.read(timecnt)) else: self._trans_idx = []", "return self._find_comp(dt).tzoffsetto def dst(self, dt): comp = self._find_comp(dt) if comp.isdst:", "ZERO tti = self._find_ttinfo(dt) if not tti.isdst: return ZERO #", "# them as time zone information files, followed by #", "and self._std_offset == other._std_offset and self._dst_offset == other._dst_offset and self._start_delta", "ZERO = datetime.timedelta(0) EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal() class tzutc(datetime.tzinfo): def utcoffset(self,", "# The number of \"local time types\" for which data", "raise ValueError(\"no timezones defined\") elif len(keys) > 1: raise ValueError(\"more", "property: \"+name) elif name == \"BEGIN\" and value == \"VTIMEZONE\":", "variables. if ttisgmtcnt: isgmt = struct.unpack(\">%db\" % ttisgmtcnt, fileobj.read(ttisgmtcnt)) #", "ttinfo = [] for i in range(typecnt): ttinfo.append(struct.unpack(\">lbb\", fileobj.read(6))) abbr", "for c in name: # name must have at least", "by # time(2)) at which the rules for computing local", "# and a one-byte value for tt_abbrind. In each #", "len(lines): line = lines[i].rstrip() if not line: del lines[i] elif", "= [] # Each ttinfo structure is written as a", "time zone envi- # ronment variables. if ttisgmtcnt: isgmt =", "parser: from dateutil import parser self._s = s res =", "stable implementation: # timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400", "# http://www.twinsun.com/tz/tz-link.htm # ftp://ftp.iana.org/tz/tz*.tar.gz def __init__(self, fileobj): if isinstance(fileobj, string_types):", "timecnt, # The number of \"local time types\" for which", "time(2)) at which the rules for computing local time #", "return \"%s(%s)\" % (self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp(object): def __init__(self, tzoffsetfrom,", "else: i += 1 tzid = None comps = []", "return self._dst_abbr else: return self._std_abbr def _isdst(self, dt): if not", "laststd=0): timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400 + dt.hour", "# first standard component, or the first component, if #", "self._name def __eq__(self, other): return (isinstance(other, tzoffset) and self._offset ==", "before the first onset date. We'll look for the #", "None for line in lines: if not line: continue name,", "dt.second) idx = 0 for trans in self._trans_list: if timestamp", "+1 if len(s) == 4: return (int(s[:2])*3600+int(s[2:])*60)*signal elif len(s) ==", "= fileobj.name else: self._filename = repr(fileobj) # From tzfile(5): #", "in (\"TZURL\", \"LAST-MODIFIED\", \"COMMENT\"): pass else: raise ValueError(\"unsupported property: \"+name)", "in Python 3. It used to return bytes, but was", "return ZERO @tzname_in_python2 def tzname(self, dt): return \"UTC\" def __eq__(self,", "standard/wall indicators stored in the file. ttisstdcnt, # The number", "OSError: pass if not tz: from dateutil.zoneinfo import gettz tz", "\"UTC\" def __eq__(self, other): return (isinstance(other, tzutc) or (isinstance(other, tzoffset)", "def get(self, tzid=None): if tzid is None: keys = list(self._vtz.keys())", "= s res = parser._parsetz(s) if res is None: raise", "{} self._parse_rfc(fileobj.read()) def keys(self): return list(self._vtz.keys()) def get(self, tzid=None): if", "Not used, for now if leapcnt: leap = struct.unpack(\">%dl\" %", "set by localtime(3), and # tt_abbrind serves as an index", "leap second # occurs; the second gives the total number", "== 6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: raise ValueError(\"invalid offset: \"+s) def", "before will be # used when a given time is", "if parms: raise ValueError(\"unsupported %s parm: %s \"%(name, parms[0])) tzoffsetfrom", "indices into an array of ttinfo structures that # appears", "[] for i in range(typecnt): ttinfo.append(struct.unpack(\">lbb\", fileobj.read(6))) abbr = fileobj.read(charcnt).decode()", "None) return state def __setstate__(self, state): for name in self.__slots__:", "so I belive that this wouldn't be the right #", "else: self._std_offset = ZERO if dstoffset is not None: self._dst_offset", "This is dst time. Convert to std. self._trans_list[i] += laststdoffset", "= tti.offset else: # This is dst time. Convert to", "= ZERO if dstoffset is not None: self._dst_offset = datetime.timedelta(seconds=dstoffset)", "# stored in the file. leapcnt, # The number of", "first sunday of april, and end # on last sunday", "name\") name = parms[0].upper() parms = parms[1:] if invtz: if", "return \"%s(%s)\" % (self.__class__.__name__, \", \".join(l)) def __eq__(self, other): if", "the first component, if # none is found. for comp", "% (self.__class__.__name__, repr(self._filename)) def __reduce__(self): if not os.path.isfile(self._filename): raise ValueError(\"Unpickable", "time.mktime((dt.year, dt.month, dt.day, dt.hour, # dt.minute, dt.second, dt.weekday(), 0, -1))", "# The pairs of values are sorted in ascending order", "way # of working with the extra hour. See the", "tt_gmtoff of type long, in a standard byte # order,", "The number of leap seconds for which data is #", "has been read ** # Build ttinfo list self._ttinfo_list =", "is before any transitions, # and will be set to", "return \"UTC\" def __eq__(self, other): return (isinstance(other, tzutc) or (isinstance(other,", "are written in ``standard'' byte order. # Each is used", "month=10, day=31, weekday=relativedelta.SU(-1)) else: self._end_delta = end def utcoffset(self, dt):", "number of characters of \"time zone # abbreviation strings\" stored", "\"TZID\": if parms: raise ValueError(\"unsupported TZID parm: \"+parms[0]) tzid =", "tz = tzlocal() else: if name.startswith(\":\"): name = name[:-1] if", "\"DAYLIGHT\"), tzname, rr) comps.append(comp) comptype = None else: raise ValueError(\"invalid", "unicode output into bytestrings in Python 2 tzname() API changed", "rrule class _tzicalvtz(datetime.tzinfo): def __init__(self, tzid, comps=[]): self._tzid = tzid", "lastcompdt < compdt): lastcompdt = compdt lastcomp = comp if", "None: l.append(\"%s=%s\" % (attr, repr(value))) return \"%s(%s)\" % (self.__class__.__name__, \",", "= dt.replace(tzinfo=None) try: return self._cachecomp[self._cachedate.index(dt)] except ValueError: pass lastcomp =", "[] invtz = False comptype = None for line in", "tzfile(filepath) break except (IOError, OSError, ValueError): pass else: tz =", "range(len(self._trans_list)): tti = self._trans_idx[i] if not tti.isdst: # This is", "end is None: self._end_delta = relativedelta.relativedelta( hours=+1, month=10, day=31, weekday=relativedelta.SU(-1))", "os import struct import sys import time from mo_future import", "!= \"TZif\": raise ValueError(\"magic not found\") fileobj.read(16) ( # The", "None: kwargs[\"yearday\"] = x.yday elif x.jyday is not None: kwargs[\"nlyearday\"]", "+= 1 tzid = None comps = [] invtz =", "len(self._comps) == 1: return self._comps[0] dt = dt.replace(tzinfo=None) try: return", "is None: self._end_delta = relativedelta.relativedelta( hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) else:", "self._dst_offset = datetime.timedelta(seconds=dstoffset) elif dstabbr and stdoffset is not None:", "= open(fileobj, 'r') # ical should be encoded in UTF-8", "path in TZPATHS: filepath = os.path.join(path, filename) if os.path.isfile(filepath): break", "STD compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True) else: compdt = comp.rrule.before(dt, inc=True)", "OSError, ValueError): pass else: tz = None if tzwin: try:", "dt.weekday(), 0, -1)) # return time.localtime(timestamp).tm_isdst # # The code", "else: for path in TZPATHS: filepath = os.path.join(path, name) if", "repr(self._s)) class _tzicalvtzcomp(object): def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None):", "UTC or # local time, and are used when a", "found\") # Process component rr = None if rrulelines: rr", "None: kwargs[\"seconds\"] = x.time else: # Default is 2AM. kwargs[\"seconds\"]", "bytes, but was changed to unicode strings \"\"\" def inner_func(*args,", "other._offset) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return", "tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0) self._ttinfo_list.append(tti)", "name = name[:-1] if os.path.isabs(name): if os.path.isfile(name): tz = tzfile(name)", "typecnt, # The number of characters of \"time zone #", "value = line.split(':', 1) parms = name.split(';') if not parms:", "historical changes in the # dst offset, so I belive", "TZPATHS: filepath = os.path.join(path, name) if not os.path.isfile(filepath): filepath =", "as an index into the array of # time zone", "property name\") name = parms[0].upper() parms = parms[1:] if invtz:", "datetime module. \"\"\" import datetime import os import struct import", "# timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, # dt.minute, dt.second,", "stored in the file. ttisstdcnt, # The number of leap", "= self._parse_offset(value) elif name == \"TZOFFSETTO\": if parms: raise ValueError(\"unsupported", "\"isgmt\"] def __init__(self): for attr in self.__slots__: setattr(self, attr, None)", "if ttisgmtcnt: isgmt = struct.unpack(\">%db\" % ttisgmtcnt, fileobj.read(ttisgmtcnt)) # **", "would be: # # return self._ttinfo_dst.offset-self._ttinfo_std.offset # # However, this", "of the tzinfo class. delta = self._dst_offset-self._std_offset kwargs[\"seconds\"] -= delta.seconds+delta.days*86400", "__reduce__ = object.__reduce__ class tzoffset(datetime.tzinfo): def __init__(self, name, offset): self._name", "kwargs[\"weekday\"] = relativedelta.SU(-1) if x.time is not None: kwargs[\"seconds\"] =", "x.time is not None: kwargs[\"seconds\"] = x.time else: # Default", "is not None: kwargs[\"yearday\"] = x.yday elif x.jyday is not", "\"%s()\" % self.__class__.__name__ __reduce__ = object.__reduce__ class _ttinfo(object): __slots__ =", "look for the # first standard component, or the first", "not line: del lines[i] elif i > 0 and line[0]", "\"+name) elif name == \"BEGIN\" and value == \"VTIMEZONE\": tzid", "tti.isdst: return tti idx -= 1 else: return self._ttinfo_std else:", "**kwargs): if PY3: return myfunc(*args, **kwargs) else: return myfunc(*args, **kwargs).encode()", "if not line: del lines[i] elif i > 0 and", "# be constant for every dt. return tti.delta-self._find_ttinfo(dt, laststd=1).delta #", "is not None: kwargs[\"weekday\"] = relativedelta.weekday(x.weekday, x.week) if x.week >", "dstabbr and end is None: self._end_delta = relativedelta.relativedelta( hours=+1, month=10,", "file (must not be zero). typecnt, # The number of", "be constant for every dt. return tti.delta-self._find_ttinfo(dt, laststd=1).delta # An", "#'BRDT' # # Here is a more stable implementation: #", "sunday of october. if not isend: kwargs[\"month\"] = 4 kwargs[\"day\"]", "standard component, or the first component, if # none is", "elif value == comptype: if not founddtstart: raise ValueError(\"mandatory DTSTART", "self._cachedate.insert(0, dt) self._cachecomp.insert(0, lastcomp) if len(self._cachedate) > 10: self._cachedate.pop() self._cachecomp.pop()", "else: return self._ttinfo_std if idx == 0: return self._ttinfo_before if", "self._trans_list = struct.unpack(\">%dl\" % timecnt, fileobj.read(timecnt*4)) else: self._trans_list = []", "def __init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None): global relativedelta", "((dt.toordinal() - EPOCHORDINAL) * 86400 + dt.hour * 3600 +", "and in the binary file isstd and # isgmt are", "self._comps: if not comp.isdst: lastcomp = comp break else: lastcomp", "isstd and # isgmt are off, so it should be", "3600 + dt.minute * 60 + dt.second) idx = 0", "\": lines[i-1] += line[1:] del lines[i] else: i += 1", "else: raise ValueError(\"unsupported property: \"+name) else: if name == \"TZID\":", "dst time. Convert to std. self._trans_list[i] += laststdoffset self._trans_list =", "comps = [] invtz = True def __repr__(self): return \"%s(%s)\"", "stdoffset is not None: self._dst_offset = self._std_offset+datetime.timedelta(hours=+1) else: self._dst_offset =", "* 60 + dt.second) return time.localtime(timestamp+time.timezone).tm_isdst def __eq__(self, other): if", "raise ValueError(\"empty string\") # Unfold i = 0 while i", "return list(self._vtz.keys()) def get(self, tzid=None): if tzid is None: keys", "in the file is associated # with the same-indexed transition", "each # structure, tt_gmtoff gives the number of # seconds", "and isgmt[i] != 0) self._ttinfo_list.append(tti) # Replace ttinfo indexes for", "if not parms: raise ValueError(\"empty property name\") name = parms[0].upper()", "# This is dst time. Convert to std. self._trans_list[i] +=", "compdt and (not lastcompdt or lastcompdt < compdt): lastcompdt =", "to std. self._trans_list[i] += laststdoffset self._trans_list = tuple(self._trans_list) def _find_ttinfo(self,", "% (attr, repr(value))) return \"%s(%s)\" % (self.__class__.__name__, \", \".join(l)) def", "= relativedelta.SU(-1) if x.time is not None: kwargs[\"seconds\"] = x.time", "else: raise ValueError(\"invalid offset: \"+s) def _parse_rfc(self, s): lines =", "# However, this class stores historical changes in the #", "and self._ttinfo_dst: break else: if self._ttinfo_dst and not self._ttinfo_std: self._ttinfo_std", "dstabbr and stdoffset is not None: self._dst_offset = self._std_offset+datetime.timedelta(hours=+1) else:", "import rrule if isinstance(fileobj, string_types): self._s = fileobj fileobj =", "dst, and before ttinfos. before will be # used when", "The above header is followed by tzh_timecnt four-byte # values", "and self._ttinfo_list == other._ttinfo_list) def __ne__(self, other): return not self.__eq__(other)", "\"\"\" Copyright (c) 2003-2007 <NAME> <<EMAIL>> This module offers extensions", "def _find_comp(self, dt): if len(self._comps) == 1: return self._comps[0] dt", "= [\"/etc/localtime\", \"localtime\"] TZPATHS = [\"/usr/share/zoneinfo\", \"/usr/lib/zoneinfo\", \"/etc/zoneinfo\"] else: TZFILES", "and _dst_offset set. Use False in start/end # to avoid", "ttinfo indexes for ttinfo objects. trans_idx = [] for idx", "comptype: if name == \"DTSTART\": rrulelines.append(line) founddtstart = True elif", "is None: raise ValueError(\"unknown string format\") # Here we break", "not the case. Python's # datetime doesn't accept sub-minute timezones.", "fileobj.read(ttisgmtcnt)) # ** Everything has been read ** # Build", "not os.path.isabs(filepath): filename = filepath for path in TZPATHS: filepath", "time or wall clock time, and are used when #", "3. It used to return bytes, but was changed to", "one-byte values of type unsigned # char; each one tells", "== other.isdst and self.abbr == other.abbr and self.isstd == other.isstd", "time from mo_future import PY3, string_types __license__ = \"Simplified BSD\"", "= relativedelta.relativedelta( hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) else: self._start_delta = start", "setattr(self, attr, None) def __repr__(self): l = [] for attr", "tti idx -= 1 else: return self._ttinfo_std else: return self._trans_idx[idx-1]", "or name == \":\": for filepath in TZFILES: if not", "utcoffset()-dst() must # be constant for every dt. return tti.delta-self._find_ttinfo(dt,", "return ZERO @tzname_in_python2 def tzname(self, dt): return self._name def __eq__(self,", "(int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: raise ValueError(\"invalid offset: \"+s) def _parse_rfc(self, s): lines", "datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' # # Here is a", "# Default is to start on first sunday of april,", "class tzfile(datetime.tzinfo): # http://www.twinsun.com/tz/tz-link.htm # ftp://ftp.iana.org/tz/tz*.tar.gz def __init__(self, fileobj): if", "self._trans_list = [] # Next come tzh_timecnt one-byte values of", "ValueError(\"mandatory TZOFFSETFROM not found\") # Process component rr = None", "self._ttinfo_dst: break else: if self._ttinfo_dst and not self._ttinfo_std: self._ttinfo_std =", "= True elif name in (\"RRULE\", \"RDATE\", \"EXRULE\", \"EXDATE\"): rrulelines.append(line)", "None else: for path in TZPATHS: filepath = os.path.join(path, name)", "ValueError(\"unsupported TZID parm: \"+parms[0]) tzid = value elif name in", "value elif name == \"COMMENT\": pass else: raise ValueError(\"unsupported property:", "which the rules for computing local time # change. if", "ZERO return self._find_ttinfo(dt).delta def dst(self, dt): if not self._ttinfo_dst: return", "= filepath.replace(' ', '_') if not os.path.isfile(filepath): continue try: tz", "for i in range(typecnt): ttinfo.append(struct.unpack(\">lbb\", fileobj.read(6))) abbr = fileobj.read(charcnt).decode() #", "if dstabbr and start is None: self._start_delta = relativedelta.relativedelta( hours=+2,", "= keys[0] return self._vtz.get(tzid) def _parse_offset(self, s): s = s.strip()", "to # the first dst, if all of them are", "kwargs[\"day\"] = 1 else: kwargs[\"day\"] = 31 elif x.day: kwargs[\"day\"]", "[] invtz = True def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__,", "== 4: return (int(s[:2])*3600+int(s[2:])*60)*signal elif len(s) == 6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal", "Use False in start/end # to avoid building it two", "x, isend=0): kwargs = {} if x.month is not None:", "component, if # none is found. for comp in self._comps:", "i = 0 while i < len(lines): line = lines[i].rstrip()", "else: TZFILES = [] TZPATHS = [] def gettz(name=None): tz", "leap seconds to be applied after the given time. #", "and self.abbr == other.abbr and self.isstd == other.isstd and self.isgmt", "rrule if isinstance(fileobj, string_types): self._s = fileobj fileobj = open(fileobj,", "with local time types were specified as UTC or #", "self.isdst == other.isdst and self.abbr == other.abbr and self.isstd ==", "# Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz = False", "= stdabbr self._dst_abbr = dstabbr if stdoffset is not None:", "# The above header is followed by tzh_timecnt four-byte #", "a tzstr if c in \"0123456789\": try: tz = tzstr(name)", "changed to unicode strings \"\"\" def inner_func(*args, **kwargs): if PY3:", "abbrind)] tti.isstd = (ttisstdcnt > i and isstd[i] != 0)", "# by time. # Not used, for now if leapcnt:", "name.startswith(\":\"): name = name[:-1] if os.path.isabs(name): if os.path.isfile(name): tz =", "is None or name == \":\": for filepath in TZFILES:", "_tzicalvtzcomp(object): def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom =", "files, followed by # sixteen bytes reserved for future use,", "end def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset else: return", "the file. ttisgmtcnt, # The number of standard/wall indicators stored", "for i in range(timecnt-1, -1, -1): tti = self._trans_idx[i] if", "dt.minute * 60 + dt.second) return time.localtime(timestamp+time.timezone).tm_isdst def __eq__(self, other):", "and self._dst_offset == other._dst_offset and self._start_delta == other._start_delta and self._end_delta", "zone envi- # ronment variables. if ttisgmtcnt: isgmt = struct.unpack(\">%db\"", "tz = None if not name: try: name = os.environ[\"TZ\"]", "compdt lastcomp = comp if not lastcomp: # RFC says", "= relativedelta.relativedelta( hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) else: self._end_delta = end", "= True def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._s)) if", "3600 + dt.minute * 60 + dt.second) return time.localtime(timestamp+time.timezone).tm_isdst def", "= datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom self.isdst = isdst self.tzname =", "(must not be zero). typecnt, # The number of characters", "this wouldn't be the right # way to implement this.", "rrule if not rrule: from dateutil import rrule if isinstance(fileobj,", "continue name, value = line.split(':', 1) parms = name.split(';') if", "\"BEGIN\" and value == \"VTIMEZONE\": tzid = None comps =", "def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return \"%s()\"", "# is setup to wall time, and in the binary", "struct.unpack(\">%dl\" % (leapcnt*2), fileobj.read(leapcnt*8)) # Then there are tzh_ttisstdcnt standard/wall", "trans_idx.append(self._ttinfo_list[idx]) self._trans_idx = tuple(trans_idx) # Set standard, dst, and before", "elif hasattr(fileobj, \"name\"): self._s = fileobj.name else: self._s = repr(fileobj)", "# on last sunday of october. if not isend: kwargs[\"month\"]", "and are used when # a time zone file is", "res.stdabbr in (\"GMT\", \"UTC\"): res.stdoffset *= -1 # We must", "follow the documented way # of working with the extra", "return (isinstance(other, tzoffset) and self._offset == other._offset) def __ne__(self, other):", "+= tti.offset laststdoffset = tti.offset else: # This is dst", "self.__eq__(other) def __repr__(self): return \"%s(%s, %s)\" % (self.__class__.__name__, repr(self._name), self._offset.days*86400+self._offset.seconds)", "tti.isdst: return ZERO # The documentation says that utcoffset()-dst() must", "0: return self._ttinfo_before if laststd: while idx > 0: tti", "self._parse_offset(value) elif name == \"TZNAME\": if parms: raise ValueError(\"unsupported TZNAME", "and before ttinfos. before will be # used when a", "pass else: raise ValueError(\"unsupported property: \"+name) elif name == \"BEGIN\"", "= struct.unpack(\">6l\", fileobj.read(24)) # The above header is followed by", "if not isinstance(other, tzfile): return False return (self._trans_list == other._trans_list", "attr, None) def __repr__(self): l = [] for attr in", "times\" for which data # is stored in the file.", "(self.__class__.__name__, \", \".join(l)) def __eq__(self, other): if not isinstance(other, _ttinfo):", "datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom self.isdst = isdst", "written as a four-byte value # for tt_gmtoff of type", "def gettz(name=None): tz = None if not name: try: name", "0 self._trans_list = list(self._trans_list) for i in range(len(self._trans_list)): tti =", "return \"%s()\" % self.__class__.__name__ __reduce__ = object.__reduce__ class _ttinfo(object): __slots__", "break else: if name in (\"GMT\", \"UTC\"): tz = tzutc()", "array of ttinfo structures that # appears next in the", "self._ttinfo_list.append(tti) # Replace ttinfo indexes for ttinfo objects. trans_idx =", "hasattr(fileobj, \"name\"): self._s = fileobj.name else: self._s = repr(fileobj) self._vtz", "extra hour. See the documentation # of the tzinfo class.", "four-byte value # for tt_gmtoff of type long, in a", "tzinfo class. delta = self._dst_offset-self._std_offset kwargs[\"seconds\"] -= delta.seconds+delta.days*86400 return relativedelta.relativedelta(**kwargs)", "pass else: raise ValueError(\"unsupported property: \"+name) else: if name ==", "tzoffsetfrom = None tzoffsetto = None rrulelines = [] tzname", "other): if not isinstance(other, _ttinfo): return False return (self.offset ==", "year+self._end_delta dt = dt.replace(tzinfo=None) if start < end: return dt", "if len(self._cachedate) > 10: self._cachedate.pop() self._cachecomp.pop() return lastcomp def utcoffset(self,", "@tzname_in_python2 def tzname(self, dt): return self._find_comp(dt).tzname def __repr__(self): return \"<tzicalvtz", "\"\"\" def inner_func(*args, **kwargs): if PY3: return myfunc(*args, **kwargs) else:", "x.week) if x.week > 0: kwargs[\"day\"] = 1 else: kwargs[\"day\"]", "name == \"COMMENT\": pass else: raise ValueError(\"unsupported property: \"+name) else:", "tz = gettz(name) if not tz: for c in name:", "\"%s(...)\" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzstr(tzrange): def __init__(self,", "__repr__(self): return \"%s()\" % self.__class__.__name__ __reduce__ = object.__reduce__ class _ttinfo(object):", "ValueError(\"unknown component: \"+value) comptype = value founddtstart = False tzoffsetfrom", "== \"TZID\": if parms: raise ValueError(\"unsupported TZID parm: \"+parms[0]) tzid", "continue if os.path.isfile(filepath): try: tz = tzfile(filepath) break except (IOError,", "return comp.tzoffsetdiff else: return ZERO @tzname_in_python2 def tzname(self, dt): return", "1) parms = name.split(';') if not parms: raise ValueError(\"empty property", "API changed in Python 3. It used to return bytes,", "Set standard, dst, and before ttinfos. before will be #", "# datetime doesn't accept sub-minute timezones. Check # http://python.org/sf/1447945 for", "= datetime.timedelta(seconds=gmtoff) tti.isdst = isdst tti.abbr = abbr[abbrind:abbr.find('\\x00', abbrind)] tti.isstd", "lines[i].rstrip() if not line: del lines[i] elif i > 0", "os.path.isfile(filepath): try: tz = tzfile(filepath) break except (IOError, OSError, ValueError):", "was changed to unicode strings \"\"\" def inner_func(*args, **kwargs): if", "self._ttinfo_std = self._ttinfo_first = self._ttinfo_list[0] else: for i in range(timecnt-1,", "return self._ttinfo_before if laststd: while idx > 0: tti =", "else: if self._ttinfo_dst and not self._ttinfo_std: self._ttinfo_std = self._ttinfo_dst for", "EPOCHORDINAL) * 86400 + dt.hour * 3600 + dt.minute *", "be applied after the given time. # The pairs of", "x.yday elif x.jyday is not None: kwargs[\"nlyearday\"] = x.jyday if", "to become relative to wall time. # # I'm not", "= datetime.timedelta(seconds=-time.altzone) else: _dst_offset = _std_offset def utcoffset(self, dt): if", "a # ``standard'' byte order (the high-order byte # of", "isdst, abbrind = ttinfo[i] # Round to full-minutes if that's", "if not tti.isdst: return tti idx -= 1 else: return", "char; each one tells which of the different types of", "relative to wall time. # # I'm not sure about", "relativedelta if not relativedelta: from dateutil import relativedelta self._std_abbr =", "def __eq__(self, other): if not isinstance(other, tzlocal): return False return", "time, and in the binary file isstd and # isgmt", "by a one-byte value for tt_isdst # and a one-byte", "OTOH, it's # always in gmt time. Let me know", "None: raise ValueError(\"unknown string format\") # Here we break the", "other._std_offset and self._dst_offset == other._dst_offset and self._start_delta == other._start_delta and", "Process component rr = None if rrulelines: rr = rrule.rrulestr(\"\\n\".join(rrulelines),", "tzwin: try: tz = tzwin(name) except OSError: pass if not", "return ZERO @tzname_in_python2 def tzname(self, dt): return time.tzname[self._isdst(dt)] def _isdst(self,", "of # leap seconds to be applied after the given", "= object.__reduce__ class tzstr(tzrange): def __init__(self, s): global parser if", "result: # #>>> import tz, datetime #>>> t = tz.tzlocal()", "dateutil.tzwin import tzwin, tzwinlocal except (ImportError, OSError): tzwin, tzwinlocal =", "sorted in ascending order # by time. # Not used,", "= struct.unpack(\">%dl\" % (leapcnt*2), fileobj.read(leapcnt*8)) # Then there are tzh_ttisstdcnt", "(ttisstdcnt > i and isstd[i] != 0) tti.isgmt = (ttisgmtcnt", "the TZ variable handling. # GMT-3 actually *means* the timezone", "if len(s) == 4: return (int(s[:2])*3600+int(s[2:])*60)*signal elif len(s) == 6:", "% timecnt, fileobj.read(timecnt)) else: self._trans_idx = [] # Each ttinfo", "self._ttinfo_std if idx == 0: return self._ttinfo_before if laststd: while", "* 3600 + dt.minute * 60 + dt.second) idx =", "tzical(object): def __init__(self, fileobj): global rrule if not rrule: from", "about what to do when a given # time is", "datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()", "is a more stable implementation: # timestamp = ((dt.toordinal() -", "self._std_abbr def _isdst(self, dt): if not self._start_delta: return False year", "start < end: return dt >= start and dt <", "tz source file # is setup to wall time, and", "fix transition times to become relative to wall time. #", "utcoffset(self, dt): return ZERO def dst(self, dt): return ZERO @tzname_in_python2", "not closed: \"+comptype) if not tzid: raise ValueError(\"mandatory TZID not", "elif hasattr(fileobj, \"name\"): self._filename = fileobj.name else: self._filename = repr(fileobj)", "return lastcomp def utcoffset(self, dt): return self._find_comp(dt).tzoffsetto def dst(self, dt):", "lastcomp) if len(self._cachedate) > 10: self._cachedate.pop() self._cachecomp.pop() return lastcomp def", "# with local time types were specified as UTC or", "laststdoffset = tti.offset else: # This is dst time. Convert", "time. Let me know if you have comments # about", "transition times to become relative to wall time. # #", "file is used in handling POSIX-style # time zone environment", "repr(fileobj) # From tzfile(5): # # The time zone information", "tti.delta = datetime.timedelta(seconds=gmtoff) tti.isdst = isdst tti.abbr = abbr[abbrind:abbr.find('\\x00', abbrind)]", "tzid, comps=[]): self._tzid = tzid self._comps = comps self._cachedate =", "self._trans_idx[i] if not self._ttinfo_std and not tti.isdst: self._ttinfo_std = tti", "datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom self.isdst = isdst self.tzname = tzname", "s): global parser if not parser: from dateutil import parser", "laststdoffset = 0 self._trans_list = list(self._trans_list) for i in range(len(self._trans_list)):", "lastcomp = comp[0] self._cachedate.insert(0, dt) self._cachecomp.insert(0, lastcomp) if len(self._cachedate) >", "The number of characters of \"time zone # abbreviation strings\"", "if not parser: from dateutil import parser self._s = s", "if name in state: setattr(self, name, state[name]) class tzfile(datetime.tzinfo): #", "os.path.join(path, filename) if os.path.isfile(filepath): break else: continue if os.path.isfile(filepath): try:", "return not self.__eq__(other) def __getstate__(self): state = {} for name", "_ttinfo): return False return (self.offset == other.offset and self.delta ==", "fileobj.read(timecnt*4)) else: self._trans_list = [] # Next come tzh_timecnt one-byte", "4: return (int(s[:2])*3600+int(s[2:])*60)*signal elif len(s) == 6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else:", "[] # Each ttinfo structure is written as a four-byte", "which a leap second # occurs; the second gives the", "byte # order, followed by a one-byte value for tt_isdst", "time, to follow the documented way # of working with", "= datetime.timedelta(seconds=-time.timezone) if time.daylight: _dst_offset = datetime.timedelta(seconds=-time.altzone) else: _dst_offset =", "# The time zone information files used by tzset(3) #", "not line: continue name, value = line.split(':', 1) parms =", "dt): return self._offset def dst(self, dt): return ZERO @tzname_in_python2 def", "getattr(self, name, None) return state def __setstate__(self, state): for name", "'r') # ical should be encoded in UTF-8 with CRLF", "to wall time, and in the binary file isstd and", "= tzname self.rrule = rrule class _tzicalvtz(datetime.tzinfo): def __init__(self, tzid,", "global relativedelta if not relativedelta: from dateutil import relativedelta self._std_abbr", "= None self._end_delta = None else: self._start_delta = self._delta(res.start) if", "name in self.__slots__: state[name] = getattr(self, name, None) return state", "ValueError): pass else: tz = tzlocal() else: if name.startswith(\":\"): name", "were specified as UTC or # local time, and are", "start is None: self._start_delta = relativedelta.relativedelta( hours=+2, month=4, day=1, weekday=relativedelta.SU(+1))", "lines: if not line: continue name, value = line.split(':', 1)", "tzoffsetto is None: raise ValueError(\"mandatory TZOFFSETFROM not found\") # Process", "os.path.isabs(filepath): filename = filepath for path in TZPATHS: filepath =", "EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal() class tzutc(datetime.tzinfo): def utcoffset(self, dt): return ZERO", "= struct.unpack(\">%db\" % ttisstdcnt, fileobj.read(ttisstdcnt)) # Finally, there are tzh_ttisgmtcnt", "or wall clock time, and are used when # a", "# Default is 2AM. kwargs[\"seconds\"] = 7200 if isend: #", "some information. gmtoff = (gmtoff+30)//60*60 tti = _ttinfo() tti.offset =", "def dst(self, dt): if not self._ttinfo_dst: return ZERO tti =", "# Process component pass else: raise ValueError(\"unknown component: \"+value) comptype", "as time zone information files, followed by # sixteen bytes", "rr = rrule.rrulestr(\"\\n\".join(rrulelines), compatible=True, ignoretz=True, cache=True) comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto,", "Let me know if you have comments # about this.", "for attr in self.__slots__: setattr(self, attr, None) def __repr__(self): l", "RFC says nothing about what to do when a given", "other.offset and self.delta == other.delta and self.isdst == other.isdst and", "self._ttinfo_list: if not tti.isdst: self._ttinfo_before = tti break else: self._ttinfo_before", "whether the transition times associated # with local time types", "= self._trans_idx[i] if not tti.isdst: # This is std time.", "= struct.unpack(\">%dB\" % timecnt, fileobj.read(timecnt)) else: self._trans_idx = [] #", "self._ttinfo_std: self._ttinfo_std = self._ttinfo_dst for tti in self._ttinfo_list: if not", "standard time, to follow the documented way # of working", "the same-indexed transition time. These values # serve as indices", "offset to be a tzstr if c in \"0123456789\": try:", "# # return self._ttinfo_dst.offset-self._ttinfo_std.offset # # However, this class stores", "tti.abbr = abbr[abbrind:abbr.find('\\x00', abbrind)] tti.isstd = (ttisstdcnt > i and", "= comp[0] self._cachedate.insert(0, dt) self._cachecomp.insert(0, lastcomp) if len(self._cachedate) > 10:", "\"tzwinlocal\", \"gettz\"] relativedelta = None parser = None rrule =", "inner_func(*args, **kwargs): if PY3: return myfunc(*args, **kwargs) else: return myfunc(*args,", "gmt time. Let me know if you have comments #", "PY3: return myfunc(*args, **kwargs) else: return myfunc(*args, **kwargs).encode() return inner_func", "# The number of standard/wall indicators stored in the file.", "self.tzname = tzname self.rrule = rrule class _tzicalvtz(datetime.tzinfo): def __init__(self,", "(as # returned by time(2)) at which a leap second", "string_types): self._filename = fileobj fileobj = open(fileobj, 'rb') elif hasattr(fileobj,", "raise ValueError(\"mandatory DTSTART not found\") if tzoffsetfrom is None: raise", "comptype: if not founddtstart: raise ValueError(\"mandatory DTSTART not found\") if", "byte order. # Each is used as a transition time", "is used as a transition time (as returned by #", "ascending order. # These values are written in ``standard'' byte", "dstoffset is not None: self._dst_offset = datetime.timedelta(seconds=dstoffset) elif dstabbr and", "found\") if tzoffsetfrom is None: raise ValueError(\"mandatory TZOFFSETFROM not found\")", "return True def __ne__(self, other): return not self.__eq__(other) def __repr__(self):", "should be in wall time. OTOH, it's # always in", "self._start_delta = relativedelta.relativedelta( hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) else: self._start_delta =", "ValueError(\"no timezones defined\") elif len(keys) > 1: raise ValueError(\"more than", "if not tz: from dateutil.zoneinfo import gettz tz = gettz(name)", "else: if name in (\"GMT\", \"UTC\"): tz = tzutc() elif", "# Finally, there are tzh_ttisgmtcnt UTC/local # indicators, each stored", "in the binary file isstd and # isgmt are off,", "documentation says that utcoffset()-dst() must # be constant for every", "# six four-byte values of type long, written in a", "returned by time(2)) at which a leap second # occurs;", "day=31, weekday=relativedelta.SU(-1)) else: self._end_delta = end def utcoffset(self, dt): if", "s.strip() if not s: raise ValueError(\"empty offset\") if s[0] in", "byte # of the value is written first). if fileobj.read(4).decode()", "tzlocal() else: if name.startswith(\":\"): name = name[:-1] if os.path.isabs(name): if", "self._cachecomp.insert(0, lastcomp) if len(self._cachedate) > 10: self._cachedate.pop() self._cachecomp.pop() return lastcomp", "ttisstdcnt, # The number of leap seconds for which data", "the file. if timecnt: self._trans_idx = struct.unpack(\">%dB\" % timecnt, fileobj.read(timecnt))", "\"<tzicalvtz %s>\" % repr(self._tzid) __reduce__ = object.__reduce__ class tzical(object): def", "raise ValueError(\"mandatory TZOFFSETFROM not found\") if tzoffsetto is None: raise", "_find_comp(self, dt): if len(self._comps) == 1: return self._comps[0] dt =", "to do when a given # time is before the", "def __eq__(self, other): if not isinstance(other, tzrange): return False return", "std. self._trans_list[i] += laststdoffset self._trans_list = tuple(self._trans_list) def _find_ttinfo(self, dt,", "None: self._dst_offset = datetime.timedelta(seconds=dstoffset) elif dstabbr and stdoffset is not", "{} for name in self.__slots__: state[name] = getattr(self, name, None)", "with local time types were specified as standard # time", "and will be set to the first non-dst ttinfo, or", "fileobj.name else: self._s = repr(fileobj) self._vtz = {} self._parse_rfc(fileobj.read()) def", "parms = name.split(';') if not parms: raise ValueError(\"empty property name\")", "None comps = [] invtz = False comptype = None", "not os.path.isfile(filepath): filepath = filepath.replace(' ', '_') if not os.path.isfile(filepath):", "list(self._vtz.keys()) def get(self, tzid=None): if tzid is None: keys =", "values # serve as indices into an array of ttinfo", "lastcompdt or lastcompdt < compdt): lastcompdt = compdt lastcomp =", "[] # Next come tzh_timecnt one-byte values of type unsigned", "return not self.__eq__(other) def __repr__(self): return \"%s(%s, %s)\" % (self.__class__.__name__,", "lastcomp: # RFC says nothing about what to do when", "if # none is found. for comp in self._comps: if", "== \"TZOFFSETTO\": if parms: raise ValueError(\"unsupported TZOFFSETTO parm: \"+parms[0]) tzoffsetto", "tzlocal(datetime.tzinfo): _std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: _dst_offset = datetime.timedelta(seconds=-time.altzone) else:", "\", \".join(l)) def __eq__(self, other): if not isinstance(other, _ttinfo): return", "gettz tz = gettz(name) if not tz: for c in", "number of leap seconds for which data is # stored", "# tm_isdst should be set by localtime(3), and # tt_abbrind", "not isinstance(other, tzlocal): return False return (self._std_offset == other._std_offset and", "it should be in wall time. OTOH, it's # always", "UTF-8 with CRLF elif hasattr(fileobj, \"name\"): self._s = fileobj.name else:", "dt = dt.replace(tzinfo=None) if start < end: return dt >=", "# ``local time'' types described in the file is associated", "self._ttinfo_std: return None return self._find_ttinfo(dt).abbr def __eq__(self, other): if not", "__ne__(self, other): return not self.__eq__(other) def __repr__(self): return \"%s(...)\" %", "documentation # of the tzinfo class. delta = self._dst_offset-self._std_offset kwargs[\"seconds\"]", "return (self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr and self._std_offset", "datetime.timedelta(seconds=dstoffset) elif dstabbr and stdoffset is not None: self._dst_offset =", "return state def __setstate__(self, state): for name in self.__slots__: if", "from dateutil.zoneinfo import gettz tz = gettz(name) if not tz:", "ValueError: pass lastcomp = None lastcompdt = None for comp", "local time types were specified as UTC or # local", "dst(self, dt): return ZERO @tzname_in_python2 def tzname(self, dt): return \"UTC\"", "one component is needed\") # Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid,", "s[0] in ('+', '-'): signal = (-1, +1)[s[0]=='+'] s =", "each stored as a one-byte value; # they tell whether", "zone environment variables. if ttisstdcnt: isstd = struct.unpack(\">%db\" % ttisstdcnt,", "dt): if self._isdst(dt): return self._dst_offset else: return self._std_offset def dst(self,", "= object.__reduce__ class tzical(object): def __init__(self, fileobj): global rrule if", "\"tzfile\", \"tzrange\", \"tzstr\", \"tzical\", \"tzwin\", \"tzwinlocal\", \"gettz\"] relativedelta = None", "However, this class stores historical changes in the # dst", "file isstd and # isgmt are off, so it should", "ZERO @tzname_in_python2 def tzname(self, dt): return self._find_comp(dt).tzname def __repr__(self): return", "of \"local time types\" for which data # is stored", "order. # Each is used as a transition time (as", "end=None): global relativedelta if not relativedelta: from dateutil import relativedelta", "for which data # is stored in the file (must", "_parse_offset(self, s): s = s.strip() if not s: raise ValueError(\"empty", "tt_abbrind. In each # structure, tt_gmtoff gives the number of", "= (ttisstdcnt > i and isstd[i] != 0) tti.isgmt =", "= (-1, +1)[s[0]=='+'] s = s[1:] else: signal = +1", "end else: return dt >= start or dt < end", "sorted in ascending order. # These values are written in", "return False year = datetime.datetime(dt.year, 1, 1) start = year+self._start_delta", "in lines: if not line: continue name, value = line.split(':',", "tuple(trans_idx) # Set standard, dst, and before ttinfos. before will", "other): if not isinstance(other, tzlocal): return False return (self._std_offset ==", "dateutil import rrule if isinstance(fileobj, string_types): self._s = fileobj fileobj", "# time zone environment variables. if ttisstdcnt: isstd = struct.unpack(\">%db\"", "if not self._start_delta: return False year = datetime.datetime(dt.year, 1, 1)", "value for tt_isdst # and a one-byte value for tt_abbrind.", "\"+value) elif comptype: if name == \"DTSTART\": rrulelines.append(line) founddtstart =", "def dst(self, dt): if self._isdst(dt): return self._dst_offset-self._std_offset else: return ZERO", "= tzfile(name) else: tz = None else: for path in", "False comptype = None for line in lines: if not", "for line in lines: if not line: continue name, value", "else: tz = None else: for path in TZPATHS: filepath", "class\" % self.__class__.__name__) return (self.__class__, (self._filename,)) class tzrange(datetime.tzinfo): def __init__(self,", "% (self.__class__.__name__, repr(self._name), self._offset.days*86400+self._offset.seconds) __reduce__ = object.__reduce__ class tzlocal(datetime.tzinfo): _std_offset", "gettz(name=None): tz = None if not name: try: name =", "datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()", "of type long, sorted in ascending order. # These values", "return (self.__class__, (self._filename,)) class tzrange(datetime.tzinfo): def __init__(self, stdabbr, stdoffset=None, dstabbr=None,", "# Next come tzh_timecnt one-byte values of type unsigned #", "two times. tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset, start=False, end=False) if", "order (the high-order byte # of the value is written", "x.time else: # Default is 2AM. kwargs[\"seconds\"] = 7200 if", "if ttisstdcnt: isstd = struct.unpack(\">%db\" % ttisstdcnt, fileobj.read(ttisstdcnt)) # Finally,", "to follow the documented way # of working with the", "order, followed by a one-byte value for tt_isdst # and", "else: # This is dst time. Convert to std. self._trans_list[i]", "datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' # # Here is a more stable implementation:", "the compatibility with the TZ variable handling. # GMT-3 actually", "# always in gmt time. Let me know if you", "in standard byte order; the # first value of each", "standard byte order; the # first value of each pair", "\"name\"): self._s = fileobj.name else: self._s = repr(fileobj) self._vtz =", "the tzinfo class. delta = self._dst_offset-self._std_offset kwargs[\"seconds\"] -= delta.seconds+delta.days*86400 return", "i += 1 tzid = None comps = [] invtz", "while idx > 0: tti = self._trans_idx[idx-1] if not tti.isdst:", "self._cachedate.pop() self._cachecomp.pop() return lastcomp def utcoffset(self, dt): return self._find_comp(dt).tzoffsetto def", "', '_') if not os.path.isfile(filepath): continue try: tz = tzfile(filepath)", "__repr__(self): l = [] for attr in self.__slots__: value =", "into the array of # time zone abbreviation characters that", "at least one offset to be a tzstr if c", "# # The time zone information files used by tzset(3)", "False return (self.offset == other.offset and self.delta == other.delta and", "= tzlocal() else: if name.startswith(\":\"): name = name[:-1] if os.path.isabs(name):", "sys.platform != \"win32\": TZFILES = [\"/etc/localtime\", \"localtime\"] TZPATHS = [\"/usr/share/zoneinfo\",", "Check # http://python.org/sf/1447945 for some information. gmtoff = (gmtoff+30)//60*60 tti", "else: self._trans_idx = [] # Each ttinfo structure is written", "# I'm not sure about this. In my tests, the", "datetime.datetime.utcfromtimestamp(0).toordinal() class tzutc(datetime.tzinfo): def utcoffset(self, dt): return ZERO def dst(self,", "except (IOError, OSError, ValueError): pass else: tz = tzlocal() else:", "Everything has been read ** # Build ttinfo list self._ttinfo_list", "whether # tm_isdst should be set by localtime(3), and #", "other): return not self.__eq__(other) def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__,", "for computing local time # change. if timecnt: self._trans_list =", "if not tti.isdst: self._ttinfo_before = tti break else: self._ttinfo_before =", "else: return self._std_abbr def _isdst(self, dt): if not self._start_delta: return", "offers extensions to the standard Python datetime module. \"\"\" import", "the different types of # ``local time'' types described in", "value of each pair gives the time (as # returned", "indicators, each stored as a one-byte value; # they tell", "raise ValueError(\"unsupported TZOFFSETTO parm: \"+parms[0]) tzoffsetto = self._parse_offset(value) elif name", "type unsigned # char; each one tells which of the", "ValueError(\"magic not found\") fileobj.read(16) ( # The number of UTC/local", "self._vtz.get(tzid) def _parse_offset(self, s): s = s.strip() if not s:", "time # change. if timecnt: self._trans_list = struct.unpack(\">%dl\" % timecnt,", "name is None or name == \":\": for filepath in", "ttinfo objects. trans_idx = [] for idx in self._trans_idx: trans_idx.append(self._ttinfo_list[idx])", "ttisgmtcnt: isgmt = struct.unpack(\">%db\" % ttisgmtcnt, fileobj.read(ttisgmtcnt)) # ** Everything", "# is used in handling POSIX-style time zone envi- #", "value founddtstart = False tzoffsetfrom = None tzoffsetto = None", "for i in range(typecnt): gmtoff, isdst, abbrind = ttinfo[i] #", "In my tests, the tz source file # is setup", "first onset date. We'll look for the # first standard", "try: from dateutil.tzwin import tzwin, tzwinlocal except (ImportError, OSError): tzwin,", "name in self.__slots__: if name in state: setattr(self, name, state[name])", "ValueError(\"empty offset\") if s[0] in ('+', '-'): signal = (-1,", "if that's not the case. Python's # datetime doesn't accept", "not comp.isdst: lastcomp = comp break else: lastcomp = comp[0]", "that follow the # ttinfo structure(s) in the file. ttinfo", "6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: raise ValueError(\"invalid offset: \"+s) def _parse_rfc(self,", "% (self.__class__.__name__, \", \".join(l)) def __eq__(self, other): if not isinstance(other,", "full-minutes if that's not the case. Python's # datetime doesn't", "> 10: self._cachedate.pop() self._cachecomp.pop() return lastcomp def utcoffset(self, dt): return", "= tti elif not self._ttinfo_dst and tti.isdst: self._ttinfo_dst = tti", "< len(lines): line = lines[i].rstrip() if not line: del lines[i]", "timecnt: self._trans_list = struct.unpack(\">%dl\" % timecnt, fileobj.read(timecnt*4)) else: self._trans_list =", "if self._start_delta: self._end_delta = self._delta(res.end, isend=1) def _delta(self, x, isend=0):", "\"isdst\", \"abbr\", \"isstd\", \"isgmt\"] def __init__(self): for attr in self.__slots__:", "ZERO @tzname_in_python2 def tzname(self, dt): if self._isdst(dt): return self._dst_abbr else:", "# dst offset, so I belive that this wouldn't be", "time.tzname[self._isdst(dt)] def _isdst(self, dt): # We can't use mktime here.", "and end is None: self._end_delta = relativedelta.relativedelta( hours=+1, month=10, day=31,", "utcoffset(self, dt): if self._isdst(dt): return self._dst_offset else: return self._std_offset def", "them are dst. self._ttinfo_std = None self._ttinfo_dst = None self._ttinfo_before", "return ZERO @tzname_in_python2 def tzname(self, dt): if self._isdst(dt): return self._dst_abbr", "[] TZPATHS = [] def gettz(name=None): tz = None if", "def utcoffset(self, dt): return ZERO def dst(self, dt): return ZERO", "state = {} for name in self.__slots__: state[name] = getattr(self,", "pass else: tz = None if tzwin: try: tz =", "as a one-byte value; # they tell whether the transition", "+= laststdoffset self._trans_list = tuple(self._trans_list) def _find_ttinfo(self, dt, laststd=0): timestamp", "= datetime.timedelta(seconds=dstoffset) elif dstabbr and stdoffset is not None: self._dst_offset", "when deciding if # the hour near to a change", "= s.splitlines() if not lines: raise ValueError(\"empty string\") # Unfold", "1 tzid = None comps = [] invtz = False", "be set by localtime(3), and # tt_abbrind serves as an", "added to UTC, tt_isdst tells whether # tm_isdst should be", "\"+parms[0]) tzoffsetto = self._parse_offset(value) elif name == \"TZNAME\": if parms:", "name == \":\": for filepath in TZFILES: if not os.path.isabs(filepath):", "wouldn't be the right # way to implement this. @tzname_in_python2", "zone # abbreviation strings\" stored in the file. charcnt, )", "self._dst_offset = self._std_offset+datetime.timedelta(hours=+1) else: self._dst_offset = ZERO if dstabbr and", "= None else: self._start_delta = self._delta(res.start) if self._start_delta: self._end_delta =", "state): for name in self.__slots__: if name in state: setattr(self,", "number of \"local time types\" for which data # is", "dst, if all of them are dst. self._ttinfo_std = None", "= name self._offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt): return self._offset", "one-byte value for tt_abbrind. In each # structure, tt_gmtoff gives", "= _tzicalvtz(tzid, comps) invtz = False elif value == comptype:", "myfunc(*args, **kwargs).encode() return inner_func ZERO = datetime.timedelta(0) EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal()", "needed\") # Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz =", "\"transition times\" for which data # is stored in the", "self._find_ttinfo(dt).abbr def __eq__(self, other): if not isinstance(other, tzfile): return False", "TZPATHS = [] def gettz(name=None): tz = None if not", "tti.offset = gmtoff tti.delta = datetime.timedelta(seconds=gmtoff) tti.isdst = isdst tti.abbr", "pass break else: if name in (\"GMT\", \"UTC\"): tz =", "the file. timecnt, # The number of \"local time types\"", "comp.isdst: # Handle the extra hour in DST -> STD", "other._start_delta and self._end_delta == other._end_delta) def __ne__(self, other): return not", "be a tzstr if c in \"0123456789\": try: tz =", "self._find_ttinfo(dt) if not tti.isdst: return ZERO # The documentation says", "not self._ttinfo_std: self._ttinfo_std = self._ttinfo_dst for tti in self._ttinfo_list: if", "stdabbr self._dst_abbr = dstabbr if stdoffset is not None: self._std_offset", "datetime.timedelta(seconds=-time.timezone) if time.daylight: _dst_offset = datetime.timedelta(seconds=-time.altzone) else: _dst_offset = _std_offset", "following result: # #>>> import tz, datetime #>>> t =", "\".join(l)) def __eq__(self, other): if not isinstance(other, _ttinfo): return False", "# appears next in the file. if timecnt: self._trans_idx =", "(self.__class__.__name__, repr(self._s)) if sys.platform != \"win32\": TZFILES = [\"/etc/localtime\", \"localtime\"]", "@tzname_in_python2 def tzname(self, dt): return self._name def __eq__(self, other): return", "object.__reduce__ class _ttinfo(object): __slots__ = [\"offset\", \"delta\", \"isdst\", \"abbr\", \"isstd\",", "None: self._start_delta = relativedelta.relativedelta( hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) else: self._start_delta", "for trans in self._trans_list: if timestamp < trans: break idx", "of \"time zone # abbreviation strings\" stored in the file.", "a one-byte value for tt_abbrind. In each # structure, tt_gmtoff", "relativedelta: from dateutil import relativedelta self._std_abbr = stdabbr self._dst_abbr =", "from dateutil import relativedelta self._std_abbr = stdabbr self._dst_abbr = dstabbr", "if not tz: for c in name: # name must", "pass if not tz: from dateutil.zoneinfo import gettz tz =", "self._s = s res = parser._parsetz(s) if res is None:", "offset): self._name = name self._offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt):", "31 kwargs[\"weekday\"] = relativedelta.SU(-1) if x.time is not None: kwargs[\"seconds\"]", "else: # Default is 2AM. kwargs[\"seconds\"] = 7200 if isend:", "time (as returned by # time(2)) at which the rules", "self._start_delta: return False year = datetime.datetime(dt.year, 1, 1) start =", "not self.__eq__(other) def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._filename)) def", "\"END\": if value == \"VTIMEZONE\": if comptype: raise ValueError(\"component not", "seconds for which data is # stored in the file.", "elif name in (\"TZURL\", \"LAST-MODIFIED\", \"COMMENT\"): pass else: raise ValueError(\"unsupported", "else: return self._trans_idx[idx-1] def utcoffset(self, dt): if not self._ttinfo_std: return", "in a # ``standard'' byte order (the high-order byte #", "return self._ttinfo_std if idx == 0: return self._ttinfo_before if laststd:", "parms: raise ValueError(\"unsupported TZOFFSETTO parm: \"+parms[0]) tzoffsetto = self._parse_offset(value) elif", "class stores historical changes in the # dst offset, so", "number of # seconds to be added to UTC, tt_isdst", "0) tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0)", "is found. for comp in self._comps: if not comp.isdst: lastcomp", "time types were specified as UTC or # local time,", "= tz.tzlocal() #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()", "other._dst_offset) return True def __ne__(self, other): return not self.__eq__(other) def", "struct.unpack(\">%db\" % ttisgmtcnt, fileobj.read(ttisgmtcnt)) # ** Everything has been read", "timecnt, fileobj.read(timecnt)) else: self._trans_idx = [] # Each ttinfo structure", "if not tti.isdst: # This is std time. self._trans_list[i] +=", "of four-byte # values, written in standard byte order; the", "given time. # The pairs of values are sorted in", "value == comptype: if not founddtstart: raise ValueError(\"mandatory DTSTART not", "# structure, tt_gmtoff gives the number of # seconds to", "in DST -> STD compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True) else: compdt", "< compdt): lastcompdt = compdt lastcomp = comp if not", "self.rrule = rrule class _tzicalvtz(datetime.tzinfo): def __init__(self, tzid, comps=[]): self._tzid", "__eq__(self, other): return (isinstance(other, tzutc) or (isinstance(other, tzoffset) and other._offset", "indicators stored in the file. ttisstdcnt, # The number of", "ttinfo, or to # the first dst, if all of", "signal = +1 if len(s) == 4: return (int(s[:2])*3600+int(s[2:])*60)*signal elif", "dst. self._ttinfo_std = None self._ttinfo_dst = None self._ttinfo_before = None", "way to implement this. @tzname_in_python2 def tzname(self, dt): if not", "# _std_offset and _dst_offset set. Use False in start/end #", "= fileobj.name else: self._s = repr(fileobj) self._vtz = {} self._parse_rfc(fileobj.read())", "ZERO def dst(self, dt): return ZERO @tzname_in_python2 def tzname(self, dt):", "if not self._ttinfo_std and not tti.isdst: self._ttinfo_std = tti elif", "\"TZif\" to identify # them as time zone information files,", "come tzh_timecnt one-byte values of type unsigned # char; each", "ValueError(\"empty string\") # Unfold i = 0 while i <", "return dt >= start and dt < end else: return", "doesn't accept sub-minute timezones. Check # http://python.org/sf/1447945 for some information.", "fileobj): if isinstance(fileobj, string_types): self._filename = fileobj fileobj = open(fileobj,", "future use, followed by # six four-byte values of type", "= relativedelta.weekday(x.weekday, x.week) if x.week > 0: kwargs[\"day\"] = 1", "class _tzicalvtz(datetime.tzinfo): def __init__(self, tzid, comps=[]): self._tzid = tzid self._comps", "= os.path.join(path, filename) if os.path.isfile(filepath): break else: continue if os.path.isfile(filepath):", "for comp in self._comps: if not comp.isdst: lastcomp = comp", "localtime(3), and # tt_abbrind serves as an index into the", "after the given time. # The pairs of values are", "\"TZif\": raise ValueError(\"magic not found\") fileobj.read(16) ( # The number", "def _isdst(self, dt): # We can't use mktime here. It", "self._trans_list = tuple(self._trans_list) def _find_ttinfo(self, dt, laststd=0): timestamp = ((dt.toordinal()", "in handling POSIX-style time zone envi- # ronment variables. if", "% timecnt, fileobj.read(timecnt*4)) else: self._trans_list = [] # Next come", "def __repr__(self): l = [] for attr in self.__slots__: value", "Now fix transition times to become relative to wall time.", "zone file is used in handling POSIX-style # time zone", "is not None: kwargs[\"seconds\"] = x.time else: # Default is", "def __repr__(self): return \"%s()\" % self.__class__.__name__ __reduce__ = object.__reduce__ class", "self.abbr == other.abbr and self.isstd == other.isstd and self.isgmt ==", "for tt_isdst # and a one-byte value for tt_abbrind. In", "_tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype == \"DAYLIGHT\"), tzname, rr) comps.append(comp) comptype =", "if x.weekday is not None: kwargs[\"weekday\"] = relativedelta.weekday(x.weekday, x.week) if", "tz = tzstr(name) except ValueError: pass break else: if name", "a leap second # occurs; the second gives the total", "self._ttinfo_std and not tti.isdst: self._ttinfo_std = tti elif not self._ttinfo_dst", "\"name\"): self._filename = fileobj.name else: self._filename = repr(fileobj) # From", "now if leapcnt: leap = struct.unpack(\">%dl\" % (leapcnt*2), fileobj.read(leapcnt*8)) #", "comps self._cachedate = [] self._cachecomp = [] def _find_comp(self, dt):", "= None if rrulelines: rr = rrule.rrulestr(\"\\n\".join(rrulelines), compatible=True, ignoretz=True, cache=True)", "return False return (self.offset == other.offset and self.delta == other.delta", "followed by # six four-byte values of type long, written", "= self._find_comp(dt) if comp.isdst: return comp.tzoffsetdiff else: return ZERO @tzname_in_python2", "# with the same-indexed transition time. These values # serve", "if start < end: return dt >= start and dt", "types were specified as UTC or # local time, and", "c in \"0123456789\": try: tz = tzstr(name) except ValueError: pass", "belive that this wouldn't be the right # way to", "def _delta(self, x, isend=0): kwargs = {} if x.month is", "tti.isdst = isdst tti.abbr = abbr[abbrind:abbr.find('\\x00', abbrind)] tti.isstd = (ttisstdcnt", "else: for i in range(timecnt-1, -1, -1): tti = self._trans_idx[i]", "Build ttinfo list self._ttinfo_list = [] for i in range(typecnt):", "associated # with local time types were specified as UTC", "by # six four-byte values of type long, written in", "not self._trans_list: self._ttinfo_std = self._ttinfo_first = self._ttinfo_list[0] else: for i", "self._comps: if not comp.isdst: # Handle the extra hour in", "__reduce__ = object.__reduce__ class tzical(object): def __init__(self, fileobj): global rrule", "def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._filename)) def __reduce__(self): if", "# The number of leap seconds for which data is", "objects. trans_idx = [] for idx in self._trans_idx: trans_idx.append(self._ttinfo_list[idx]) self._trans_idx", "from mo_future import PY3, string_types __license__ = \"Simplified BSD\" __all__", "% (leapcnt*2), fileobj.read(leapcnt*8)) # Then there are tzh_ttisstdcnt standard/wall #", "os.environ[\"TZ\"] except KeyError: pass if name is None or name", "attr in self.__slots__: value = getattr(self, attr) if value is", "i in range(timecnt-1, -1, -1): tti = self._trans_idx[i] if not", "= name.split(';') if not parms: raise ValueError(\"empty property name\") name", "= tzwin(name) except OSError: pass if not tz: from dateutil.zoneinfo", "extra hour in DST -> STD compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True)", "ValueError(\"unknown string format\") # Here we break the compatibility with", "abbr[abbrind:abbr.find('\\x00', abbrind)] tti.isstd = (ttisstdcnt > i and isstd[i] !=", "in the file. ttisgmtcnt, # The number of standard/wall indicators", "is unstable when deciding if # the hour near to", "10: self._cachedate.pop() self._cachecomp.pop() return lastcomp def utcoffset(self, dt): return self._find_comp(dt).tzoffsetto", "del lines[i] elif i > 0 and line[0] == \"", "# isgmt are off, so it should be in wall", "# of the value is written first). if fileobj.read(4).decode() !=", "tell whether the transition times associated # with local time", "if not name: try: name = os.environ[\"TZ\"] except KeyError: pass", "comp.tzoffsetdiff else: return ZERO @tzname_in_python2 def tzname(self, dt): return self._find_comp(dt).tzname", "not s: raise ValueError(\"empty offset\") if s[0] in ('+', '-'):", "comp.isdst: return comp.tzoffsetdiff else: return ZERO @tzname_in_python2 def tzname(self, dt):", "other): return not self.__eq__(other) def __repr__(self): return \"%s(%s, %s)\" %", "about this. In my tests, the tz source file #", "except (IOError, OSError, ValueError): pass else: tz = None if", "raise ValueError(\"unsupported TZID parm: \"+parms[0]) tzid = value elif name", "ttisstdcnt: isstd = struct.unpack(\">%db\" % ttisstdcnt, fileobj.read(ttisstdcnt)) # Finally, there", "a time zone file is used in handling POSIX-style #", "gives the number of # seconds to be added to", "utcoffset(self, dt): return self._offset def dst(self, dt): return ZERO @tzname_in_python2", "that this wouldn't be the right # way to implement", "# name must have at least one offset to be", "# the hour near to a change is DST or", "tzfile(5): # # The time zone information files used by", "stored in the file. leapcnt, # The number of \"transition", "other._trans_list and self._trans_idx == other._trans_idx and self._ttinfo_list == other._ttinfo_list) def", "self._start_delta: self._end_delta = self._delta(res.end, isend=1) def _delta(self, x, isend=0): kwargs", "# first value of each pair gives the time (as", "= None for comp in self._comps: if not comp.isdst: #", "the value is written first). if fileobj.read(4).decode() != \"TZif\": raise", "#'BRDT' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' # # Here is a more", "raise ValueError(\"empty offset\") if s[0] in ('+', '-'): signal =", "if tzoffsetto is None: raise ValueError(\"mandatory TZOFFSETFROM not found\") #", "sixteen bytes reserved for future use, followed by # six", "stored in the file. ttisgmtcnt, # The number of standard/wall", "= rrule class _tzicalvtz(datetime.tzinfo): def __init__(self, tzid, comps=[]): self._tzid =", "def tzname(self, dt): return self._find_comp(dt).tzname def __repr__(self): return \"<tzicalvtz %s>\"", "name self._offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt): return self._offset def", "were specified as standard # time or wall clock time,", "self._dst_offset-self._std_offset else: return ZERO @tzname_in_python2 def tzname(self, dt): return time.tzname[self._isdst(dt)]", "but was changed to unicode strings \"\"\" def inner_func(*args, **kwargs):", "values of type long, sorted in ascending order. # These", "repr(fileobj) self._vtz = {} self._parse_rfc(fileobj.read()) def keys(self): return list(self._vtz.keys()) def", "of type long, in a standard byte # order, followed", "file. ttisstdcnt, # The number of leap seconds for which", "UTC/local # indicators, each stored as a one-byte value; #", "return self._trans_idx[idx-1] def utcoffset(self, dt): if not self._ttinfo_std: return ZERO", "a more stable implementation: # timestamp = ((dt.toordinal() - EPOCHORDINAL)", "break idx += 1 else: return self._ttinfo_std if idx ==", "None: kwargs[\"nlyearday\"] = x.jyday if not kwargs: # Default is", "self._trans_list[i] += laststdoffset self._trans_list = tuple(self._trans_list) def _find_ttinfo(self, dt, laststd=0):", "TZFILES = [\"/etc/localtime\", \"localtime\"] TZPATHS = [\"/usr/share/zoneinfo\", \"/usr/lib/zoneinfo\", \"/etc/zoneinfo\"] else:", "TZNAME parm: \"+parms[0]) tzname = value elif name == \"COMMENT\":", "self._trans_idx[idx-1] def utcoffset(self, dt): if not self._ttinfo_std: return ZERO return", "self._ttinfo_before = tti break else: self._ttinfo_before = self._ttinfo_list[0] # Now", "gettz(name) if not tz: for c in name: # name", "if res.stdabbr in (\"GMT\", \"UTC\"): res.stdoffset *= -1 # We", "tt_isdst # and a one-byte value for tt_abbrind. In each", "= x.day elif x.yday is not None: kwargs[\"yearday\"] = x.yday", "0: raise ValueError(\"no timezones defined\") elif len(keys) > 1: raise", "kwargs[\"weekday\"] = relativedelta.SU(+1) else: kwargs[\"month\"] = 10 kwargs[\"day\"] = 31", "and a one-byte value for tt_abbrind. In each # structure,", "trans_idx = [] for idx in self._trans_idx: trans_idx.append(self._ttinfo_list[idx]) self._trans_idx =", "self.__eq__(other) def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._filename)) def __reduce__(self):", "= fileobj.read(charcnt).decode() # Then there are tzh_leapcnt pairs of four-byte", "information files, followed by # sixteen bytes reserved for future", "self._dst_abbr == other._dst_abbr and self._std_offset == other._std_offset and self._dst_offset ==", "fileobj = open(fileobj, 'rb') elif hasattr(fileobj, \"name\"): self._filename = fileobj.name", "it first, since _delta() needs # _std_offset and _dst_offset set.", "self._trans_idx[i] if not tti.isdst: # This is std time. self._trans_list[i]", "end def __eq__(self, other): if not isinstance(other, tzrange): return False", "as UTC or # local time, and are used when", "so it should be in wall time. OTOH, it's #", "keys = list(self._vtz.keys()) if len(keys) == 0: raise ValueError(\"no timezones", "used in handling POSIX-style # time zone environment variables. if", "of them are dst. self._ttinfo_std = None self._ttinfo_dst = None", "list(self._vtz.keys()) if len(keys) == 0: raise ValueError(\"no timezones defined\") elif", "not None: self._std_offset = datetime.timedelta(seconds=stdoffset) else: self._std_offset = ZERO if", "= end def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset else:", "# time(2)) at which the rules for computing local time", "= dt.replace(tzinfo=None) if start < end: return dt >= start", "raise ValueError(\"mandatory TZOFFSETFROM not found\") # Process component rr =", "False elif value == comptype: if not founddtstart: raise ValueError(\"mandatory", "x.day elif x.yday is not None: kwargs[\"yearday\"] = x.yday elif", "leapcnt, # The number of \"transition times\" for which data", "if self._ttinfo_std and self._ttinfo_dst: break else: if self._ttinfo_dst and not", "tzname_in_python2(myfunc): \"\"\"Change unicode output into bytestrings in Python 2 tzname()", "= self._ttinfo_list[0] # Now fix transition times to become relative", "in gmt time. Let me know if you have comments", "def tzname(self, dt): return time.tzname[self._isdst(dt)] def _isdst(self, dt): # We", "relativedelta self._std_abbr = stdabbr self._dst_abbr = dstabbr if stdoffset is", "relativedelta.relativedelta( hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) else: self._start_delta = start if", "seconds to be applied after the given time. # The", "return self._dst_offset-self._std_offset else: return ZERO @tzname_in_python2 def tzname(self, dt): if", "inc=True) else: compdt = comp.rrule.before(dt, inc=True) if compdt and (not", "dt < end def __eq__(self, other): if not isinstance(other, tzrange):", "number of standard/wall indicators stored in the file. ttisstdcnt, #", "self._offset def dst(self, dt): return ZERO @tzname_in_python2 def tzname(self, dt):", "return not self.__eq__(other) def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._filename))", "%s parm: %s \"%(name, parms[0])) tzoffsetfrom = self._parse_offset(value) elif name", "(self.offset == other.offset and self.delta == other.delta and self.isdst ==", "not None: kwargs[\"weekday\"] = relativedelta.weekday(x.weekday, x.week) if x.week > 0:", "values are sorted in ascending order # by time. #", "= [] invtz = False comptype = None for line", "return self._std_abbr def _isdst(self, dt): if not self._start_delta: return False", "if x.week > 0: kwargs[\"day\"] = 1 else: kwargs[\"day\"] =", "self._end_delta = end def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset", "by tzh_timecnt four-byte # values of type long, sorted in", "other.isgmt) def __ne__(self, other): return not self.__eq__(other) def __getstate__(self): state", "end=False) if not res.dstabbr: self._start_delta = None self._end_delta = None", "(isinstance(other, tzoffset) and other._offset == ZERO)) def __ne__(self, other): return", "= getattr(self, name, None) return state def __setstate__(self, state): for", "self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom self.isdst = isdst self.tzname = tzname self.rrule", "if parms: raise ValueError(\"unsupported TZOFFSETTO parm: \"+parms[0]) tzoffsetto = self._parse_offset(value)", "if not isinstance(other, _ttinfo): return False return (self.offset == other.offset", "% ttisgmtcnt, fileobj.read(ttisgmtcnt)) # ** Everything has been read **", "[] def gettz(name=None): tz = None if not name: try:", "not name: try: name = os.environ[\"TZ\"] except KeyError: pass if", "= None parser = None rrule = None try: from", "is not None: self._dst_offset = self._std_offset+datetime.timedelta(hours=+1) else: self._dst_offset = ZERO", "tzname, rr) comps.append(comp) comptype = None else: raise ValueError(\"invalid component", "\"tzwin\", \"tzwinlocal\", \"gettz\"] relativedelta = None parser = None rrule", "__ne__(self, other): return not self.__eq__(other) def __repr__(self): return \"%s()\" %", "high-order byte # of the value is written first). if", "lines: raise ValueError(\"empty string\") # Unfold i = 0 while", "# # The code above yields the following result: #", "[\"tzutc\", \"tzoffset\", \"tzlocal\", \"tzfile\", \"tzrange\", \"tzstr\", \"tzical\", \"tzwin\", \"tzwinlocal\", \"gettz\"]", "fileobj.name else: self._filename = repr(fileobj) # From tzfile(5): # #", "# ``standard'' byte order (the high-order byte # of the", "not isinstance(other, _ttinfo): return False return (self.offset == other.offset and", "OSError): tzwin, tzwinlocal = None, None def tzname_in_python2(myfunc): \"\"\"Change unicode", "that would be: # # return self._ttinfo_dst.offset-self._ttinfo_std.offset # # However,", "\"DAYLIGHT\"): # Process component pass else: raise ValueError(\"unknown component: \"+value)", "trans: break idx += 1 else: return self._ttinfo_std if idx", "isgmt are off, so it should be in wall time.", "None) def __repr__(self): l = [] for attr in self.__slots__:", "name in (\"TZURL\", \"LAST-MODIFIED\", \"COMMENT\"): pass else: raise ValueError(\"unsupported property:", "first non-dst ttinfo, or to # the first dst, if", "-1)) # return time.localtime(timestamp).tm_isdst # # The code above yields", "tzstr(name) except ValueError: pass break else: if name in (\"GMT\",", "# We must initialize it first, since _delta() needs #", "comp.rrule.before(dt-comp.tzoffsetdiff, inc=True) else: compdt = comp.rrule.before(dt, inc=True) if compdt and", "for ttinfo objects. trans_idx = [] for idx in self._trans_idx:", "TZID not found\") if not comps: raise ValueError(\"at least one", "other): if not isinstance(other, tzrange): return False return (self._std_abbr ==", "utcoffset(self, dt): if not self._ttinfo_std: return ZERO return self._find_ttinfo(dt).delta def", "s): lines = s.splitlines() if not lines: raise ValueError(\"empty string\")", "to be a tzstr if c in \"0123456789\": try: tz", "a given # time is before the first onset date.", "time. OTOH, it's # always in gmt time. Let me", "self._filename = fileobj.name else: self._filename = repr(fileobj) # From tzfile(5):", "Then there are tzh_ttisstdcnt standard/wall # indicators, each stored as", "self._dst_offset == other._dst_offset and self._start_delta == other._start_delta and self._end_delta ==", "dt): if self._isdst(dt): return self._dst_offset-self._std_offset else: return ZERO @tzname_in_python2 def", "tzname = None elif name == \"END\": if value ==", "+ dt.second) return time.localtime(timestamp+time.timezone).tm_isdst def __eq__(self, other): if not isinstance(other,", "use, followed by # six four-byte values of type long,", "self._std_offset = ZERO if dstoffset is not None: self._dst_offset =", "True def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return", "== \"DTSTART\": rrulelines.append(line) founddtstart = True elif name in (\"RRULE\",", "0: kwargs[\"day\"] = 1 else: kwargs[\"day\"] = 31 elif x.day:", "kwargs: # Default is to start on first sunday of", "self._cachecomp[self._cachedate.index(dt)] except ValueError: pass lastcomp = None lastcompdt = None", "self._trans_list: self._ttinfo_std = self._ttinfo_first = self._ttinfo_list[0] else: for i in", "appears next in the file. if timecnt: self._trans_idx = struct.unpack(\">%dB\"", "number of \"transition times\" for which data # is stored", "These values are written in ``standard'' byte order. # Each", "offset\") if s[0] in ('+', '-'): signal = (-1, +1)[s[0]=='+']", "is None: raise ValueError(\"mandatory TZOFFSETFROM not found\") # Process component", "the first dst, if all of them are dst. self._ttinfo_std", "is None: raise ValueError(\"mandatory TZOFFSETFROM not found\") if tzoffsetto is", "the hour near to a change is DST or not.", "dstoffset=None, start=None, end=None): global relativedelta if not relativedelta: from dateutil", "The number of standard/wall indicators stored in the file. ttisstdcnt,", "pass lastcomp = None lastcompdt = None for comp in", "self._end_delta == other._end_delta) def __ne__(self, other): return not self.__eq__(other) def", "The number of \"local time types\" for which data #", "other._offset == ZERO)) def __ne__(self, other): return not self.__eq__(other) def", "change. if timecnt: self._trans_list = struct.unpack(\">%dl\" % timecnt, fileobj.read(timecnt*4)) else:", "'-'): signal = (-1, +1)[s[0]=='+'] s = s[1:] else: signal", "% ttisstdcnt, fileobj.read(ttisstdcnt)) # Finally, there are tzh_ttisgmtcnt UTC/local #", "time types\" for which data # is stored in the", "timecnt: self._trans_idx = struct.unpack(\">%dB\" % timecnt, fileobj.read(timecnt)) else: self._trans_idx =", "tti = self._trans_idx[idx-1] if not tti.isdst: return tti idx -=", "name == \"TZOFFSETFROM\": if parms: raise ValueError(\"unsupported %s parm: %s", "start and dt < end else: return dt >= start", "return None return self._find_ttinfo(dt).abbr def __eq__(self, other): if not isinstance(other,", "\"BEGIN\": if value in (\"STANDARD\", \"DAYLIGHT\"): # Process component pass", "(isinstance(other, tzutc) or (isinstance(other, tzoffset) and other._offset == ZERO)) def", "__slots__ = [\"offset\", \"delta\", \"isdst\", \"abbr\", \"isstd\", \"isgmt\"] def __init__(self):", "not self.__eq__(other) def __repr__(self): return \"%s(%s, %s)\" % (self.__class__.__name__, repr(self._name),", "def tzname(self, dt): if not self._ttinfo_std: return None return self._find_ttinfo(dt).abbr", "if not isinstance(other, tzlocal): return False return (self._std_offset == other._std_offset", "_std_offset and _dst_offset set. Use False in start/end # to", "* 3600 + dt.minute * 60 + dt.second) return time.localtime(timestamp+time.timezone).tm_isdst", "parms: raise ValueError(\"unsupported %s parm: %s \"%(name, parms[0])) tzoffsetfrom =", "compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True) else: compdt = comp.rrule.before(dt, inc=True) if", "def utcoffset(self, dt): return self._find_comp(dt).tzoffsetto def dst(self, dt): comp =", "for path in TZPATHS: filepath = os.path.join(path, name) if not", "\"%s(%s, %s)\" % (self.__class__.__name__, repr(self._name), self._offset.days*86400+self._offset.seconds) __reduce__ = object.__reduce__ class", "self._comps[0] dt = dt.replace(tzinfo=None) try: return self._cachecomp[self._cachedate.index(dt)] except ValueError: pass", "into bytestrings in Python 2 tzname() API changed in Python", "= None if tzwin: try: tz = tzwin(name) except OSError:", "setattr(self, name, state[name]) class tzfile(datetime.tzinfo): # http://www.twinsun.com/tz/tz-link.htm # ftp://ftp.iana.org/tz/tz*.tar.gz def", "used when a time zone file # is used in", "for attr in self.__slots__: value = getattr(self, attr) if value", "__init__(self): for attr in self.__slots__: setattr(self, attr, None) def __repr__(self):", "binary file isstd and # isgmt are off, so it", "kwargs[\"seconds\"] = x.time else: # Default is 2AM. kwargs[\"seconds\"] =", "Then there are tzh_leapcnt pairs of four-byte # values, written", "= 7200 if isend: # Convert to standard time, to", "mktime here. It is unstable when deciding if # the", "in ascending order. # These values are written in ``standard''", "None self._ttinfo_before = None if self._ttinfo_list: if not self._trans_list: self._ttinfo_std", "while i < len(lines): line = lines[i].rstrip() if not line:", "\"isstd\", \"isgmt\"] def __init__(self): for attr in self.__slots__: setattr(self, attr,", "available\") tzid = keys[0] return self._vtz.get(tzid) def _parse_offset(self, s): s", "dt.minute * 60 + dt.second) idx = 0 for trans", "in self.__slots__: if name in state: setattr(self, name, state[name]) class", "res.stdoffset *= -1 # We must initialize it first, since", "# seconds to be added to UTC, tt_isdst tells whether", "other._std_abbr and self._dst_abbr == other._dst_abbr and self._std_offset == other._std_offset and", "weekday=relativedelta.SU(-1)) else: self._end_delta = end def utcoffset(self, dt): if self._isdst(dt):", "_parse_rfc(self, s): lines = s.splitlines() if not lines: raise ValueError(\"empty", "else: return ZERO @tzname_in_python2 def tzname(self, dt): return time.tzname[self._isdst(dt)] def", "def inner_func(*args, **kwargs): if PY3: return myfunc(*args, **kwargs) else: return", "# The code above yields the following result: # #>>>", "occurs; the second gives the total number of # leap", "# for tt_gmtoff of type long, in a standard byte", "hasattr(fileobj, \"name\"): self._filename = fileobj.name else: self._filename = repr(fileobj) #", "0) self._ttinfo_list.append(tti) # Replace ttinfo indexes for ttinfo objects. trans_idx", "( # The number of UTC/local indicators stored in the", "os.path.isfile(self._filename): raise ValueError(\"Unpickable %s class\" % self.__class__.__name__) return (self.__class__, (self._filename,))", "tzid=None): if tzid is None: keys = list(self._vtz.keys()) if len(keys)", "if not kwargs: # Default is to start on first", "It used to return bytes, but was changed to unicode", "self._ttinfo_std and self._ttinfo_dst: break else: if self._ttinfo_dst and not self._ttinfo_std:", "in \"0123456789\": try: tz = tzstr(name) except ValueError: pass break", "\"delta\", \"isdst\", \"abbr\", \"isstd\", \"isgmt\"] def __init__(self): for attr in", "= 0 while i < len(lines): line = lines[i].rstrip() if", "return myfunc(*args, **kwargs) else: return myfunc(*args, **kwargs).encode() return inner_func ZERO", "file. timecnt, # The number of \"local time types\" for", "= rrule.rrulestr(\"\\n\".join(rrulelines), compatible=True, ignoretz=True, cache=True) comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype", "self.__slots__: value = getattr(self, attr) if value is not None:", "else: raise ValueError(\"invalid component end: \"+value) elif comptype: if name", "abbreviation strings\" stored in the file. charcnt, ) = struct.unpack(\">6l\",", "tzfile): return False return (self._trans_list == other._trans_list and self._trans_idx ==", "dateutil import relativedelta self._std_abbr = stdabbr self._dst_abbr = dstabbr if", "in (\"GMT\", \"UTC\"): res.stdoffset *= -1 # We must initialize", "case. Python's # datetime doesn't accept sub-minute timezones. Check #", "global parser if not parser: from dateutil import parser self._s", "elif x.jyday is not None: kwargs[\"nlyearday\"] = x.jyday if not", "- EPOCHORDINAL) * 86400 + dt.hour * 3600 + dt.minute", "gives the total number of # leap seconds to be", "rrulelines.append(line) elif name == \"TZOFFSETFROM\": if parms: raise ValueError(\"unsupported %s", "transition times associated # with local time types were specified", "tti = self._trans_idx[i] if not self._ttinfo_std and not tti.isdst: self._ttinfo_std", "else: return dt >= start or dt < end def", "must initialize it first, since _delta() needs # _std_offset and", "self.__class__.__name__ __reduce__ = object.__reduce__ class _ttinfo(object): __slots__ = [\"offset\", \"delta\",", "= None else: raise ValueError(\"invalid component end: \"+value) elif comptype:", "in range(typecnt): ttinfo.append(struct.unpack(\">lbb\", fileobj.read(6))) abbr = fileobj.read(charcnt).decode() # Then there", "above header is followed by tzh_timecnt four-byte # values of", "s: raise ValueError(\"empty offset\") if s[0] in ('+', '-'): signal", "dst(self, dt): if self._isdst(dt): return self._dst_offset-self._std_offset else: return ZERO @tzname_in_python2", "# returned by time(2)) at which a leap second #", "* 60 + dt.second) idx = 0 for trans in", "_std_offset def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset else: return", "if not isend: kwargs[\"month\"] = 4 kwargs[\"day\"] = 1 kwargs[\"weekday\"]", "comps.append(comp) comptype = None else: raise ValueError(\"invalid component end: \"+value)", "self.__class__.__name__ __reduce__ = object.__reduce__ class tzoffset(datetime.tzinfo): def __init__(self, name, offset):", "\"tzlocal\", \"tzfile\", \"tzrange\", \"tzstr\", \"tzical\", \"tzwin\", \"tzwinlocal\", \"gettz\"] relativedelta =", "The pairs of values are sorted in ascending order #", "POSIX-style time zone envi- # ronment variables. if ttisgmtcnt: isgmt", "if not self._trans_list: self._ttinfo_std = self._ttinfo_first = self._ttinfo_list[0] else: for", "self._parse_offset(value) elif name == \"TZOFFSETTO\": if parms: raise ValueError(\"unsupported TZOFFSETTO", "the extra hour. See the documentation # of the tzinfo", "when # a time zone file is used in handling", "else: self._filename = repr(fileobj) # From tzfile(5): # # The", "gmtoff, isdst, abbrind = ttinfo[i] # Round to full-minutes if", "= self._trans_idx[i] if not self._ttinfo_std and not tti.isdst: self._ttinfo_std =", "to standard time, to follow the documented way # of", "to the first non-dst ttinfo, or to # the first", "isend: # Convert to standard time, to follow the documented", "# Unfold i = 0 while i < len(lines): line", "return \"<tzicalvtz %s>\" % repr(self._tzid) __reduce__ = object.__reduce__ class tzical(object):", "# An alternative for that would be: # # return", "> 0 and line[0] == \" \": lines[i-1] += line[1:]", "comp in self._comps: if not comp.isdst: lastcomp = comp break", "comptype = value founddtstart = False tzoffsetfrom = None tzoffsetto", "self.__slots__: if name in state: setattr(self, name, state[name]) class tzfile(datetime.tzinfo):", "not tz: from dateutil.zoneinfo import gettz tz = gettz(name) if", "== other.delta and self.isdst == other.isdst and self.abbr == other.abbr", "written in a # ``standard'' byte order (the high-order byte", "datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' # #", "in Python 2 tzname() API changed in Python 3. It", "-1): tti = self._trans_idx[i] if not self._ttinfo_std and not tti.isdst:", "time. These values # serve as indices into an array", "ValueError(\"unsupported TZNAME parm: \"+parms[0]) tzname = value elif name ==", "tti elif not self._ttinfo_dst and tti.isdst: self._ttinfo_dst = tti if", "x.jyday if not kwargs: # Default is to start on", "#>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST' #>>>", "at which a leap second # occurs; the second gives", "(self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp(object): def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None,", "31 elif x.day: kwargs[\"day\"] = x.day elif x.yday is not", "if tzoffsetfrom is None: raise ValueError(\"mandatory TZOFFSETFROM not found\") if", "= 10 kwargs[\"day\"] = 31 kwargs[\"weekday\"] = relativedelta.SU(-1) if x.time", "if dstabbr and end is None: self._end_delta = relativedelta.relativedelta( hours=+1,", "delta = self._dst_offset-self._std_offset kwargs[\"seconds\"] -= delta.seconds+delta.days*86400 return relativedelta.relativedelta(**kwargs) def __repr__(self):", "other.abbr and self.isstd == other.isstd and self.isgmt == other.isgmt) def", "the first non-dst ttinfo, or to # the first dst,", "ZERO if dstabbr and start is None: self._start_delta = relativedelta.relativedelta(", "tzname(self, dt): return self._find_comp(dt).tzname def __repr__(self): return \"<tzicalvtz %s>\" %", "(IOError, OSError, ValueError): pass else: tz = tzlocal() else: if", "time zone file is used in handling POSIX-style # time", "else: self._ttinfo_before = self._ttinfo_list[0] # Now fix transition times to", "for the # first standard component, or the first component,", "= [] TZPATHS = [] def gettz(name=None): tz = None", "# Build ttinfo list self._ttinfo_list = [] for i in", "gmtoff tti.delta = datetime.timedelta(seconds=gmtoff) tti.isdst = isdst tti.abbr = abbr[abbrind:abbr.find('\\x00',", "tzwin(name) except OSError: pass if not tz: from dateutil.zoneinfo import", "self._cachedate = [] self._cachecomp = [] def _find_comp(self, dt): if", "return myfunc(*args, **kwargs).encode() return inner_func ZERO = datetime.timedelta(0) EPOCHORDINAL =", "in self._trans_list: if timestamp < trans: break idx += 1", "fileobj.read(24)) # The above header is followed by tzh_timecnt four-byte", "a one-byte value; # they tell whether the transition times", "PY3, string_types __license__ = \"Simplified BSD\" __all__ = [\"tzutc\", \"tzoffset\",", "= \"Simplified BSD\" __all__ = [\"tzutc\", \"tzoffset\", \"tzlocal\", \"tzfile\", \"tzrange\",", "else: kwargs[\"day\"] = 31 elif x.day: kwargs[\"day\"] = x.day elif", "other): return not self.__eq__(other) def __getstate__(self): state = {} for", "== \":\": for filepath in TZFILES: if not os.path.isabs(filepath): filename", "not tti.isdst: self._ttinfo_before = tti break else: self._ttinfo_before = self._ttinfo_list[0]", "name == \"TZID\": if parms: raise ValueError(\"unsupported TZID parm: \"+parms[0])", "x.yday is not None: kwargs[\"yearday\"] = x.yday elif x.jyday is", "None: raise ValueError(\"mandatory TZOFFSETFROM not found\") # Process component rr", "order. # These values are written in ``standard'' byte order.", "to start on first sunday of april, and end #", "== \"BEGIN\" and value == \"VTIMEZONE\": tzid = None comps", "1) start = year+self._start_delta end = year+self._end_delta dt = dt.replace(tzinfo=None)", "rrule: from dateutil import rrule if isinstance(fileobj, string_types): self._s =", "# values, written in standard byte order; the # first", "time zone file # is used in handling POSIX-style time", "than one timezone available\") tzid = keys[0] return self._vtz.get(tzid) def", "standard # time or wall clock time, and are used", "= [] # Next come tzh_timecnt one-byte values of type", "number of # leap seconds to be applied after the", "**kwargs).encode() return inner_func ZERO = datetime.timedelta(0) EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal() class", "not os.path.isfile(self._filename): raise ValueError(\"Unpickable %s class\" % self.__class__.__name__) return (self.__class__,", "comp in self._comps: if not comp.isdst: # Handle the extra", "if dstoffset is not None: self._dst_offset = datetime.timedelta(seconds=dstoffset) elif dstabbr", "self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz = False elif value ==", "__eq__(self, other): return (isinstance(other, tzoffset) and self._offset == other._offset) def", "s.splitlines() if not lines: raise ValueError(\"empty string\") # Unfold i", "if os.path.isfile(name): tz = tzfile(name) else: tz = None else:", "(self.__class__.__name__, repr(self._filename)) def __reduce__(self): if not os.path.isfile(self._filename): raise ValueError(\"Unpickable %s", "self._start_delta = self._delta(res.start) if self._start_delta: self._end_delta = self._delta(res.end, isend=1) def", "# This is std time. self._trans_list[i] += tti.offset laststdoffset =", "TZOFFSETFROM not found\") # Process component rr = None if", "datetime #>>> t = tz.tzlocal() #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()", "+ dt.second) idx = 0 for trans in self._trans_list: if", "== other._trans_idx and self._ttinfo_list == other._ttinfo_list) def __ne__(self, other): return", "zone file # is used in handling POSIX-style time zone", "else: return self._ttinfo_std else: return self._trans_idx[idx-1] def utcoffset(self, dt): if", "name == \"DTSTART\": rrulelines.append(line) founddtstart = True elif name in", "datetime.timedelta(0) EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal() class tzutc(datetime.tzinfo): def utcoffset(self, dt): return", "In each # structure, tt_gmtoff gives the number of #", "= ttinfo[i] # Round to full-minutes if that's not the", "gives the time (as # returned by time(2)) at which", "followed by a one-byte value for tt_isdst # and a", "ValueError(\"empty property name\") name = parms[0].upper() parms = parms[1:] if", "\"EXDATE\"): rrulelines.append(line) elif name == \"TZOFFSETFROM\": if parms: raise ValueError(\"unsupported", "self._trans_idx = tuple(trans_idx) # Set standard, dst, and before ttinfos.", "tzwinlocal = None, None def tzname_in_python2(myfunc): \"\"\"Change unicode output into", "\"tzical\", \"tzwin\", \"tzwinlocal\", \"gettz\"] relativedelta = None parser = None", "not self.__eq__(other) def __repr__(self): return \"%s()\" % self.__class__.__name__ __reduce__ =", "# indicators, each stored as a one-byte value; # they", "We can't use mktime here. It is unstable when deciding", "break else: continue if os.path.isfile(filepath): try: tz = tzfile(filepath) break", "= isdst self.tzname = tzname self.rrule = rrule class _tzicalvtz(datetime.tzinfo):", "found\") if tzoffsetto is None: raise ValueError(\"mandatory TZOFFSETFROM not found\")", "name == \"TZNAME\": if parms: raise ValueError(\"unsupported TZNAME parm: \"+parms[0])", "time. Convert to std. self._trans_list[i] += laststdoffset self._trans_list = tuple(self._trans_list)", "found\") fileobj.read(16) ( # The number of UTC/local indicators stored", "not None: l.append(\"%s=%s\" % (attr, repr(value))) return \"%s(%s)\" % (self.__class__.__name__,", "as standard # time or wall clock time, and are", "hour. See the documentation # of the tzinfo class. delta", "\"+parms[0]) tzid = value elif name in (\"TZURL\", \"LAST-MODIFIED\", \"COMMENT\"):", "attr in self.__slots__: setattr(self, attr, None) def __repr__(self): l =", "if tzwin: try: tz = tzwin(name) except OSError: pass if", "cache=True) comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype == \"DAYLIGHT\"), tzname, rr)", "raise ValueError(\"component not closed: \"+comptype) if not tzid: raise ValueError(\"mandatory", "tzname(self, dt): if not self._ttinfo_std: return None return self._find_ttinfo(dt).abbr def", "ZERO)) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return", "-3. if res.stdabbr in (\"GMT\", \"UTC\"): res.stdoffset *= -1 #", "% self.__class__.__name__) return (self.__class__, (self._filename,)) class tzrange(datetime.tzinfo): def __init__(self, stdabbr,", "with CRLF elif hasattr(fileobj, \"name\"): self._s = fileobj.name else: self._s", "tzid = None comps = [] invtz = False comptype", "\"TZOFFSETTO\": if parms: raise ValueError(\"unsupported TZOFFSETTO parm: \"+parms[0]) tzoffsetto =", "dt): return self._find_comp(dt).tzoffsetto def dst(self, dt): comp = self._find_comp(dt) if", "del lines[i] else: i += 1 tzid = None comps", "_std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: _dst_offset = datetime.timedelta(seconds=-time.altzone) else: _dst_offset", "_isdst(self, dt): if not self._start_delta: return False year = datetime.datetime(dt.year,", "set. Use False in start/end # to avoid building it", "self.__eq__(other) def __repr__(self): return \"%s()\" % self.__class__.__name__ __reduce__ = object.__reduce__", "tm_isdst should be set by localtime(3), and # tt_abbrind serves", "not tz: for c in name: # name must have", "== \"COMMENT\": pass else: raise ValueError(\"unsupported property: \"+name) else: if", "raise ValueError(\"magic not found\") fileobj.read(16) ( # The number of", "stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None): global relativedelta if not relativedelta:", "sure about this. In my tests, the tz source file", "self._ttinfo_before if laststd: while idx > 0: tti = self._trans_idx[idx-1]", "always in gmt time. Let me know if you have", "raise ValueError(\"unsupported property: \"+name) elif name == \"BEGIN\" and value", "ValueError(\"unsupported TZOFFSETTO parm: \"+parms[0]) tzoffsetto = self._parse_offset(value) elif name ==", "= {} if x.month is not None: kwargs[\"month\"] = x.month", "dt): return ZERO @tzname_in_python2 def tzname(self, dt): return \"UTC\" def", "standard byte # order, followed by a one-byte value for", "is std time. self._trans_list[i] += tti.offset laststdoffset = tti.offset else:", "for path in TZPATHS: filepath = os.path.join(path, filename) if os.path.isfile(filepath):", "> i and isgmt[i] != 0) self._ttinfo_list.append(tti) # Replace ttinfo", "def tzname(self, dt): if self._isdst(dt): return self._dst_abbr else: return self._std_abbr", "zone abbreviation characters that follow the # ttinfo structure(s) in", "__eq__(self, other): if not isinstance(other, _ttinfo): return False return (self.offset", "transition time. These values # serve as indices into an", "return \"%s(%s, %s)\" % (self.__class__.__name__, repr(self._name), self._offset.days*86400+self._offset.seconds) __reduce__ = object.__reduce__", "range(typecnt): gmtoff, isdst, abbrind = ttinfo[i] # Round to full-minutes", "not found\") # Process component rr = None if rrulelines:", "#'BRST' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT'", "(gmtoff+30)//60*60 tti = _ttinfo() tti.offset = gmtoff tti.delta = datetime.timedelta(seconds=gmtoff)", "None if self._ttinfo_list: if not self._trans_list: self._ttinfo_std = self._ttinfo_first =", "__init__(self, fileobj): if isinstance(fileobj, string_types): self._filename = fileobj fileobj =", "described in the file is associated # with the same-indexed", "do when a given # time is before the first", "return self._find_ttinfo(dt).delta def dst(self, dt): if not self._ttinfo_dst: return ZERO", "self._ttinfo_list == other._ttinfo_list) def __ne__(self, other): return not self.__eq__(other) def", "self._offset.days*86400+self._offset.seconds) __reduce__ = object.__reduce__ class tzlocal(datetime.tzinfo): _std_offset = datetime.timedelta(seconds=-time.timezone) if", "charcnt, ) = struct.unpack(\">6l\", fileobj.read(24)) # The above header is", "if not os.path.isabs(filepath): filename = filepath for path in TZPATHS:", "fileobj.read(leapcnt*8)) # Then there are tzh_ttisstdcnt standard/wall # indicators, each", "_delta(self, x, isend=0): kwargs = {} if x.month is not", "= year+self._end_delta dt = dt.replace(tzinfo=None) if start < end: return", "time.localtime(timestamp+time.timezone).tm_isdst def __eq__(self, other): if not isinstance(other, tzlocal): return False", "raise ValueError(\"Unpickable %s class\" % self.__class__.__name__) return (self.__class__, (self._filename,)) class", "lines[i-1] += line[1:] del lines[i] else: i += 1 tzid", "parser = None rrule = None try: from dateutil.tzwin import", "#>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' # # Here is", "byte order; the # first value of each pair gives", "\"LAST-MODIFIED\", \"COMMENT\"): pass else: raise ValueError(\"unsupported property: \"+name) elif name", "self._ttinfo_std = self._ttinfo_dst for tti in self._ttinfo_list: if not tti.isdst:", "file. charcnt, ) = struct.unpack(\">6l\", fileobj.read(24)) # The above header", "self._ttinfo_dst and tti.isdst: self._ttinfo_dst = tti if self._ttinfo_std and self._ttinfo_dst:", "x.month if x.weekday is not None: kwargs[\"weekday\"] = relativedelta.weekday(x.weekday, x.week)", "from dateutil import rrule if isinstance(fileobj, string_types): self._s = fileobj", "rr) comps.append(comp) comptype = None else: raise ValueError(\"invalid component end:", "in TZPATHS: filepath = os.path.join(path, name) if not os.path.isfile(filepath): filepath", "fileobj): global rrule if not rrule: from dateutil import rrule", "is setup to wall time, and in the binary file", "says that utcoffset()-dst() must # be constant for every dt.", "repr(self._tzid) __reduce__ = object.__reduce__ class tzical(object): def __init__(self, fileobj): global", "** Everything has been read ** # Build ttinfo list", "0, -1)) # return time.localtime(timestamp).tm_isdst # # The code above", "me know if you have comments # about this. laststdoffset", "parser self._s = s res = parser._parsetz(s) if res is", "in wall time. OTOH, it's # always in gmt time.", "is None: self._start_delta = relativedelta.relativedelta( hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) else:", "= dstabbr if stdoffset is not None: self._std_offset = datetime.timedelta(seconds=stdoffset)", "total number of # leap seconds to be applied after", "= None try: from dateutil.tzwin import tzwin, tzwinlocal except (ImportError,", "when a given # time is before the first onset", "if leapcnt: leap = struct.unpack(\">%dl\" % (leapcnt*2), fileobj.read(leapcnt*8)) # Then", "== other.offset and self.delta == other.delta and self.isdst == other.isdst", "= +1 if len(s) == 4: return (int(s[:2])*3600+int(s[2:])*60)*signal elif len(s)", "strings\" stored in the file. charcnt, ) = struct.unpack(\">6l\", fileobj.read(24))", "dt): return ZERO @tzname_in_python2 def tzname(self, dt): return self._name def", "file # is setup to wall time, and in the", "\"TZNAME\": if parms: raise ValueError(\"unsupported TZNAME parm: \"+parms[0]) tzname =", "kwargs[\"month\"] = 10 kwargs[\"day\"] = 31 kwargs[\"weekday\"] = relativedelta.SU(-1) if", "len(self._cachedate) > 10: self._cachedate.pop() self._cachecomp.pop() return lastcomp def utcoffset(self, dt):", ">= start and dt < end else: return dt >=", "file. ttinfo = [] for i in range(typecnt): ttinfo.append(struct.unpack(\">lbb\", fileobj.read(6)))", "= 1 kwargs[\"weekday\"] = relativedelta.SU(+1) else: kwargs[\"month\"] = 10 kwargs[\"day\"]", "else: raise ValueError(\"unknown component: \"+value) comptype = value founddtstart =", "characters that follow the # ttinfo structure(s) in the file.", "of \"transition times\" for which data # is stored in", "== other._dst_offset and self._start_delta == other._start_delta and self._end_delta == other._end_delta)", "= list(self._vtz.keys()) if len(keys) == 0: raise ValueError(\"no timezones defined\")", "first, since _delta() needs # _std_offset and _dst_offset set. Use", "try: tz = tzstr(name) except ValueError: pass break else: if", "envi- # ronment variables. if ttisgmtcnt: isgmt = struct.unpack(\">%db\" %", ">= start or dt < end def __eq__(self, other): if", "except KeyError: pass if name is None or name ==", "dt): # We can't use mktime here. It is unstable", "string format\") # Here we break the compatibility with the", "self.tzoffsetto-self.tzoffsetfrom self.isdst = isdst self.tzname = tzname self.rrule = rrule", "object.__reduce__ class tzoffset(datetime.tzinfo): def __init__(self, name, offset): self._name = name", "byte order (the high-order byte # of the value is", "= compdt lastcomp = comp if not lastcomp: # RFC", "self._ttinfo_first = self._ttinfo_list[0] else: for i in range(timecnt-1, -1, -1):", "in name: # name must have at least one offset", "return self._ttinfo_std else: return self._trans_idx[idx-1] def utcoffset(self, dt): if not", "return bytes, but was changed to unicode strings \"\"\" def", "+ dt.minute * 60 + dt.second) return time.localtime(timestamp+time.timezone).tm_isdst def __eq__(self,", "self._std_offset = datetime.timedelta(seconds=stdoffset) else: self._std_offset = ZERO if dstoffset is", "if sys.platform != \"win32\": TZFILES = [\"/etc/localtime\", \"localtime\"] TZPATHS =", "def __init__(self): for attr in self.__slots__: setattr(self, attr, None) def", "TZFILES: if not os.path.isabs(filepath): filename = filepath for path in", "filepath.replace(' ', '_') if not os.path.isfile(filepath): continue try: tz =", "fileobj.read(4).decode() != \"TZif\": raise ValueError(\"magic not found\") fileobj.read(16) ( #", "the total number of # leap seconds to be applied", "building it two times. tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset, start=False,", "elif x.day: kwargs[\"day\"] = x.day elif x.yday is not None:", "# serve as indices into an array of ttinfo structures", "module. \"\"\" import datetime import os import struct import sys", "ronment variables. if ttisgmtcnt: isgmt = struct.unpack(\">%db\" % ttisgmtcnt, fileobj.read(ttisgmtcnt))", "__ne__(self, other): return not self.__eq__(other) def __getstate__(self): state = {}", "lastcomp = comp if not lastcomp: # RFC says nothing", "value for tt_abbrind. In each # structure, tt_gmtoff gives the", "name, offset): self._name = name self._offset = datetime.timedelta(seconds=offset) def utcoffset(self,", "isinstance(fileobj, string_types): self._filename = fileobj fileobj = open(fileobj, 'rb') elif", "is written as a four-byte value # for tt_gmtoff of", "= 31 elif x.day: kwargs[\"day\"] = x.day elif x.yday is", "standard/wall # indicators, each stored as a one-byte value; #", "< trans: break idx += 1 else: return self._ttinfo_std if", "least one offset to be a tzstr if c in", "These values # serve as indices into an array of", "**kwargs) else: return myfunc(*args, **kwargs).encode() return inner_func ZERO = datetime.timedelta(0)", "variables. if ttisstdcnt: isstd = struct.unpack(\">%db\" % ttisstdcnt, fileobj.read(ttisstdcnt)) #", "def __getstate__(self): state = {} for name in self.__slots__: state[name]", "value # for tt_gmtoff of type long, in a standard", "stores historical changes in the # dst offset, so I", "= [] tzname = None elif name == \"END\": if", "x.weekday is not None: kwargs[\"weekday\"] = relativedelta.weekday(x.weekday, x.week) if x.week", "parm: \"+parms[0]) tzid = value elif name in (\"TZURL\", \"LAST-MODIFIED\",", "> i and isstd[i] != 0) tti.isgmt = (ttisgmtcnt >", "in TZFILES: if not os.path.isabs(filepath): filename = filepath for path", "def tzname(self, dt): return \"UTC\" def __eq__(self, other): return (isinstance(other,", "struct.unpack(\">%db\" % ttisstdcnt, fileobj.read(ttisstdcnt)) # Finally, there are tzh_ttisgmtcnt UTC/local", "pair gives the time (as # returned by time(2)) at", "self._parse_rfc(fileobj.read()) def keys(self): return list(self._vtz.keys()) def get(self, tzid=None): if tzid", "(\"STANDARD\", \"DAYLIGHT\"): # Process component pass else: raise ValueError(\"unknown component:", "invtz: if name == \"BEGIN\": if value in (\"STANDARD\", \"DAYLIGHT\"):", "__init__(self, tzid, comps=[]): self._tzid = tzid self._comps = comps self._cachedate", "stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None): global relativedelta if not", "= parser._parsetz(s) if res is None: raise ValueError(\"unknown string format\")", "\"+parms[0]) tzname = value elif name == \"COMMENT\": pass else:", "extensions to the standard Python datetime module. \"\"\" import datetime", "repr(self._filename)) def __reduce__(self): if not os.path.isfile(self._filename): raise ValueError(\"Unpickable %s class\"", "= parms[0].upper() parms = parms[1:] if invtz: if name ==", "tzh_ttisstdcnt standard/wall # indicators, each stored as a one-byte value;", "DTSTART not found\") if tzoffsetfrom is None: raise ValueError(\"mandatory TZOFFSETFROM", "used as a transition time (as returned by # time(2))", "start = year+self._start_delta end = year+self._end_delta dt = dt.replace(tzinfo=None) if", "I belive that this wouldn't be the right # way", "if all of them are dst. self._ttinfo_std = None self._ttinfo_dst", "\"%s(%s)\" % (self.__class__.__name__, \", \".join(l)) def __eq__(self, other): if not", "data is # stored in the file. leapcnt, # The", "dstabbr if stdoffset is not None: self._std_offset = datetime.timedelta(seconds=stdoffset) else:", "not None: kwargs[\"seconds\"] = x.time else: # Default is 2AM.", "tzfile(datetime.tzinfo): # http://www.twinsun.com/tz/tz-link.htm # ftp://ftp.iana.org/tz/tz*.tar.gz def __init__(self, fileobj): if isinstance(fileobj,", "are tzh_ttisstdcnt standard/wall # indicators, each stored as a one-byte", "types of # ``local time'' types described in the file", "if name == \"BEGIN\": if value in (\"STANDARD\", \"DAYLIGHT\"): #", "dt): return self._find_comp(dt).tzname def __repr__(self): return \"<tzicalvtz %s>\" % repr(self._tzid)", "else: return ZERO @tzname_in_python2 def tzname(self, dt): if self._isdst(dt): return", "the rules for computing local time # change. if timecnt:", "return ZERO tti = self._find_ttinfo(dt) if not tti.isdst: return ZERO", "__license__ = \"Simplified BSD\" __all__ = [\"tzutc\", \"tzoffset\", \"tzlocal\", \"tzfile\",", "in self.__slots__: state[name] = getattr(self, name, None) return state def", "elif name == \"TZOFFSETFROM\": if parms: raise ValueError(\"unsupported %s parm:", "tzname(self, dt): return time.tzname[self._isdst(dt)] def _isdst(self, dt): # We can't", "idx = 0 for trans in self._trans_list: if timestamp <", "file. ttisgmtcnt, # The number of standard/wall indicators stored in", "if timestamp < trans: break idx += 1 else: return", "for that would be: # # return self._ttinfo_dst.offset-self._ttinfo_std.offset # #", "elif comptype: if name == \"DTSTART\": rrulelines.append(line) founddtstart = True", "abbrind = ttinfo[i] # Round to full-minutes if that's not", "== other.isgmt) def __ne__(self, other): return not self.__eq__(other) def __getstate__(self):", "== other._dst_abbr and self._std_offset == other._std_offset and self._dst_offset == other._dst_offset", "written in standard byte order; the # first value of", "s): s = s.strip() if not s: raise ValueError(\"empty offset\")", "kwargs[\"nlyearday\"] = x.jyday if not kwargs: # Default is to", "is # stored in the file. leapcnt, # The number", "and tti.isdst: self._ttinfo_dst = tti if self._ttinfo_std and self._ttinfo_dst: break", "== comptype: if not founddtstart: raise ValueError(\"mandatory DTSTART not found\")", "return self._name def __eq__(self, other): return (isinstance(other, tzoffset) and self._offset", "start on first sunday of april, and end # on", "+= line[1:] del lines[i] else: i += 1 tzid =", "component pass else: raise ValueError(\"unknown component: \"+value) comptype = value", "== \"VTIMEZONE\": if comptype: raise ValueError(\"component not closed: \"+comptype) if", "%s class\" % self.__class__.__name__) return (self.__class__, (self._filename,)) class tzrange(datetime.tzinfo): def", "in the file. leapcnt, # The number of \"transition times\"", "Round to full-minutes if that's not the case. Python's #", "lastcompdt = None for comp in self._comps: if not comp.isdst:", "one tells which of the different types of # ``local", "will be set to the first non-dst ttinfo, or to", "which data is # stored in the file. leapcnt, #", "Next come tzh_timecnt one-byte values of type unsigned # char;", "encoded in UTF-8 with CRLF elif hasattr(fileobj, \"name\"): self._s =", "tz = tzutc() elif name in time.tzname: tz = tzlocal()", "!= 0) self._ttinfo_list.append(tti) # Replace ttinfo indexes for ttinfo objects.", "res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset, start=False, end=False) if not res.dstabbr: self._start_delta", "== \"DAYLIGHT\"), tzname, rr) comps.append(comp) comptype = None else: raise", "Python datetime module. \"\"\" import datetime import os import struct", "None if rrulelines: rr = rrule.rrulestr(\"\\n\".join(rrulelines), compatible=True, ignoretz=True, cache=True) comp", "found\") if not comps: raise ValueError(\"at least one component is", "# ronment variables. if ttisgmtcnt: isgmt = struct.unpack(\">%db\" % ttisgmtcnt,", "# ftp://ftp.iana.org/tz/tz*.tar.gz def __init__(self, fileobj): if isinstance(fileobj, string_types): self._filename =", "month=4, day=1, weekday=relativedelta.SU(+1)) else: self._start_delta = start if dstabbr and", "def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._s)) if sys.platform !=", "order # by time. # Not used, for now if", "time. # Not used, for now if leapcnt: leap =", "= list(self._trans_list) for i in range(len(self._trans_list)): tti = self._trans_idx[i] if", "used, for now if leapcnt: leap = struct.unpack(\">%dl\" % (leapcnt*2),", "else: self._dst_offset = ZERO if dstabbr and start is None:", "lastcomp def utcoffset(self, dt): return self._find_comp(dt).tzoffsetto def dst(self, dt): comp", "founddtstart: raise ValueError(\"mandatory DTSTART not found\") if tzoffsetfrom is None:", "bytestrings in Python 2 tzname() API changed in Python 3.", "data # is stored in the file. timecnt, # The", "(self.__class__, (self._filename,)) class tzrange(datetime.tzinfo): def __init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None,", "TZ variable handling. # GMT-3 actually *means* the timezone -3.", "follow the # ttinfo structure(s) in the file. ttinfo =", "return (self.offset == other.offset and self.delta == other.delta and self.isdst", "else: return self._std_offset def dst(self, dt): if self._isdst(dt): return self._dst_offset-self._std_offset", "ttinfo structures that # appears next in the file. if", "dt.replace(tzinfo=None) try: return self._cachecomp[self._cachedate.index(dt)] except ValueError: pass lastcomp = None", "fileobj.read(timecnt)) else: self._trans_idx = [] # Each ttinfo structure is", "datetime doesn't accept sub-minute timezones. Check # http://python.org/sf/1447945 for some", "== ZERO)) def __ne__(self, other): return not self.__eq__(other) def __repr__(self):", "self.isstd == other.isstd and self.isgmt == other.isgmt) def __ne__(self, other):", "= None for line in lines: if not line: continue", "and # tt_abbrind serves as an index into the array", "actually *means* the timezone -3. if res.stdabbr in (\"GMT\", \"UTC\"):", "tzid = None comps = [] invtz = True def", "== 0: return self._ttinfo_before if laststd: while idx > 0:", "and self.isstd == other.isstd and self.isgmt == other.isgmt) def __ne__(self,", "0 for trans in self._trans_list: if timestamp < trans: break", "fileobj.read(16) ( # The number of UTC/local indicators stored in", "= repr(fileobj) self._vtz = {} self._parse_rfc(fileobj.read()) def keys(self): return list(self._vtz.keys())", "= None self._ttinfo_dst = None self._ttinfo_before = None if self._ttinfo_list:", "return tti.delta-self._find_ttinfo(dt, laststd=1).delta # An alternative for that would be:", "(-1, +1)[s[0]=='+'] s = s[1:] else: signal = +1 if", "= tuple(trans_idx) # Set standard, dst, and before ttinfos. before", "for tt_gmtoff of type long, in a standard byte #", "self._ttinfo_dst: return ZERO tti = self._find_ttinfo(dt) if not tti.isdst: return", "not comp.isdst: # Handle the extra hour in DST ->", "component, or the first component, if # none is found.", "tells which of the different types of # ``local time''", "used in handling POSIX-style time zone envi- # ronment variables.", "= [] def _find_comp(self, dt): if len(self._comps) == 1: return", "1 else: return self._ttinfo_std else: return self._trans_idx[idx-1] def utcoffset(self, dt):", "and are used when a time zone file # is", "__ne__(self, other): return not self.__eq__(other) def __repr__(self): return \"%s(%s, %s)\"", "t = tz.tzlocal() #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST' #>>>", "time types were specified as standard # time or wall", "and isstd[i] != 0) tti.isgmt = (ttisgmtcnt > i and", "= 0 self._trans_list = list(self._trans_list) for i in range(len(self._trans_list)): tti", "*= -1 # We must initialize it first, since _delta()", "to be added to UTC, tt_isdst tells whether # tm_isdst", "{} if x.month is not None: kwargs[\"month\"] = x.month if", "4 kwargs[\"day\"] = 1 kwargs[\"weekday\"] = relativedelta.SU(+1) else: kwargs[\"month\"] =", "invtz = True def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._s))", "ttisgmtcnt, # The number of standard/wall indicators stored in the", "[] for attr in self.__slots__: value = getattr(self, attr) if", "ttinfo structure is written as a four-byte value # for", "isend=1) def _delta(self, x, isend=0): kwargs = {} if x.month", "(int(s[:2])*3600+int(s[2:])*60)*signal elif len(s) == 6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: raise ValueError(\"invalid", "and # isgmt are off, so it should be in", "ValueError: pass break else: if name in (\"GMT\", \"UTC\"): tz", "False year = datetime.datetime(dt.year, 1, 1) start = year+self._start_delta end", "tti.isdst: self._ttinfo_std = tti elif not self._ttinfo_dst and tti.isdst: self._ttinfo_dst", "return not self.__eq__(other) def __repr__(self): return \"%s(...)\" % self.__class__.__name__ __reduce__", "yields the following result: # #>>> import tz, datetime #>>>", "the file. ttinfo = [] for i in range(typecnt): ttinfo.append(struct.unpack(\">lbb\",", "to full-minutes if that's not the case. Python's # datetime", "handling POSIX-style # time zone environment variables. if ttisstdcnt: isstd", "self._end_delta = self._delta(res.end, isend=1) def _delta(self, x, isend=0): kwargs =", "name: try: name = os.environ[\"TZ\"] except KeyError: pass if name", "self._ttinfo_dst and not self._ttinfo_std: self._ttinfo_std = self._ttinfo_dst for tti in", "must have at least one offset to be a tzstr", "\"\"\" import datetime import os import struct import sys import", "if not comp.isdst: lastcomp = comp break else: lastcomp =", "parms = parms[1:] if invtz: if name == \"BEGIN\": if", "file. leapcnt, # The number of \"transition times\" for which", "Convert to std. self._trans_list[i] += laststdoffset self._trans_list = tuple(self._trans_list) def", "parm: \"+parms[0]) tzname = value elif name == \"COMMENT\": pass", "fileobj fileobj = open(fileobj, 'r') # ical should be encoded", "state[name]) class tzfile(datetime.tzinfo): # http://www.twinsun.com/tz/tz-link.htm # ftp://ftp.iana.org/tz/tz*.tar.gz def __init__(self, fileobj):", "# time is before the first onset date. We'll look", "len(s) == 6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: raise ValueError(\"invalid offset: \"+s)", "# time zone abbreviation characters that follow the # ttinfo", "self._find_comp(dt).tzoffsetto def dst(self, dt): comp = self._find_comp(dt) if comp.isdst: return", "< end: return dt >= start and dt < end", "types were specified as standard # time or wall clock", "not relativedelta: from dateutil import relativedelta self._std_abbr = stdabbr self._dst_abbr", "type long, sorted in ascending order. # These values are", "# change. if timecnt: self._trans_list = struct.unpack(\">%dl\" % timecnt, fileobj.read(timecnt*4))", "to wall time. # # I'm not sure about this.", "= s[1:] else: signal = +1 if len(s) == 4:", "self._std_abbr = stdabbr self._dst_abbr = dstabbr if stdoffset is not", "isend=0): kwargs = {} if x.month is not None: kwargs[\"month\"]", "before any transitions, # and will be set to the", "types\" for which data # is stored in the file", "2003-2007 <NAME> <<EMAIL>> This module offers extensions to the standard", "False tzoffsetfrom = None tzoffsetto = None rrulelines = []", "and self._start_delta == other._start_delta and self._end_delta == other._end_delta) def __ne__(self,", "a given time is before any transitions, # and will", "name = parms[0].upper() parms = parms[1:] if invtz: if name", "ttinfos. before will be # used when a given time", "__init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None): global relativedelta if", "self._filename = repr(fileobj) # From tzfile(5): # # The time", "file. if timecnt: self._trans_idx = struct.unpack(\">%dB\" % timecnt, fileobj.read(timecnt)) else:", "and self._trans_idx == other._trans_idx and self._ttinfo_list == other._ttinfo_list) def __ne__(self,", "def __eq__(self, other): if not isinstance(other, _ttinfo): return False return", "this. laststdoffset = 0 self._trans_list = list(self._trans_list) for i in", "datetime.timedelta(seconds=gmtoff) tti.isdst = isdst tti.abbr = abbr[abbrind:abbr.find('\\x00', abbrind)] tti.isstd =", "False in start/end # to avoid building it two times.", "#>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #", "become relative to wall time. # # I'm not sure", "the # dst offset, so I belive that this wouldn't", "is None: keys = list(self._vtz.keys()) if len(keys) == 0: raise", "86400 + dt.hour * 3600 + dt.minute * 60 +", "there are tzh_ttisgmtcnt UTC/local # indicators, each stored as a", "offset: \"+s) def _parse_rfc(self, s): lines = s.splitlines() if not", "= _std_offset def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset else:", "as indices into an array of ttinfo structures that #", "given time is before any transitions, # and will be", "associated # with the same-indexed transition time. These values #", "# and will be set to the first non-dst ttinfo,", "See the documentation # of the tzinfo class. delta =", "closed: \"+comptype) if not tzid: raise ValueError(\"mandatory TZID not found\")", "tzid = keys[0] return self._vtz.get(tzid) def _parse_offset(self, s): s =", "wall time, and in the binary file isstd and #", "\"VTIMEZONE\": tzid = None comps = [] invtz = True", "can't use mktime here. It is unstable when deciding if", "= tti if self._ttinfo_std and self._ttinfo_dst: break else: if self._ttinfo_dst", "= os.environ[\"TZ\"] except KeyError: pass if name is None or", "TZOFFSETTO parm: \"+parms[0]) tzoffsetto = self._parse_offset(value) elif name == \"TZNAME\":", "True elif name in (\"RRULE\", \"RDATE\", \"EXRULE\", \"EXDATE\"): rrulelines.append(line) elif", "= gmtoff tti.delta = datetime.timedelta(seconds=gmtoff) tti.isdst = isdst tti.abbr =", "!= 0) tti.isgmt = (ttisgmtcnt > i and isgmt[i] !=", "break except (IOError, OSError, ValueError): pass else: tz = None", "leap = struct.unpack(\">%dl\" % (leapcnt*2), fileobj.read(leapcnt*8)) # Then there are", "end = year+self._end_delta dt = dt.replace(tzinfo=None) if start < end:", "isinstance(other, tzrange): return False return (self._std_abbr == other._std_abbr and self._dst_abbr", "@tzname_in_python2 def tzname(self, dt): return \"UTC\" def __eq__(self, other): return", "The number of \"transition times\" for which data # is", "dst(self, dt): return ZERO @tzname_in_python2 def tzname(self, dt): return self._name", "# Replace ttinfo indexes for ttinfo objects. trans_idx = []", "ZERO if dstoffset is not None: self._dst_offset = datetime.timedelta(seconds=dstoffset) elif", "> 0: tti = self._trans_idx[idx-1] if not tti.isdst: return tti", "variable handling. # GMT-3 actually *means* the timezone -3. if", "time. # The pairs of values are sorted in ascending", "module offers extensions to the standard Python datetime module. \"\"\"", "(\"GMT\", \"UTC\"): tz = tzutc() elif name in time.tzname: tz", "self._ttinfo_dst = tti if self._ttinfo_std and self._ttinfo_dst: break else: if", "_ttinfo(object): __slots__ = [\"offset\", \"delta\", \"isdst\", \"abbr\", \"isstd\", \"isgmt\"] def", "def utcoffset(self, dt): return self._offset def dst(self, dt): return ZERO", "in the file. charcnt, ) = struct.unpack(\">6l\", fileobj.read(24)) # The", "# values of type long, sorted in ascending order. #", "(ttisgmtcnt > i and isgmt[i] != 0) self._ttinfo_list.append(tti) # Replace", "six four-byte values of type long, written in a #", "(\"GMT\", \"UTC\"): res.stdoffset *= -1 # We must initialize it", "trans in self._trans_list: if timestamp < trans: break idx +=", "kwargs[\"day\"] = 31 kwargs[\"weekday\"] = relativedelta.SU(-1) if x.time is not", "filepath for path in TZPATHS: filepath = os.path.join(path, filename) if", "= 1 else: kwargs[\"day\"] = 31 elif x.day: kwargs[\"day\"] =", "characters \"TZif\" to identify # them as time zone information", "unstable when deciding if # the hour near to a", "= None comps = [] invtz = True def __repr__(self):", "i in range(typecnt): ttinfo.append(struct.unpack(\">lbb\", fileobj.read(6))) abbr = fileobj.read(charcnt).decode() # Then", "self._end_delta = relativedelta.relativedelta( hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) else: self._end_delta =", "% self.__class__.__name__ __reduce__ = object.__reduce__ class _ttinfo(object): __slots__ = [\"offset\",", "read ** # Build ttinfo list self._ttinfo_list = [] for", "on first sunday of april, and end # on last", "comp.rrule.before(dt, inc=True) if compdt and (not lastcompdt or lastcompdt <", "and line[0] == \" \": lines[i-1] += line[1:] del lines[i]", "self._vtz = {} self._parse_rfc(fileobj.read()) def keys(self): return list(self._vtz.keys()) def get(self,", "= False elif value == comptype: if not founddtstart: raise", "tzoffset) and self._offset == other._offset) def __ne__(self, other): return not", "off, so it should be in wall time. OTOH, it's", "This is std time. self._trans_list[i] += tti.offset laststdoffset = tti.offset", "rrule = None try: from dateutil.tzwin import tzwin, tzwinlocal except", "name, None) return state def __setstate__(self, state): for name in", "self._ttinfo_dst.offset-self._ttinfo_std.offset # # However, this class stores historical changes in", "dt): return self._name def __eq__(self, other): return (isinstance(other, tzoffset) and", "*means* the timezone -3. if res.stdabbr in (\"GMT\", \"UTC\"): res.stdoffset", "not tzid: raise ValueError(\"mandatory TZID not found\") if not comps:", "tz = tzwin(name) except OSError: pass if not tz: from", "[\"/usr/share/zoneinfo\", \"/usr/lib/zoneinfo\", \"/etc/zoneinfo\"] else: TZFILES = [] TZPATHS = []", "dateutil.zoneinfo import gettz tz = gettz(name) if not tz: for", "ZERO # The documentation says that utcoffset()-dst() must # be", "the following result: # #>>> import tz, datetime #>>> t", "= value founddtstart = False tzoffsetfrom = None tzoffsetto =", "setup to wall time, and in the binary file isstd", "res.dstoffset, start=False, end=False) if not res.dstabbr: self._start_delta = None self._end_delta", "self._s = fileobj fileobj = open(fileobj, 'r') # ical should", "state: setattr(self, name, state[name]) class tzfile(datetime.tzinfo): # http://www.twinsun.com/tz/tz-link.htm # ftp://ftp.iana.org/tz/tz*.tar.gz", "timecnt, fileobj.read(timecnt*4)) else: self._trans_list = [] # Next come tzh_timecnt", "None parser = None rrule = None try: from dateutil.tzwin", "first dst, if all of them are dst. self._ttinfo_std =", "== other._dst_offset) return True def __ne__(self, other): return not self.__eq__(other)", "OSError, ValueError): pass else: tz = tzlocal() else: if name.startswith(\":\"):", "class tzoffset(datetime.tzinfo): def __init__(self, name, offset): self._name = name self._offset", "dt): if self._isdst(dt): return self._dst_abbr else: return self._std_abbr def _isdst(self,", "and self.isgmt == other.isgmt) def __ne__(self, other): return not self.__eq__(other)", "unsigned # char; each one tells which of the different", "tz = tzfile(filepath) break except (IOError, OSError, ValueError): pass else:", "dt.hour, # dt.minute, dt.second, dt.weekday(), 0, -1)) # return time.localtime(timestamp).tm_isdst", "= None rrule = None try: from dateutil.tzwin import tzwin,", "wall time. # # I'm not sure about this. In", "dt.second, dt.weekday(), 0, -1)) # return time.localtime(timestamp).tm_isdst # # The", "TZFILES = [] TZPATHS = [] def gettz(name=None): tz =", "= [] self._cachecomp = [] def _find_comp(self, dt): if len(self._comps)", "offset, so I belive that this wouldn't be the right", "== \"VTIMEZONE\": tzid = None comps = [] invtz =", "self._isdst(dt): return self._dst_offset else: return self._std_offset def dst(self, dt): if", "l.append(\"%s=%s\" % (attr, repr(value))) return \"%s(%s)\" % (self.__class__.__name__, \", \".join(l))", "to be applied after the given time. # The pairs", "# occurs; the second gives the total number of #", "or to # the first dst, if all of them", "= tzutc() elif name in time.tzname: tz = tzlocal() return", "compatible=True, ignoretz=True, cache=True) comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype == \"DAYLIGHT\"),", "The code above yields the following result: # #>>> import", "of type long, written in a # ``standard'' byte order", "ical should be encoded in UTF-8 with CRLF elif hasattr(fileobj,", "[] tzname = None elif name == \"END\": if value", "and value == \"VTIMEZONE\": tzid = None comps = []", "them as time zone information files, followed by # sixteen", "(self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr and self._std_offset ==", "of working with the extra hour. See the documentation #", "= False comptype = None for line in lines: if", "= (gmtoff+30)//60*60 tti = _ttinfo() tti.offset = gmtoff tti.delta =", "= None comps = [] invtz = False comptype =", "raise ValueError(\"invalid offset: \"+s) def _parse_rfc(self, s): lines = s.splitlines()", "my tests, the tz source file # is setup to", "@tzname_in_python2 def tzname(self, dt): return time.tzname[self._isdst(dt)] def _isdst(self, dt): #", "elif x.yday is not None: kwargs[\"yearday\"] = x.yday elif x.jyday", "if time.daylight: _dst_offset = datetime.timedelta(seconds=-time.altzone) else: _dst_offset = _std_offset def", "which data # is stored in the file. timecnt, #", "wall time. OTOH, it's # always in gmt time. Let", "dt = dt.replace(tzinfo=None) try: return self._cachecomp[self._cachedate.index(dt)] except ValueError: pass lastcomp", "in (\"STANDARD\", \"DAYLIGHT\"): # Process component pass else: raise ValueError(\"unknown", "if rrulelines: rr = rrule.rrulestr(\"\\n\".join(rrulelines), compatible=True, ignoretz=True, cache=True) comp =", "last sunday of october. if not isend: kwargs[\"month\"] = 4", "raise ValueError(\"empty property name\") name = parms[0].upper() parms = parms[1:]", "getattr(self, attr) if value is not None: l.append(\"%s=%s\" % (attr,", "= None else: for path in TZPATHS: filepath = os.path.join(path,", "as a four-byte value # for tt_gmtoff of type long,", "# Process component rr = None if rrulelines: rr =", "by # sixteen bytes reserved for future use, followed by", "founddtstart = False tzoffsetfrom = None tzoffsetto = None rrulelines", "kwargs[\"day\"] = 31 elif x.day: kwargs[\"day\"] = x.day elif x.yday", "dt < end else: return dt >= start or dt", "ValueError): pass else: tz = None if tzwin: try: tz", "#>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' # # Here is a more stable", "for name in self.__slots__: if name in state: setattr(self, name,", "std time. self._trans_list[i] += tti.offset laststdoffset = tti.offset else: #", "object.__reduce__ class tzlocal(datetime.tzinfo): _std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: _dst_offset =", "return False return (self._std_offset == other._std_offset and self._dst_offset == other._dst_offset)", "tti.isstd = (ttisstdcnt > i and isstd[i] != 0) tti.isgmt", "component is needed\") # Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps)", "elif name == \"TZNAME\": if parms: raise ValueError(\"unsupported TZNAME parm:", "is not None: self._std_offset = datetime.timedelta(seconds=stdoffset) else: self._std_offset = ZERO", "self._cachecomp.pop() return lastcomp def utcoffset(self, dt): return self._find_comp(dt).tzoffsetto def dst(self,", "type long, written in a # ``standard'' byte order (the", "tz: for c in name: # name must have at", "idx in self._trans_idx: trans_idx.append(self._ttinfo_list[idx]) self._trans_idx = tuple(trans_idx) # Set standard,", "self._dst_offset == other._dst_offset) return True def __ne__(self, other): return not", "elif not self._ttinfo_dst and tti.isdst: self._ttinfo_dst = tti if self._ttinfo_std", "self._ttinfo_before = self._ttinfo_list[0] # Now fix transition times to become", "indicators stored in the file. ttisgmtcnt, # The number of", "# These values are written in ``standard'' byte order. #", "an array of ttinfo structures that # appears next in", "year+self._start_delta end = year+self._end_delta dt = dt.replace(tzinfo=None) if start <", "a transition time (as returned by # time(2)) at which", "dst(self, dt): if not self._ttinfo_dst: return ZERO tti = self._find_ttinfo(dt)", "if self._isdst(dt): return self._dst_offset-self._std_offset else: return ZERO @tzname_in_python2 def tzname(self,", "you have comments # about this. laststdoffset = 0 self._trans_list", "try: tz = tzwin(name) except OSError: pass if not tz:", "= 0 for trans in self._trans_list: if timestamp < trans:", "(\"TZURL\", \"LAST-MODIFIED\", \"COMMENT\"): pass else: raise ValueError(\"unsupported property: \"+name) elif", "if os.path.isfile(filepath): try: tz = tzfile(filepath) break except (IOError, OSError,", "return ZERO @tzname_in_python2 def tzname(self, dt): return self._find_comp(dt).tzname def __repr__(self):", "or # local time, and are used when a time", "day=1, weekday=relativedelta.SU(+1)) else: self._start_delta = start if dstabbr and end", "= name[:-1] if os.path.isabs(name): if os.path.isfile(name): tz = tzfile(name) else:", "code above yields the following result: # #>>> import tz,", "else: self._trans_list = [] # Next come tzh_timecnt one-byte values", "Here is a more stable implementation: # timestamp = ((dt.toordinal()", "-1, -1): tti = self._trans_idx[i] if not self._ttinfo_std and not", "from dateutil.tzwin import tzwin, tzwinlocal except (ImportError, OSError): tzwin, tzwinlocal", "sys import time from mo_future import PY3, string_types __license__ =", "tzwinlocal except (ImportError, OSError): tzwin, tzwinlocal = None, None def", "idx == 0: return self._ttinfo_before if laststd: while idx >", "set to the first non-dst ttinfo, or to # the", "% self.__class__.__name__ __reduce__ = object.__reduce__ class tzstr(tzrange): def __init__(self, s):", "= [] for idx in self._trans_idx: trans_idx.append(self._ttinfo_list[idx]) self._trans_idx = tuple(trans_idx)", "dt): if not self._ttinfo_std: return ZERO return self._find_ttinfo(dt).delta def dst(self,", "import struct import sys import time from mo_future import PY3,", "return self._find_comp(dt).tzname def __repr__(self): return \"<tzicalvtz %s>\" % repr(self._tzid) __reduce__", "== \"END\": if value == \"VTIMEZONE\": if comptype: raise ValueError(\"component", "# ** Everything has been read ** # Build ttinfo", "by tzset(3) # begin with the magic characters \"TZif\" to", "def __init__(self, name, offset): self._name = name self._offset = datetime.timedelta(seconds=offset)", "return False return (self._trans_list == other._trans_list and self._trans_idx == other._trans_idx", "__eq__(self, other): if not isinstance(other, tzlocal): return False return (self._std_offset", "not None: self._dst_offset = datetime.timedelta(seconds=dstoffset) elif dstabbr and stdoffset is", "\"RDATE\", \"EXRULE\", \"EXDATE\"): rrulelines.append(line) elif name == \"TZOFFSETFROM\": if parms:", "tzstr if c in \"0123456789\": try: tz = tzstr(name) except", "def __ne__(self, other): return not self.__eq__(other) def __getstate__(self): state =", "lastcomp = comp break else: lastcomp = comp[0] self._cachedate.insert(0, dt)", "when a given time is before any transitions, # and", "not comps: raise ValueError(\"at least one component is needed\") #", "keys[0] return self._vtz.get(tzid) def _parse_offset(self, s): s = s.strip() if", "== \"BEGIN\": if value in (\"STANDARD\", \"DAYLIGHT\"): # Process component", "TZOFFSETFROM not found\") if tzoffsetto is None: raise ValueError(\"mandatory TZOFFSETFROM", "== other._std_offset and self._dst_offset == other._dst_offset) return True def __ne__(self,", "import os import struct import sys import time from mo_future", "# to avoid building it two times. tzrange.__init__(self, res.stdabbr, res.stdoffset,", "# local time, and are used when a time zone", "# ttinfo structure(s) in the file. ttinfo = [] for", "else: self._start_delta = start if dstabbr and end is None:", "the # ttinfo structure(s) in the file. ttinfo = []", "stored in the file. charcnt, ) = struct.unpack(\">6l\", fileobj.read(24)) #", "self._end_delta = None else: self._start_delta = self._delta(res.start) if self._start_delta: self._end_delta", "start=False, end=False) if not res.dstabbr: self._start_delta = None self._end_delta =", "deciding if # the hour near to a change is", "__repr__(self): return \"%s()\" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzoffset(datetime.tzinfo):", "for i in range(len(self._trans_list)): tti = self._trans_idx[i] if not tti.isdst:", "tti if self._ttinfo_std and self._ttinfo_dst: break else: if self._ttinfo_dst and", "if not comp.isdst: # Handle the extra hour in DST", "= False tzoffsetfrom = None tzoffsetto = None rrulelines =", "ValueError(\"unsupported property: \"+name) else: if name == \"TZID\": if parms:", "datetime.timedelta(seconds=stdoffset) else: self._std_offset = ZERO if dstoffset is not None:", "identify # them as time zone information files, followed by", "self._dst_abbr = dstabbr if stdoffset is not None: self._std_offset =", "# We can't use mktime here. It is unstable when", "self._trans_list = list(self._trans_list) for i in range(len(self._trans_list)): tti = self._trans_idx[i]", "filename) if os.path.isfile(filepath): break else: continue if os.path.isfile(filepath): try: tz", "os.path.join(path, name) if not os.path.isfile(filepath): filepath = filepath.replace(' ', '_')", "self._dst_offset-self._std_offset else: return ZERO @tzname_in_python2 def tzname(self, dt): if self._isdst(dt):", "def keys(self): return list(self._vtz.keys()) def get(self, tzid=None): if tzid is", "= comps self._cachedate = [] self._cachecomp = [] def _find_comp(self,", "None comps = [] invtz = True def __repr__(self): return", "\"UTC\"): res.stdoffset *= -1 # We must initialize it first,", "> 1: raise ValueError(\"more than one timezone available\") tzid =", "end: \"+value) elif comptype: if name == \"DTSTART\": rrulelines.append(line) founddtstart", "stored in the file. timecnt, # The number of \"local", "a time zone file # is used in handling POSIX-style", "comptype = None for line in lines: if not line:", "= struct.unpack(\">%dl\" % timecnt, fileobj.read(timecnt*4)) else: self._trans_list = [] #", "time zone environment variables. if ttisstdcnt: isstd = struct.unpack(\">%db\" %", "tzname(self, dt): return self._name def __eq__(self, other): return (isinstance(other, tzoffset)", "(IOError, OSError, ValueError): pass else: tz = None if tzwin:", "__all__ = [\"tzutc\", \"tzoffset\", \"tzlocal\", \"tzfile\", \"tzrange\", \"tzstr\", \"tzical\", \"tzwin\",", "self._name = name self._offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt): return", "self._ttinfo_list[0] else: for i in range(timecnt-1, -1, -1): tti =", "== other._end_delta) def __ne__(self, other): return not self.__eq__(other) def __repr__(self):", "repr(value))) return \"%s(%s)\" % (self.__class__.__name__, \", \".join(l)) def __eq__(self, other):", "there are tzh_leapcnt pairs of four-byte # values, written in", "for comp in self._comps: if not comp.isdst: # Handle the", "dt. return tti.delta-self._find_ttinfo(dt, laststd=1).delta # An alternative for that would", "return False return (self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr", "that # appears next in the file. if timecnt: self._trans_idx", "tti.offset laststdoffset = tti.offset else: # This is dst time.", "here. It is unstable when deciding if # the hour", "not tti.isdst: # This is std time. self._trans_list[i] += tti.offset", "in the file. if timecnt: self._trans_idx = struct.unpack(\">%dB\" % timecnt,", "one timezone available\") tzid = keys[0] return self._vtz.get(tzid) def _parse_offset(self,", "dt): if not self._start_delta: return False year = datetime.datetime(dt.year, 1,", "the given time. # The pairs of values are sorted", "date. We'll look for the # first standard component, or", "the case. Python's # datetime doesn't accept sub-minute timezones. Check", "= self._delta(res.start) if self._start_delta: self._end_delta = self._delta(res.end, isend=1) def _delta(self,", "2AM. kwargs[\"seconds\"] = 7200 if isend: # Convert to standard", "if stdoffset is not None: self._std_offset = datetime.timedelta(seconds=stdoffset) else: self._std_offset", "0 and line[0] == \" \": lines[i-1] += line[1:] del", "Each is used as a transition time (as returned by", "time.daylight: _dst_offset = datetime.timedelta(seconds=-time.altzone) else: _dst_offset = _std_offset def utcoffset(self,", "tt_abbrind serves as an index into the array of #", "Convert to standard time, to follow the documented way #", "ValueError(\"unsupported %s parm: %s \"%(name, parms[0])) tzoffsetfrom = self._parse_offset(value) elif", "kwargs[\"month\"] = x.month if x.weekday is not None: kwargs[\"weekday\"] =", "** # Build ttinfo list self._ttinfo_list = [] for i", "def _isdst(self, dt): if not self._start_delta: return False year =", "self._isdst(dt): return self._dst_offset-self._std_offset else: return ZERO @tzname_in_python2 def tzname(self, dt):", "fileobj.read(ttisstdcnt)) # Finally, there are tzh_ttisgmtcnt UTC/local # indicators, each", "def utcoffset(self, dt): if not self._ttinfo_std: return ZERO return self._find_ttinfo(dt).delta", "tzstr(tzrange): def __init__(self, s): global parser if not parser: from", "else: kwargs[\"month\"] = 10 kwargs[\"day\"] = 31 kwargs[\"weekday\"] = relativedelta.SU(-1)", "into an array of ttinfo structures that # appears next", "class. delta = self._dst_offset-self._std_offset kwargs[\"seconds\"] -= delta.seconds+delta.days*86400 return relativedelta.relativedelta(**kwargs) def", "every dt. return tti.delta-self._find_ttinfo(dt, laststd=1).delta # An alternative for that", "found. for comp in self._comps: if not comp.isdst: lastcomp =", "component end: \"+value) elif comptype: if name == \"DTSTART\": rrulelines.append(line)", "import PY3, string_types __license__ = \"Simplified BSD\" __all__ = [\"tzutc\",", "to a change is DST or not. # # timestamp", "ttinfo structure(s) in the file. ttinfo = [] for i", "associated # with local time types were specified as standard", "1, 1) start = year+self._start_delta end = year+self._end_delta dt =", "return \"%s(...)\" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzstr(tzrange): def", "__repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._s)) if sys.platform != \"win32\":", "use mktime here. It is unstable when deciding if #", "def dst(self, dt): return ZERO @tzname_in_python2 def tzname(self, dt): return", "None self._ttinfo_dst = None self._ttinfo_before = None if self._ttinfo_list: if", "``standard'' byte order. # Each is used as a transition", "tzlocal): return False return (self._std_offset == other._std_offset and self._dst_offset ==", "self._comps = comps self._cachedate = [] self._cachecomp = [] def", "an index into the array of # time zone abbreviation", "there are tzh_ttisstdcnt standard/wall # indicators, each stored as a", "lastcompdt = compdt lastcomp = comp if not lastcomp: #", "implement this. @tzname_in_python2 def tzname(self, dt): if not self._ttinfo_std: return", "long, written in a # ``standard'' byte order (the high-order", "\"EXRULE\", \"EXDATE\"): rrulelines.append(line) elif name == \"TZOFFSETFROM\": if parms: raise", "else: _dst_offset = _std_offset def utcoffset(self, dt): if self._isdst(dt): return", "datetime.timedelta(seconds=offset) def utcoffset(self, dt): return self._offset def dst(self, dt): return", "that's not the case. Python's # datetime doesn't accept sub-minute", "and start is None: self._start_delta = relativedelta.relativedelta( hours=+2, month=4, day=1,", "os.path.isfile(filepath): filepath = filepath.replace(' ', '_') if not os.path.isfile(filepath): continue", "for which data # is stored in the file. timecnt,", "timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, # dt.minute, dt.second, dt.weekday(),", "the documented way # of working with the extra hour.", "None else: raise ValueError(\"invalid component end: \"+value) elif comptype: if", "is stored in the file. timecnt, # The number of", "raise ValueError(\"unsupported %s parm: %s \"%(name, parms[0])) tzoffsetfrom = self._parse_offset(value)", "tzname self.rrule = rrule class _tzicalvtz(datetime.tzinfo): def __init__(self, tzid, comps=[]):", "in ('+', '-'): signal = (-1, +1)[s[0]=='+'] s = s[1:]", "the array of # time zone abbreviation characters that follow", "def tzname_in_python2(myfunc): \"\"\"Change unicode output into bytestrings in Python 2", "7200 if isend: # Convert to standard time, to follow", "= {} for name in self.__slots__: state[name] = getattr(self, name,", "elif len(s) == 6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: raise ValueError(\"invalid offset:", "# The number of UTC/local indicators stored in the file.", "values are written in ``standard'' byte order. # Each is", "initialize it first, since _delta() needs # _std_offset and _dst_offset", "break except (IOError, OSError, ValueError): pass else: tz = tzlocal()", "dt): return ZERO def dst(self, dt): return ZERO @tzname_in_python2 def", "elif name == \"TZOFFSETTO\": if parms: raise ValueError(\"unsupported TZOFFSETTO parm:", "if not tti.isdst: return ZERO # The documentation says that", "self._ttinfo_std: return ZERO return self._find_ttinfo(dt).delta def dst(self, dt): if not", "value = getattr(self, attr) if value is not None: l.append(\"%s=%s\"", "if fileobj.read(4).decode() != \"TZif\": raise ValueError(\"magic not found\") fileobj.read(16) (", "seconds to be added to UTC, tt_isdst tells whether #", "The number of UTC/local indicators stored in the file. ttisgmtcnt,", "# Round to full-minutes if that's not the case. Python's", "= value elif name in (\"TZURL\", \"LAST-MODIFIED\", \"COMMENT\"): pass else:", "datetime.timedelta(seconds=-time.altzone) else: _dst_offset = _std_offset def utcoffset(self, dt): if self._isdst(dt):", "to UTC, tt_isdst tells whether # tm_isdst should be set", "if res is None: raise ValueError(\"unknown string format\") # Here", "# used when a given time is before any transitions,", "# The documentation says that utcoffset()-dst() must # be constant", "self.__class__.__name__ __reduce__ = object.__reduce__ class tzstr(tzrange): def __init__(self, s): global", "rrulelines = [] tzname = None elif name == \"END\":", "< end else: return dt >= start or dt <", "x.jyday is not None: kwargs[\"nlyearday\"] = x.jyday if not kwargs:", "and self._end_delta == other._end_delta) def __ne__(self, other): return not self.__eq__(other)", "global rrule if not rrule: from dateutil import rrule if", "get(self, tzid=None): if tzid is None: keys = list(self._vtz.keys()) if", "be added to UTC, tt_isdst tells whether # tm_isdst should", "are tzh_ttisgmtcnt UTC/local # indicators, each stored as a one-byte", "each one tells which of the different types of #", "self.isdst = isdst self.tzname = tzname self.rrule = rrule class", "= object.__reduce__ class tzoffset(datetime.tzinfo): def __init__(self, name, offset): self._name =", "return self._find_ttinfo(dt).abbr def __eq__(self, other): if not isinstance(other, tzfile): return", "tz, datetime #>>> t = tz.tzlocal() #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #>>>", "# The number of characters of \"time zone # abbreviation", "been read ** # Build ttinfo list self._ttinfo_list = []", "I'm not sure about this. In my tests, the tz", "= relativedelta.SU(+1) else: kwargs[\"month\"] = 10 kwargs[\"day\"] = 31 kwargs[\"weekday\"]", "self._std_offset def dst(self, dt): if self._isdst(dt): return self._dst_offset-self._std_offset else: return", "and not self._ttinfo_std: self._ttinfo_std = self._ttinfo_dst for tti in self._ttinfo_list:", "os.path.isfile(filepath): break else: continue if os.path.isfile(filepath): try: tz = tzfile(filepath)", "__reduce__(self): if not os.path.isfile(self._filename): raise ValueError(\"Unpickable %s class\" % self.__class__.__name__)", "value is not None: l.append(\"%s=%s\" % (attr, repr(value))) return \"%s(%s)\"", "\"tzrange\", \"tzstr\", \"tzical\", \"tzwin\", \"tzwinlocal\", \"gettz\"] relativedelta = None parser", "comp[0] self._cachedate.insert(0, dt) self._cachecomp.insert(0, lastcomp) if len(self._cachedate) > 10: self._cachedate.pop()", "dt.month, dt.day, dt.hour, # dt.minute, dt.second, dt.weekday(), 0, -1)) #", "tzset(3) # begin with the magic characters \"TZif\" to identify", "TZPATHS = [\"/usr/share/zoneinfo\", \"/usr/lib/zoneinfo\", \"/etc/zoneinfo\"] else: TZFILES = [] TZPATHS", "with the magic characters \"TZif\" to identify # them as", "__eq__(self, other): if not isinstance(other, tzrange): return False return (self._std_abbr", "string\") # Unfold i = 0 while i < len(lines):", "[] for idx in self._trans_idx: trans_idx.append(self._ttinfo_list[idx]) self._trans_idx = tuple(trans_idx) #", "= datetime.datetime.utcfromtimestamp(0).toordinal() class tzutc(datetime.tzinfo): def utcoffset(self, dt): return ZERO def", "be: # # return self._ttinfo_dst.offset-self._ttinfo_std.offset # # However, this class", "From tzfile(5): # # The time zone information files used", "# order, followed by a one-byte value for tt_isdst #", "alternative for that would be: # # return self._ttinfo_dst.offset-self._ttinfo_std.offset #", "name, state[name]) class tzfile(datetime.tzinfo): # http://www.twinsun.com/tz/tz-link.htm # ftp://ftp.iana.org/tz/tz*.tar.gz def __init__(self,", "# char; each one tells which of the different types", "are dst. self._ttinfo_std = None self._ttinfo_dst = None self._ttinfo_before =", "_delta() needs # _std_offset and _dst_offset set. Use False in", "isinstance(other, tzfile): return False return (self._trans_list == other._trans_list and self._trans_idx", "to unicode strings \"\"\" def inner_func(*args, **kwargs): if PY3: return", "self._cachecomp = [] def _find_comp(self, dt): if len(self._comps) == 1:", "tti break else: self._ttinfo_before = self._ttinfo_list[0] # Now fix transition", "dt.minute, dt.second, dt.weekday(), 0, -1)) # return time.localtime(timestamp).tm_isdst # #", "dt.hour * 3600 + dt.minute * 60 + dt.second) idx", "is 2AM. kwargs[\"seconds\"] = 7200 if isend: # Convert to", "name == \"BEGIN\": if value in (\"STANDARD\", \"DAYLIGHT\"): # Process", "Here we break the compatibility with the TZ variable handling.", "def __repr__(self): return \"%s(%s, %s)\" % (self.__class__.__name__, repr(self._name), self._offset.days*86400+self._offset.seconds) __reduce__", "of # time zone abbreviation characters that follow the #", "parms: raise ValueError(\"unsupported TZID parm: \"+parms[0]) tzid = value elif", "in the # dst offset, so I belive that this", "list(self._trans_list) for i in range(len(self._trans_list)): tti = self._trans_idx[i] if not", "tz = None else: for path in TZPATHS: filepath =", "The time zone information files used by tzset(3) # begin", "changes in the # dst offset, so I belive that", "tzid = value elif name in (\"TZURL\", \"LAST-MODIFIED\", \"COMMENT\"): pass", "value == \"VTIMEZONE\": if comptype: raise ValueError(\"component not closed: \"+comptype)", "not tti.isdst: return ZERO # The documentation says that utcoffset()-dst()", "myfunc(*args, **kwargs) else: return myfunc(*args, **kwargs).encode() return inner_func ZERO =", "a change is DST or not. # # timestamp =", "not kwargs: # Default is to start on first sunday", "if idx == 0: return self._ttinfo_before if laststd: while idx", "tzh_ttisgmtcnt UTC/local # indicators, each stored as a one-byte value;", "if parms: raise ValueError(\"unsupported TZNAME parm: \"+parms[0]) tzname = value", "for now if leapcnt: leap = struct.unpack(\">%dl\" % (leapcnt*2), fileobj.read(leapcnt*8))", "not None: kwargs[\"month\"] = x.month if x.weekday is not None:", "CRLF elif hasattr(fileobj, \"name\"): self._s = fileobj.name else: self._s =", "self._dst_abbr else: return self._std_abbr def _isdst(self, dt): if not self._start_delta:", "if # the hour near to a change is DST", "fileobj = open(fileobj, 'r') # ical should be encoded in", "1: return self._comps[0] dt = dt.replace(tzinfo=None) try: return self._cachecomp[self._cachedate.index(dt)] except", "be in wall time. OTOH, it's # always in gmt", "timezones. Check # http://python.org/sf/1447945 for some information. gmtoff = (gmtoff+30)//60*60", "Replace ttinfo indexes for ttinfo objects. trans_idx = [] for", "< end def __eq__(self, other): if not isinstance(other, tzrange): return", "name = os.environ[\"TZ\"] except KeyError: pass if name is None", "self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom self.isdst", "zone information files used by tzset(3) # begin with the", "long, in a standard byte # order, followed by a", "\"Simplified BSD\" __all__ = [\"tzutc\", \"tzoffset\", \"tzlocal\", \"tzfile\", \"tzrange\", \"tzstr\",", "not sure about this. In my tests, the tz source", "given # time is before the first onset date. We'll", "that utcoffset()-dst() must # be constant for every dt. return", "self._ttinfo_dst = None self._ttinfo_before = None if self._ttinfo_list: if not", "source file # is setup to wall time, and in", "values of type long, written in a # ``standard'' byte", "not self._start_delta: return False year = datetime.datetime(dt.year, 1, 1) start", "signal = (-1, +1)[s[0]=='+'] s = s[1:] else: signal =", "dt.second) return time.localtime(timestamp+time.timezone).tm_isdst def __eq__(self, other): if not isinstance(other, tzlocal):", "= isdst tti.abbr = abbr[abbrind:abbr.find('\\x00', abbrind)] tti.isstd = (ttisstdcnt >", "== other._trans_list and self._trans_idx == other._trans_idx and self._ttinfo_list == other._ttinfo_list)", "in the file. ttinfo = [] for i in range(typecnt):", "tzname() API changed in Python 3. It used to return", "not rrule: from dateutil import rrule if isinstance(fileobj, string_types): self._s", "tzoffsetto, (comptype == \"DAYLIGHT\"), tzname, rr) comps.append(comp) comptype = None", "i in range(typecnt): gmtoff, isdst, abbrind = ttinfo[i] # Round", "value elif name in (\"TZURL\", \"LAST-MODIFIED\", \"COMMENT\"): pass else: raise", "when a time zone file # is used in handling", "founddtstart = True elif name in (\"RRULE\", \"RDATE\", \"EXRULE\", \"EXDATE\"):", "time (as # returned by time(2)) at which a leap", "def __repr__(self): return \"%s(...)\" % self.__class__.__name__ __reduce__ = object.__reduce__ class", "idx += 1 else: return self._ttinfo_std if idx == 0:", "in ascending order # by time. # Not used, for", "have at least one offset to be a tzstr if", "def dst(self, dt): comp = self._find_comp(dt) if comp.isdst: return comp.tzoffsetdiff", "\"+comptype) if not tzid: raise ValueError(\"mandatory TZID not found\") if", "60 + dt.second) idx = 0 for trans in self._trans_list:", "with the TZ variable handling. # GMT-3 actually *means* the", "tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff =", "else: raise ValueError(\"unsupported property: \"+name) elif name == \"BEGIN\" and", "times. tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset, start=False, end=False) if not", "october. if not isend: kwargs[\"month\"] = 4 kwargs[\"day\"] = 1", "parser._parsetz(s) if res is None: raise ValueError(\"unknown string format\") #", "and self.isdst == other.isdst and self.abbr == other.abbr and self.isstd", "parser if not parser: from dateutil import parser self._s =", "TZPATHS: filepath = os.path.join(path, filename) if os.path.isfile(filepath): break else: continue", "if parms: raise ValueError(\"unsupported TZID parm: \"+parms[0]) tzid = value", "isinstance(other, _ttinfo): return False return (self.offset == other.offset and self.delta", "value; # they tell whether the transition times associated #", "= abbr[abbrind:abbr.find('\\x00', abbrind)] tti.isstd = (ttisstdcnt > i and isstd[i]", "# The number of \"transition times\" for which data #", "60 + dt.second) return time.localtime(timestamp+time.timezone).tm_isdst def __eq__(self, other): if not", "if not os.path.isfile(self._filename): raise ValueError(\"Unpickable %s class\" % self.__class__.__name__) return", "other): if not isinstance(other, tzfile): return False return (self._trans_list ==", "used when # a time zone file is used in", "fileobj fileobj = open(fileobj, 'rb') elif hasattr(fileobj, \"name\"): self._filename =", "if comp.isdst: return comp.tzoffsetdiff else: return ZERO @tzname_in_python2 def tzname(self,", "None try: from dateutil.tzwin import tzwin, tzwinlocal except (ImportError, OSError):", "ttisgmtcnt, fileobj.read(ttisgmtcnt)) # ** Everything has been read ** #", "other._end_delta) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return", "= self._dst_offset-self._std_offset kwargs[\"seconds\"] -= delta.seconds+delta.days*86400 return relativedelta.relativedelta(**kwargs) def __repr__(self): return", "__reduce__ = object.__reduce__ class tzstr(tzrange): def __init__(self, s): global parser", "not None: kwargs[\"yearday\"] = x.yday elif x.jyday is not None:", "res is None: raise ValueError(\"unknown string format\") # Here we", "\"%s(%s)\" % (self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp(object): def __init__(self, tzoffsetfrom, tzoffsetto,", "unicode strings \"\"\" def inner_func(*args, **kwargs): if PY3: return myfunc(*args,", "if not tzid: raise ValueError(\"mandatory TZID not found\") if not", "timestamp < trans: break idx += 1 else: return self._ttinfo_std", "if not line: continue name, value = line.split(':', 1) parms", "stdoffset is not None: self._std_offset = datetime.timedelta(seconds=stdoffset) else: self._std_offset =", "None: kwargs[\"weekday\"] = relativedelta.weekday(x.weekday, x.week) if x.week > 0: kwargs[\"day\"]", "other): return not self.__eq__(other) def __repr__(self): return \"%s(...)\" % self.__class__.__name__", "DST or not. # # timestamp = time.mktime((dt.year, dt.month, dt.day,", "break else: if self._ttinfo_dst and not self._ttinfo_std: self._ttinfo_std = self._ttinfo_dst", "# GMT-3 actually *means* the timezone -3. if res.stdabbr in", "of ttinfo structures that # appears next in the file.", "elif name in time.tzname: tz = tzlocal() return tz #", "line = lines[i].rstrip() if not line: del lines[i] elif i", "as a transition time (as returned by # time(2)) at", "= [\"offset\", \"delta\", \"isdst\", \"abbr\", \"isstd\", \"isgmt\"] def __init__(self): for", "information. gmtoff = (gmtoff+30)//60*60 tti = _ttinfo() tti.offset = gmtoff", "if isinstance(fileobj, string_types): self._s = fileobj fileobj = open(fileobj, 'r')", "if not lines: raise ValueError(\"empty string\") # Unfold i =", "parm: %s \"%(name, parms[0])) tzoffsetfrom = self._parse_offset(value) elif name ==", "!= \"win32\": TZFILES = [\"/etc/localtime\", \"localtime\"] TZPATHS = [\"/usr/share/zoneinfo\", \"/usr/lib/zoneinfo\",", "\"%s()\" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzoffset(datetime.tzinfo): def __init__(self,", "followed by # sixteen bytes reserved for future use, followed", "= {} self._parse_rfc(fileobj.read()) def keys(self): return list(self._vtz.keys()) def get(self, tzid=None):", "self.__class__.__name__) return (self.__class__, (self._filename,)) class tzrange(datetime.tzinfo): def __init__(self, stdabbr, stdoffset=None,", "pairs of four-byte # values, written in standard byte order;", "def __init__(self, fileobj): if isinstance(fileobj, string_types): self._filename = fileobj fileobj", "= x.jyday if not kwargs: # Default is to start", "not found\") if not comps: raise ValueError(\"at least one component", "def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return \"%s(%s,", "self._start_delta = None self._end_delta = None else: self._start_delta = self._delta(res.start)", "repr(self._name), self._offset.days*86400+self._offset.seconds) __reduce__ = object.__reduce__ class tzlocal(datetime.tzinfo): _std_offset = datetime.timedelta(seconds=-time.timezone)", "None lastcompdt = None for comp in self._comps: if not", "# abbreviation strings\" stored in the file. charcnt, ) =", "filepath = filepath.replace(' ', '_') if not os.path.isfile(filepath): continue try:", "if PY3: return myfunc(*args, **kwargs) else: return myfunc(*args, **kwargs).encode() return", "filepath in TZFILES: if not os.path.isabs(filepath): filename = filepath for", "= None elif name == \"END\": if value == \"VTIMEZONE\":", "struct.unpack(\">6l\", fileobj.read(24)) # The above header is followed by tzh_timecnt", "end: return dt >= start and dt < end else:", "parm: \"+parms[0]) tzoffsetto = self._parse_offset(value) elif name == \"TZNAME\": if", "# way to implement this. @tzname_in_python2 def tzname(self, dt): if", "tti.isdst: # This is std time. self._trans_list[i] += tti.offset laststdoffset", "mo_future import PY3, string_types __license__ = \"Simplified BSD\" __all__ =", "= year+self._start_delta end = year+self._end_delta dt = dt.replace(tzinfo=None) if start", "not found\") if tzoffsetfrom is None: raise ValueError(\"mandatory TZOFFSETFROM not", "if name.startswith(\":\"): name = name[:-1] if os.path.isabs(name): if os.path.isfile(name): tz", "= None if self._ttinfo_list: if not self._trans_list: self._ttinfo_std = self._ttinfo_first", "one-byte value; # they tell whether the transition times associated", "%s)\" % (self.__class__.__name__, repr(self._name), self._offset.days*86400+self._offset.seconds) __reduce__ = object.__reduce__ class tzlocal(datetime.tzinfo):", "computing local time # change. if timecnt: self._trans_list = struct.unpack(\">%dl\"", "is not None: self._dst_offset = datetime.timedelta(seconds=dstoffset) elif dstabbr and stdoffset", "files used by tzset(3) # begin with the magic characters", "which of the different types of # ``local time'' types", "\"tzstr\", \"tzical\", \"tzwin\", \"tzwinlocal\", \"gettz\"] relativedelta = None parser =", "This module offers extensions to the standard Python datetime module.", "sunday of april, and end # on last sunday of", "name == \"END\": if value == \"VTIMEZONE\": if comptype: raise", "# dt.minute, dt.second, dt.weekday(), 0, -1)) # return time.localtime(timestamp).tm_isdst #", "i and isgmt[i] != 0) self._ttinfo_list.append(tti) # Replace ttinfo indexes", "needs # _std_offset and _dst_offset set. Use False in start/end", "dt): if not self._ttinfo_dst: return ZERO tti = self._find_ttinfo(dt) if", "or the first component, if # none is found. for", "in self._ttinfo_list: if not tti.isdst: self._ttinfo_before = tti break else:", "in the file. ttisstdcnt, # The number of leap seconds", "= [] invtz = True def __repr__(self): return \"%s(%s)\" %", "order; the # first value of each pair gives the", "not self._ttinfo_std and not tti.isdst: self._ttinfo_std = tti elif not", "used to return bytes, but was changed to unicode strings", "ValueError(\"Unpickable %s class\" % self.__class__.__name__) return (self.__class__, (self._filename,)) class tzrange(datetime.tzinfo):", "if len(keys) == 0: raise ValueError(\"no timezones defined\") elif len(keys)", "= 4 kwargs[\"day\"] = 1 kwargs[\"weekday\"] = relativedelta.SU(+1) else: kwargs[\"month\"]", "1: raise ValueError(\"more than one timezone available\") tzid = keys[0]", "structure, tt_gmtoff gives the number of # seconds to be", "for idx in self._trans_idx: trans_idx.append(self._ttinfo_list[idx]) self._trans_idx = tuple(trans_idx) # Set", "keys(self): return list(self._vtz.keys()) def get(self, tzid=None): if tzid is None:", "Finally, there are tzh_ttisgmtcnt UTC/local # indicators, each stored as", "for every dt. return tti.delta-self._find_ttinfo(dt, laststd=1).delta # An alternative for", "a standard byte # order, followed by a one-byte value", "Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz = False elif", "fileobj.read(6))) abbr = fileobj.read(charcnt).decode() # Then there are tzh_leapcnt pairs", "delta.seconds+delta.days*86400 return relativedelta.relativedelta(**kwargs) def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._s))", "= tuple(self._trans_list) def _find_ttinfo(self, dt, laststd=0): timestamp = ((dt.toordinal() -", "range(typecnt): ttinfo.append(struct.unpack(\">lbb\", fileobj.read(6))) abbr = fileobj.read(charcnt).decode() # Then there are", "GMT-3 actually *means* the timezone -3. if res.stdabbr in (\"GMT\",", "handling. # GMT-3 actually *means* the timezone -3. if res.stdabbr", "lastcomp = None lastcompdt = None for comp in self._comps:", "if you have comments # about this. laststdoffset = 0", "documented way # of working with the extra hour. See", "# return self._ttinfo_dst.offset-self._ttinfo_std.offset # # However, this class stores historical", "implementation: # timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400 +", "def _parse_rfc(self, s): lines = s.splitlines() if not lines: raise", "elif i > 0 and line[0] == \" \": lines[i-1]", "is stored in the file (must not be zero). typecnt,", "first standard component, or the first component, if # none", "return (int(s[:2])*3600+int(s[2:])*60)*signal elif len(s) == 6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: raise", "isinstance(other, tzlocal): return False return (self._std_offset == other._std_offset and self._dst_offset", "self._filename = fileobj fileobj = open(fileobj, 'rb') elif hasattr(fileobj, \"name\"):", "ttinfo.append(struct.unpack(\">lbb\", fileobj.read(6))) abbr = fileobj.read(charcnt).decode() # Then there are tzh_leapcnt", "handling POSIX-style time zone envi- # ronment variables. if ttisgmtcnt:", "else: self._end_delta = end def utcoffset(self, dt): if self._isdst(dt): return", "def __eq__(self, other): if not isinstance(other, tzfile): return False return", "the documentation # of the tzinfo class. delta = self._dst_offset-self._std_offset", "rrulelines: rr = rrule.rrulestr(\"\\n\".join(rrulelines), compatible=True, ignoretz=True, cache=True) comp = _tzicalvtzcomp(tzoffsetfrom,", "name[:-1] if os.path.isabs(name): if os.path.isfile(name): tz = tzfile(name) else: tz", "except ValueError: pass lastcomp = None lastcompdt = None for", "else: return ZERO @tzname_in_python2 def tzname(self, dt): return self._find_comp(dt).tzname def", "we break the compatibility with the TZ variable handling. #", "None: keys = list(self._vtz.keys()) if len(keys) == 0: raise ValueError(\"no", "object.__reduce__ class tzical(object): def __init__(self, fileobj): global rrule if not", "\"%s(%s)\" % (self.__class__.__name__, repr(self._s)) if sys.platform != \"win32\": TZFILES =", "= getattr(self, attr) if value is not None: l.append(\"%s=%s\" %", "in a standard byte # order, followed by a one-byte", "x.day: kwargs[\"day\"] = x.day elif x.yday is not None: kwargs[\"yearday\"]", "not isinstance(other, tzfile): return False return (self._trans_list == other._trans_list and", "KeyError: pass if name is None or name == \":\":", "= datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom self.isdst =", "%s \"%(name, parms[0])) tzoffsetfrom = self._parse_offset(value) elif name == \"TZOFFSETTO\":", "self._find_comp(dt) if comp.isdst: return comp.tzoffsetdiff else: return ZERO @tzname_in_python2 def", "(leapcnt*2), fileobj.read(leapcnt*8)) # Then there are tzh_ttisstdcnt standard/wall # indicators,", "is used in handling POSIX-style time zone envi- # ronment", "the number of # seconds to be added to UTC,", "elif name in (\"RRULE\", \"RDATE\", \"EXRULE\", \"EXDATE\"): rrulelines.append(line) elif name", "# of the tzinfo class. delta = self._dst_offset-self._std_offset kwargs[\"seconds\"] -=", "= tti break else: self._ttinfo_before = self._ttinfo_list[0] # Now fix", "return \"%s(%s)\" % (self.__class__.__name__, repr(self._filename)) def __reduce__(self): if not os.path.isfile(self._filename):", "@tzname_in_python2 def tzname(self, dt): if self._isdst(dt): return self._dst_abbr else: return", "self._trans_idx[idx-1] if not tti.isdst: return tti idx -= 1 else:", "(as returned by # time(2)) at which the rules for", "@tzname_in_python2 def tzname(self, dt): if not self._ttinfo_std: return None return", "least one component is needed\") # Process vtimezone self._vtz[tzid] =", "# # However, this class stores historical changes in the", "datetime.datetime(dt.year, 1, 1) start = year+self._start_delta end = year+self._end_delta dt", "\"gettz\"] relativedelta = None parser = None rrule = None", "line[0] == \" \": lines[i-1] += line[1:] del lines[i] else:", "# sixteen bytes reserved for future use, followed by #", "= 31 kwargs[\"weekday\"] = relativedelta.SU(-1) if x.time is not None:", "try: return self._cachecomp[self._cachedate.index(dt)] except ValueError: pass lastcomp = None lastcompdt", "else: self._s = repr(fileobj) self._vtz = {} self._parse_rfc(fileobj.read()) def keys(self):", "raise ValueError(\"more than one timezone available\") tzid = keys[0] return", "__init__(self, name, offset): self._name = name self._offset = datetime.timedelta(seconds=offset) def", "to avoid building it two times. tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr,", "isdst tti.abbr = abbr[abbrind:abbr.find('\\x00', abbrind)] tti.isstd = (ttisstdcnt > i", "kwargs[\"yearday\"] = x.yday elif x.jyday is not None: kwargs[\"nlyearday\"] =", "import sys import time from mo_future import PY3, string_types __license__", "of # seconds to be added to UTC, tt_isdst tells", "(\"RRULE\", \"RDATE\", \"EXRULE\", \"EXDATE\"): rrulelines.append(line) elif name == \"TZOFFSETFROM\": if", "name == \"TZOFFSETTO\": if parms: raise ValueError(\"unsupported TZOFFSETTO parm: \"+parms[0])", "True def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._s)) if sys.platform", "# Each ttinfo structure is written as a four-byte value", "def __repr__(self): return \"<tzicalvtz %s>\" % repr(self._tzid) __reduce__ = object.__reduce__", "else: tz = tzlocal() else: if name.startswith(\":\"): name = name[:-1]", "UTC, tt_isdst tells whether # tm_isdst should be set by", "\"0123456789\": try: tz = tzstr(name) except ValueError: pass break else:", "kwargs[\"day\"] = x.day elif x.yday is not None: kwargs[\"yearday\"] =", "= [] for i in range(typecnt): gmtoff, isdst, abbrind =", "# time or wall clock time, and are used when", "(isinstance(other, tzoffset) and self._offset == other._offset) def __ne__(self, other): return", "rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom", "l = [] for attr in self.__slots__: value = getattr(self,", "the # first standard component, or the first component, if", "inner_func ZERO = datetime.timedelta(0) EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal() class tzutc(datetime.tzinfo): def", "of standard/wall indicators stored in the file. ttisstdcnt, # The", "of leap seconds for which data is # stored in", "datetime import os import struct import sys import time from", "-= 1 else: return self._ttinfo_std else: return self._trans_idx[idx-1] def utcoffset(self,", "if not lastcomp: # RFC says nothing about what to", "onset date. We'll look for the # first standard component,", "parms: raise ValueError(\"empty property name\") name = parms[0].upper() parms =", "fileobj.read(charcnt).decode() # Then there are tzh_leapcnt pairs of four-byte #", "else: if name.startswith(\":\"): name = name[:-1] if os.path.isabs(name): if os.path.isfile(name):", "comp if not lastcomp: # RFC says nothing about what", "tzid self._comps = comps self._cachedate = [] self._cachecomp = []", "tzfile(name) else: tz = None else: for path in TZPATHS:", "name) if not os.path.isfile(filepath): filepath = filepath.replace(' ', '_') if", "time. self._trans_list[i] += tti.offset laststdoffset = tti.offset else: # This", "return relativedelta.relativedelta(**kwargs) def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._s)) class", "weekday=relativedelta.SU(+1)) else: self._start_delta = start if dstabbr and end is", "line: del lines[i] elif i > 0 and line[0] ==", "# # Here is a more stable implementation: # timestamp", "return (isinstance(other, tzutc) or (isinstance(other, tzoffset) and other._offset == ZERO))", "structure is written as a four-byte value # for tt_gmtoff", "relativedelta.relativedelta( hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) else: self._end_delta = end def", "= comp if not lastcomp: # RFC says nothing about", "http://www.twinsun.com/tz/tz-link.htm # ftp://ftp.iana.org/tz/tz*.tar.gz def __init__(self, fileobj): if isinstance(fileobj, string_types): self._filename", "_dst_offset set. Use False in start/end # to avoid building", "+ dt.hour * 3600 + dt.minute * 60 + dt.second)", "len(s) == 4: return (int(s[:2])*3600+int(s[2:])*60)*signal elif len(s) == 6: return", "lines[i] elif i > 0 and line[0] == \" \":", "ValueError(\"component not closed: \"+comptype) if not tzid: raise ValueError(\"mandatory TZID", "c in name: # name must have at least one", "\"+value) comptype = value founddtstart = False tzoffsetfrom = None", "tuple(self._trans_list) def _find_ttinfo(self, dt, laststd=0): timestamp = ((dt.toordinal() - EPOCHORDINAL)", "# Then there are tzh_ttisstdcnt standard/wall # indicators, each stored", "dt.day, dt.hour, # dt.minute, dt.second, dt.weekday(), 0, -1)) # return", "should be set by localtime(3), and # tt_abbrind serves as", "# with local time types were specified as standard #", "= os.path.join(path, name) if not os.path.isfile(filepath): filepath = filepath.replace(' ',", "self._offset == other._offset) def __ne__(self, other): return not self.__eq__(other) def", "this. In my tests, the tz source file # is", "since _delta() needs # _std_offset and _dst_offset set. Use False", "dt >= start and dt < end else: return dt", "<gh_stars>0 \"\"\" Copyright (c) 2003-2007 <NAME> <<EMAIL>> This module offers", "return time.localtime(timestamp).tm_isdst # # The code above yields the following", "file # is used in handling POSIX-style time zone envi-", "return tti idx -= 1 else: return self._ttinfo_std else: return", "not founddtstart: raise ValueError(\"mandatory DTSTART not found\") if tzoffsetfrom is", "__repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._filename)) def __reduce__(self): if not", "* 86400 + dt.hour * 3600 + dt.minute * 60", "of the value is written first). if fileobj.read(4).decode() != \"TZif\":", "in ``standard'' byte order. # Each is used as a", "idx > 0: tti = self._trans_idx[idx-1] if not tti.isdst: return", "\"time zone # abbreviation strings\" stored in the file. charcnt,", "[] def _find_comp(self, dt): if len(self._comps) == 1: return self._comps[0]", "\":\": for filepath in TZFILES: if not os.path.isabs(filepath): filename =", "def __repr__(self): return \"%s(%s)\" % (self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp(object): def", "tests, the tz source file # is setup to wall" ]
[ "# @FileName : view.py # @Author : 胡守杰 # @Email", "conf.global_settings import BASE_PATH class InputWindowView(View): uiFilePath = os.path.join(BASE_PATH, \"src\\\\window\\\\inputWindow\\\\inputWindow.ui\") if", "胡守杰 # @Email : <EMAIL> # @ZhFileDescription : # @EnFileDescription", "# @ZhFileDescription : # @EnFileDescription : \"\"\" import os from", "import os from pyside2mvcframework.core.view import View from conf.global_settings import BASE_PATH", "{filename}\".format(filename=__file__)) import sys from PySide2.QtWidgets import QApplication app = QApplication(sys.argv)", "# @ProjectName : PySide2MVCFramework # @FileName : view.py # @Author", "-*- coding: utf-8 -*- \"\"\" # @SoftwareIDE : PyCharm2020Pro #", "<EMAIL> # @ZhFileDescription : # @EnFileDescription : \"\"\" import os", "@EnFileDescription : \"\"\" import os from pyside2mvcframework.core.view import View from", "import QApplication app = QApplication(sys.argv) view = InputWindowView().birth() view.show() sys.exit(app.exec_())", "from {filename}\".format(filename=__file__)) import sys from PySide2.QtWidgets import QApplication app =", "\"src\\\\window\\\\inputWindow\\\\inputWindow.ui\") if __name__ == '__main__': print(\"unit test from {filename}\".format(filename=__file__)) import", ": PyCharm2020Pro # @ProjectName : PySide2MVCFramework # @FileName : view.py", "import sys from PySide2.QtWidgets import QApplication app = QApplication(sys.argv) view", "# @EnFileDescription : \"\"\" import os from pyside2mvcframework.core.view import View", "coding: utf-8 -*- \"\"\" # @SoftwareIDE : PyCharm2020Pro # @ProjectName", "from conf.global_settings import BASE_PATH class InputWindowView(View): uiFilePath = os.path.join(BASE_PATH, \"src\\\\window\\\\inputWindow\\\\inputWindow.ui\")", ": view.py # @Author : 胡守杰 # @Email : <EMAIL>", "\"\"\" import os from pyside2mvcframework.core.view import View from conf.global_settings import", "@SoftwareIDE : PyCharm2020Pro # @ProjectName : PySide2MVCFramework # @FileName :", "-*- \"\"\" # @SoftwareIDE : PyCharm2020Pro # @ProjectName : PySide2MVCFramework", ": \"\"\" import os from pyside2mvcframework.core.view import View from conf.global_settings", "'__main__': print(\"unit test from {filename}\".format(filename=__file__)) import sys from PySide2.QtWidgets import", "utf-8 -*- \"\"\" # @SoftwareIDE : PyCharm2020Pro # @ProjectName :", "class InputWindowView(View): uiFilePath = os.path.join(BASE_PATH, \"src\\\\window\\\\inputWindow\\\\inputWindow.ui\") if __name__ == '__main__':", "import BASE_PATH class InputWindowView(View): uiFilePath = os.path.join(BASE_PATH, \"src\\\\window\\\\inputWindow\\\\inputWindow.ui\") if __name__", "__name__ == '__main__': print(\"unit test from {filename}\".format(filename=__file__)) import sys from", "PySide2.QtWidgets import QApplication app = QApplication(sys.argv) view = InputWindowView().birth() view.show()", "from PySide2.QtWidgets import QApplication app = QApplication(sys.argv) view = InputWindowView().birth()", "if __name__ == '__main__': print(\"unit test from {filename}\".format(filename=__file__)) import sys", ": # @EnFileDescription : \"\"\" import os from pyside2mvcframework.core.view import", "view.py # @Author : 胡守杰 # @Email : <EMAIL> #", ": 胡守杰 # @Email : <EMAIL> # @ZhFileDescription : #", "# @Email : <EMAIL> # @ZhFileDescription : # @EnFileDescription :", "@Author : 胡守杰 # @Email : <EMAIL> # @ZhFileDescription :", "InputWindowView(View): uiFilePath = os.path.join(BASE_PATH, \"src\\\\window\\\\inputWindow\\\\inputWindow.ui\") if __name__ == '__main__': print(\"unit", "PySide2MVCFramework # @FileName : view.py # @Author : 胡守杰 #", "\"\"\" # @SoftwareIDE : PyCharm2020Pro # @ProjectName : PySide2MVCFramework #", "= os.path.join(BASE_PATH, \"src\\\\window\\\\inputWindow\\\\inputWindow.ui\") if __name__ == '__main__': print(\"unit test from", "== '__main__': print(\"unit test from {filename}\".format(filename=__file__)) import sys from PySide2.QtWidgets", "uiFilePath = os.path.join(BASE_PATH, \"src\\\\window\\\\inputWindow\\\\inputWindow.ui\") if __name__ == '__main__': print(\"unit test", "os from pyside2mvcframework.core.view import View from conf.global_settings import BASE_PATH class", "@FileName : view.py # @Author : 胡守杰 # @Email :", "# @SoftwareIDE : PyCharm2020Pro # @ProjectName : PySide2MVCFramework # @FileName", ": <EMAIL> # @ZhFileDescription : # @EnFileDescription : \"\"\" import", "from pyside2mvcframework.core.view import View from conf.global_settings import BASE_PATH class InputWindowView(View):", "@ProjectName : PySide2MVCFramework # @FileName : view.py # @Author :", "print(\"unit test from {filename}\".format(filename=__file__)) import sys from PySide2.QtWidgets import QApplication", "@ZhFileDescription : # @EnFileDescription : \"\"\" import os from pyside2mvcframework.core.view", "# @Author : 胡守杰 # @Email : <EMAIL> # @ZhFileDescription", "pyside2mvcframework.core.view import View from conf.global_settings import BASE_PATH class InputWindowView(View): uiFilePath", "BASE_PATH class InputWindowView(View): uiFilePath = os.path.join(BASE_PATH, \"src\\\\window\\\\inputWindow\\\\inputWindow.ui\") if __name__ ==", "# -*- coding: utf-8 -*- \"\"\" # @SoftwareIDE : PyCharm2020Pro", "os.path.join(BASE_PATH, \"src\\\\window\\\\inputWindow\\\\inputWindow.ui\") if __name__ == '__main__': print(\"unit test from {filename}\".format(filename=__file__))", "View from conf.global_settings import BASE_PATH class InputWindowView(View): uiFilePath = os.path.join(BASE_PATH,", "sys from PySide2.QtWidgets import QApplication app = QApplication(sys.argv) view =", "test from {filename}\".format(filename=__file__)) import sys from PySide2.QtWidgets import QApplication app", "@Email : <EMAIL> # @ZhFileDescription : # @EnFileDescription : \"\"\"", "PyCharm2020Pro # @ProjectName : PySide2MVCFramework # @FileName : view.py #", ": PySide2MVCFramework # @FileName : view.py # @Author : 胡守杰", "import View from conf.global_settings import BASE_PATH class InputWindowView(View): uiFilePath =" ]
[ "code_gen_line) f = open(os.path.join(verilog_dir, \"{}.v\".format(self.onnx_node.name)), \"w\") f.write(template) f.close() self.code_gen_dict.clear() def", "True, \"\"), # Toggle between hls or IPI implementation #", "# and/or other materials provided with the distribution. # #", "impl_style == \"rtl\": return super().code_generation_ipi() elif impl_style == \"vivado\": cmd", "\"create_bd_intf_pin -mode Slave \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, din_name)", "\"\"), # Toggle between hls or IPI implementation # rtl", "for FIFOs when impl_style is vivado # auto -- let", "[list CONFIG.TDATA_NUM_BYTES {%d}] \" \"[get_bd_cells /%s/fifo]\" % (np.ceil(self.get_outstream_width() / 8),", "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR", "node = self.onnx_node prefixed_top_name = \"%s\" % (node.name) return prefixed_top_name", "f.write(\"vivado -mode batch -source package_ip.tcl\\n\") f.write(\"cd {}\\n\".format(working_dir)) bash_command = [\"bash\",", "packaging tcl template template = templates.ip_package_tcl self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)]", "StreamingFIFO(HLSCustomOp): def __init__(self, onnx_node): super().__init__(onnx_node) self.strm_fifo_wrapper = templates.strm_fifo_wrapper def get_nodeattr_types(self):", "% ( node.name, str(self.get_input_datatype()), str(idt), ) warnings.warn(warn_str) self.set_nodeattr(\"dataType\", idt.name) #", "model): exp_ishape = self.get_normal_input_shape() oshape = self.get_normal_output_shape() ishape = tuple(model.get_tensor_shape(self.onnx_node.input[0]))", "NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE", "without specific prior written permission. # # THIS SOFTWARE IS", "# set ipgen_path and ip_path to point to the new", "(math.ceil(W / 18)) else: return (math.ceil(depth / 512)) * (math.ceil(W", "is vivado # auto -- let Vivado decide # block", "(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR", "# vivado - use the AXI Infrastructure FIFO \"impl_style\": (\"s\",", "= [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$OUT_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$WIDTH$\"]", "GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS;", "\"s\", False, \"auto\", {\"auto\", \"block\", \"distributed\", \"ultra\"}, ), } my_attrs.update(super().get_nodeattr_types())", "script will be invoked from the sources dir so root_dir=.", "def read_npy_data(self): pass def strm_decl(self): pass def docompute(self): pass def", "notice, this # list of conditions and the following disclaimer.", "+ \"/make_ip.sh\" working_dir = os.environ[\"PWD\"] with open(make_project_sh, \"w\") as f:", "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH", "assert depth >= 2, \"\"\"Depth is too low\"\"\" if depth", "self.get_nodeattr(\"impl_style\") == \"rtl\": warnings.warn( \"Depth is high, set between 2", "-mode Slave \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, din_name) )", "!= self.get_input_datatype(): warn_str = \"inputDataType changing for %s: %s ->", "= odt.bitwidth() packed_bits = self.get_outstream_width() out_npy_path = \"{}/output.npy\".format(code_gen_dir) out_shape =", "= \"%s\" % (node.name) return prefixed_top_name def code_generation_ipgen(self, model, fpgapart,", "# block -- use BRAM # distributed -- use LUTRAM", "node = self.onnx_node inp = context[node.input[0]] exp_shape = self.get_normal_input_shape() if", "\"FIFO implementation style %s not supported, please use rtl or", "template template = templates.ip_package_tcl self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] # note:", "in between fpgadataflow nodes # the folded shape could be", "Copyright (c) 2020, Xilinx # All rights reserved. # #", "= inp.reshape(expected_inp_shape) if DataType[self.get_nodeattr(\"dataType\")] == DataType.BIPOLAR: # store bipolar activations", "output = np.load(out_npy_path) oshape = self.get_normal_output_shape() output = np.asarray([output], dtype=np.float32).reshape(*oshape)", "transform list into long string separated by '\\n' code_gen_line =", "subprocess.Popen(bash_command, stdout=subprocess.PIPE) process_compile.communicate() # set ipgen_path and ip_path to point", "/%s/%s\" % (node_name, clk_name)) cmd.append(\"create_bd_pin -dir I -type rst /%s/%s\"", "activations as binary reshaped_input = (reshaped_input + 1) / 2", ") def get_number_output_values(self): folded_oshape = self.get_folded_output_shape() return np.prod(folded_oshape[:-1]) def global_includes(self):", "IP packaging tcl template template = templates.ip_package_tcl self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] =", "(1, mh) # so to achieve this the two inner", "with the next inner dimension folding_factor = folded_shape[-2] * inner_dim", "\"\\n\".join(self.code_gen_dict[key]) template = template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir, \"{}.v\".format(self.onnx_node.name)), \"w\")", "\"StreamingFIFO impl_style \" \"cannot be vivado for rtlsim. Only impl_style=rtl", "templates.ip_package_tcl self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] # note: setting the root", "/ 8192) elif W <= 4: return (math.ceil(depth / 4096))", "ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, #", "StreamingFIFOs are inserted in between fpgadataflow nodes # the folded", "shutil import copy import subprocess import math import warnings from", "return 0 else: return (math.ceil(depth / 4096)) * (math.ceil(W /", "impl == \"rtl\" or (impl == \"vivado\" and ram_type !=", "and binary forms, with or without # modification, are permitted", "clk): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name )", "names of its # contributors may be used to endorse", "achieve this the two inner dimensions are multiplied # and", "%s/fifo/S_AXIS] \" \"[get_bd_intf_pins %s/%s]\" % (node_name, node_name, din_name) ) cmd.append(", "self.get_nodeattr(\"code_gen_dir_ipgen\") # create a npy file for the input of", "source code must retain the above copyright notice, this #", "\"{}_{}\".format(self.onnx_node.name, self.onnx_node.name) ] # make instream width a multiple of", "self.get_nodeattr(\"depth\") W = self.get_instream_width() if impl == \"rtl\" or (impl", "code_gen_dir, self.onnx_node.name ) # prepare the IP packaging tcl template", "I -type rst /%s/%s\" % (node_name, rst_name)) cmd.append( \"create_bd_intf_pin -mode", "OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON", "Toggle between hls or IPI implementation # rtl - use", ") # prepare the IP packaging tcl template template =", "== \"rtl\" or (impl == \"vivado\" and ram_type != \"block\"):", "# * Neither the name of FINN nor the names", "\"folded_shape\": (\"ints\", True, []), # FINN DataTypes for inputs/outputs \"dataType\":", "SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)", "written permission. # # THIS SOFTWARE IS PROVIDED BY THE", "= \"xilinx.com:hls:%s:1.0\" % (self.onnx_node.name) self.set_nodeattr(\"ip_vlnv\", vlnv) self.code_gen_dict.clear() def get_normal_input_shape(self): depth", "between fpgadataflow nodes # the folded shape could be for", "WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE", "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import", "stitching # vivado - use the AXI Infrastructure FIFO \"impl_style\":", "= 0 return int(address_luts + ram_luts) def prepare_rtlsim(self): assert self.get_nodeattr(\"impl_style\")", "other materials provided with the distribution. # # * Neither", "self.get_nodeattr(\"folded_shape\") in_width = folded_shape[-1] * dtype.bitwidth() return in_width def execute_node(self,", "inp = context[node.input[0]] exp_shape = self.get_normal_input_shape() if mode == \"cppsim\":", "software without specific prior written permission. # # THIS SOFTWARE", "\"cppsim\": output = inp output = np.asarray([output], dtype=np.float32).reshape(*exp_shape) context[node.output[0]] =", "[\".\"] for key in self.code_gen_dict: # transform list into long", "for efficient SRL implementation\" ) # derive normal shape from", "dictionary for new entries self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] self.code_gen_dict[\"$LAYER_NAME$\"] =", "array reshaped_input = reshaped_input.copy() np.save(os.path.join(code_gen_dir, \"input_0.npy\"), reshaped_input) sim = self.get_rtlsim()", "implement tensor with correct shape values = np.random.randn(*oshape).astype(np.float32) return helper.make_node(", "odt.bitwidth() packed_bits = self.get_outstream_width() out_npy_path = \"{}/output.npy\".format(code_gen_dir) out_shape = self.get_folded_output_shape()", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "%s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aresetn]\" % (node_name, rst_name, node_name) ) cmd.append(", "BRAM # distributed -- use LUTRAM # ultra -- use", "list into long string separated by '\\n' code_gen_line = \"\\n\".join(self.code_gen_dict[key])", "= [] # create the normal_ishape for i in range(len(folded_shape)", "datatype is not float32 as expected.\"\"\" expected_inp_shape = self.get_folded_input_shape() reshaped_input", "-dir I -type clk /%s/%s\" % (node_name, clk_name)) cmd.append(\"create_bd_pin -dir", "# make instream width a multiple of 8 for axi", "TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "cmd.append( \"create_bd_intf_pin -mode Slave \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name,", "npy_to_rtlsim_input, rtlsim_output_to_npy from . import templates class StreamingFIFO(HLSCustomOp): def __init__(self,", "example (1, nf, pe) # with nf (neuron folding): mh", "estimation for BRAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth", "self.get_instream_width() bram16_est = self.bram_estimation() if bram16_est == 0: return 1", "tensor with correct shape values = np.random.randn(*oshape).astype(np.float32) return helper.make_node( \"Constant\",", "!= \"block\"): # Non-BRAM based implementation return 0 if W", "for LUTs\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth =", "# this software without specific prior written permission. # #", "between hls or IPI implementation # rtl - use the", "class StreamingFIFO(HLSCustomOp): def __init__(self, onnx_node): super().__init__(onnx_node) self.strm_fifo_wrapper = templates.strm_fifo_wrapper def", "-mode Master \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, dout_name) )", "math.ceil(math.log(depth, 2)) if impl == \"rtl\" or (impl == \"vivado\"", "self.get_nodeattr(\"ram_style\") # create a hierarchy for this layer, with the", "== \"distributed\"): ram_luts = (math.ceil(depth / 32)) * (math.ceil(W /", "(node_name, rst_name)) cmd.append( \"create_bd_intf_pin -mode Master \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\"", "Redistributions of source code must retain the above copyright notice,", "% (node.name) return prefixed_top_name def code_generation_ipgen(self, model, fpgapart, clk): code_gen_dir", "= self.get_nodeattr(\"code_gen_dir_ipgen\") # create a npy file for the input", ") cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aclk]\" % (node_name,", "OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT", "if W == 1: return math.ceil(depth / 16384) elif W", "from shutil import copy import subprocess import math import warnings", "# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "* depth bram16_est_capacity = bram16_est * 36 * 512 return", "the root dir as absolute can cause path problems #", "setting the root dir as absolute can cause path problems", "- 1).bit_length() self.code_gen_dict[\"$COUNT_RANGE$\"] = [\"[{}:0]\".format(count_width - 1)] self.code_gen_dict[\"$IN_RANGE$\"] = [\"[{}:0]\".format(in_width", "assert ( str(inp.dtype) == \"float32\" ), \"\"\"Input datatype is not", "node_name ) cmd.append( \"set_property -dict [list CONFIG.FIFO_DEPTH {%d}] \" \"[get_bd_cells", "verilog_dir) vlnv = \"xilinx.com:hls:%s:1.0\" % (self.onnx_node.name) self.set_nodeattr(\"ip_vlnv\", vlnv) self.code_gen_dict.clear() def", "\"dataType\": (\"s\", True, \"\"), # Toggle between hls or IPI", "{}\\n\".format(verilog_dir)) f.write(\"vivado -mode batch -source package_ip.tcl\\n\") f.write(\"cd {}\\n\".format(working_dir)) bash_command =", "dataoutstrm(self): pass def save_as_npy(self): pass def blackboxfunction(self): pass def pragmas(self):", "fpgapart, clk): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name", "% (node_name, clk_name)) cmd.append(\"create_bd_pin -dir I -type rst /%s/%s\" %", "\"\"\"Input datatype is not float32 as expected.\"\"\" expected_inp_shape = self.get_folded_input_shape()", "if depth > 256 and self.get_nodeattr(\"impl_style\") == \"rtl\": warnings.warn( \"Depth", "key in self.code_gen_dict: # transform list into long string separated", "= \"{}/output.npy\".format(code_gen_dir) out_shape = self.get_folded_output_shape() rtlsim_output_to_npy( output, out_npy_path, odt, out_shape,", "nor the names of its # contributors may be used", "too low\"\"\" if depth > 256 and self.get_nodeattr(\"impl_style\") == \"rtl\":", "to: {} has to be set to one of the", "auto -- let Vivado decide # block -- use BRAM", "= model.get_tensor_datatype(node.input[0]) if idt != self.get_input_datatype(): warn_str = \"inputDataType changing", "the normal input shape folded_shape = self.get_nodeattr(\"folded_shape\") # extract inner", "# rtl - use the hls generated IP during stitching", "self.get_folded_input_shape() reshaped_input = inp.reshape(expected_inp_shape) if DataType[self.get_nodeattr(\"dataType\")] == DataType.BIPOLAR: # store", "and 256 with the current # StreamingFIFO implementation assert depth", "BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF", "\"vivado\", ( \"StreamingFIFO impl_style \" \"cannot be vivado for rtlsim.", "def get_outstream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\") in_width =", "code gen dictionary for new entries self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)]", "= subprocess.Popen(bash_command, stdout=subprocess.PIPE) process_compile.communicate() # set ipgen_path and ip_path to", "data type stays the same model.set_tensor_datatype(node.output[0], idt) def verify_node(self): pass", "= tuple(model.get_tensor_shape(self.onnx_node.input[0])) assert ishape == tuple(exp_ishape), \"Unexpect input shape for", "and together with all previous dimensions # this gives the", "or (impl == \"vivado\" and ram_type != \"ultra\"): # Non-BRAM", "AXI Infrastructure FIFO \"impl_style\": (\"s\", False, \"rtl\", {\"rtl\", \"vivado\"}), #", "'\\n' code_gen_line = \"\\n\".join(self.code_gen_dict[key]) template = template.replace(key, code_gen_line) f =", "\"rtl\" or (impl == \"vivado\" and ram_type != \"ultra\"): #", "DataType[self.get_nodeattr(\"dataType\")] == DataType.BIPOLAR: # store bipolar activations as binary reshaped_input", "ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER", "FIFO \"impl_style\": (\"s\", False, \"rtl\", {\"rtl\", \"vivado\"}), # FPGA resource", "generated IP during stitching # vivado - use the AXI", "import npy_to_rtlsim_input, rtlsim_output_to_npy from . import templates class StreamingFIFO(HLSCustomOp): def", "form must reproduce the above copyright notice, # this list", "as np from shutil import copy import subprocess import math", "+ 1) / 2 export_idt = DataType.BINARY else: export_idt =", "outputs=[self.onnx_node.output[0]], value=helper.make_tensor( name=\"const_tensor\", data_type=TensorProto.FLOAT, dims=values.shape, vals=values.flatten().astype(float), ), ) def infer_node_datatype(self,", "CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,", "[list CONFIG.FIFO_MEMORY_TYPE {%s}] \" \"[get_bd_cells /%s/fifo]\" % (ram_style, node_name) )", "cmd.append( \"set_property -dict [list CONFIG.FIFO_MEMORY_TYPE {%s}] \" \"[get_bd_cells /%s/fifo]\" %", "elif impl_style == \"vivado\": cmd = [] node_name = self.onnx_node.name", "dout_name) ) cmd.append( \"create_bd_intf_pin -mode Slave \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\"", "return 1 wbits = W * depth bram16_est_capacity = bram16_est", "2: return math.ceil(depth / 8192) elif W <= 4: return", "= np.asarray([output], dtype=np.float32).reshape(*exp_shape) context[node.output[0]] = output elif mode == \"rtlsim\":", "rst_name = self.get_verilog_top_module_intf_names()[\"rst\"][0] dout_name = self.get_verilog_top_module_intf_names()[\"m_axis\"][0][0] din_name = self.get_verilog_top_module_intf_names()[\"s_axis\"][0][0] cmd.append(\"create_bd_cell", "1)] self.code_gen_dict[\"$OUT_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$WIDTH$\"] = [str(in_width)] self.code_gen_dict[\"$DEPTH$\"]", "f = open(os.path.join(verilog_dir, \"package_ip.tcl\"), \"w\") f.write(template) f.close() # create a", "# contributors may be used to endorse or promote products", "nbits = self.get_instream_width() inp = npy_to_rtlsim_input( \"{}/input_0.npy\".format(code_gen_dir), export_idt, nbits )", "== \"vivado\": cmd = [] node_name = self.onnx_node.name depth =", "when impl_style is vivado # auto -- let Vivado decide", "self.get_nodeattr(\"impl_style\") if impl_style == \"rtl\": return super().code_generation_ipi() elif impl_style ==", "return math.ceil(depth / 8192) elif W <= 4: return (math.ceil(depth", "\"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, din_name) ) # instantiate and", "be between 2 and 256 with the current # StreamingFIFO", "infer_node_datatype(self, model): node = self.onnx_node idt = model.get_tensor_datatype(node.input[0]) if idt", "self.get_nodeattr(\"folded_shape\") in_width = folded_shape[-1] * dtype.bitwidth() return in_width def get_outstream_width(self):", "dtype=np.float32).reshape(*oshape) context[node.output[0]] = output else: raise Exception( \"\"\"Invalid value for", "[ \"{}_{}\".format(self.onnx_node.name, self.onnx_node.name) ] # make instream width a multiple", "pe # the normal input shape is in this case", "normal input shape is in this case (1, mh) #", "\" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, din_name) ) # instantiate", "* (math.ceil(W / 18)) else: return (math.ceil(depth / 512)) *", "execute_node(self, context, graph): mode = self.get_nodeattr(\"exec_mode\") node = self.onnx_node inp", "self.set_nodeattr(\"ipgen_path\", verilog_dir) self.set_nodeattr(\"ip_path\", verilog_dir) vlnv = \"xilinx.com:hls:%s:1.0\" % (self.onnx_node.name) self.set_nodeattr(\"ip_vlnv\",", "\"w\") as f: f.write(\"#!/bin/bash \\n\") f.write(\"cd {}\\n\".format(verilog_dir)) f.write(\"vivado -mode batch", "the AXI Infrastructure FIFO \"impl_style\": (\"s\", False, \"rtl\", {\"rtl\", \"vivado\"}),", "\"\"\"Depth is too low\"\"\" if depth > 256 and self.get_nodeattr(\"impl_style\")", "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES", "folded_shape[-1] * dtype.bitwidth() return in_width def get_outstream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")]", "node_name) ) cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aclk]\" %", "{\"auto\", \"block\", \"distributed\", \"ultra\"}, ), } my_attrs.update(super().get_nodeattr_types()) return my_attrs def", "new packaged IP self.set_nodeattr(\"ipgen_path\", verilog_dir) self.set_nodeattr(\"ip_path\", verilog_dir) vlnv = \"xilinx.com:hls:%s:1.0\"", "(node_name, rst_name, node_name) ) cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins", "output = np.asarray([output], dtype=np.float32).reshape(*exp_shape) context[node.output[0]] = output elif mode ==", "# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL", "0 else: return (math.ceil(depth / 4096)) * (math.ceil(W / 72))", "f.close() # create a shell script and call Vivado to", "must retain the above copyright notice, this # list of", "context[node.input[0]] exp_shape = self.get_normal_input_shape() if mode == \"cppsim\": output =", "Vivado decide # block -- use BRAM # distributed --", "is not float32 as expected.\"\"\" expected_inp_shape = self.get_folded_input_shape() reshaped_input =", "def get_verilog_top_module_name(self): \"Return the Verilog top module name for this", "FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT", "* (math.ceil(W / 36)) def uram_estimation(self): \"\"\"Calculates resource estimation for", "the following disclaimer in the documentation # and/or other materials", "# with nf (neuron folding): mh // pe # the", "self.get_normal_output_shape() output = np.asarray([output], dtype=np.float32).reshape(*oshape) context[node.output[0]] = output else: raise", "inputs/outputs \"dataType\": (\"s\", True, \"\"), # Toggle between hls or", "implementation\" ) # derive normal shape from folded shape #", "# * Redistributions in binary form must reproduce the above", "nf, pe) # with nf (neuron folding): mh // pe", "(math.ceil(depth / 512)) * (math.ceil(W / 36)) def uram_estimation(self): \"\"\"Calculates", ") super().reset_rtlsim(sim) super().toggle_clk(sim) output = self.rtlsim(sim, inp) odt = DataType[self.get_nodeattr(\"dataType\")]", "= self.onnx_node inp = context[node.input[0]] exp_shape = self.get_normal_input_shape() if mode", "= DataType.BINARY else: export_idt = DataType[self.get_nodeattr(\"dataType\")] # make copy before", "[get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aresetn]\" % (node_name, rst_name, node_name) )", "implementation return 0 if W == 1: return math.ceil(depth /", "nbits ) super().reset_rtlsim(sim) super().toggle_clk(sim) output = self.rtlsim(sim, inp) odt =", "rtl - use the hls generated IP during stitching #", "[str(self.get_nodeattr(\"depth\"))] template = self.strm_fifo_wrapper for key in self.code_gen_dict: # transform", "# multiply with the next inner dimension folding_factor = folded_shape[-2]", "/%s/fifo\" % node_name ) cmd.append( \"set_property -dict [list CONFIG.FIFO_DEPTH {%d}]", "cause path problems # the ipgen script will be invoked", "get_normal_input_shape(self): depth = self.get_nodeattr(\"depth\") # depth has to be between", "Slave \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, din_name) ) #", "the new packaged IP self.set_nodeattr(\"ipgen_path\", verilog_dir) self.set_nodeattr(\"ip_path\", verilog_dir) vlnv =", "%s: %s -> %s \" % ( node.name, str(self.get_input_datatype()), str(idt),", "\"create_bd_cell -type ip \" \"-vlnv xilinx.com:ip:axis_data_fifo:2.0 /%s/fifo\" % node_name )", "(np.ceil(self.get_outstream_width() / 8), node_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/M_AXIS] \"", "if impl == \"rtl\" or (impl == \"vivado\" and ram_type", "= DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\") in_width = folded_shape[-1] * dtype.bitwidth()", "in_width = folded_shape[-1] * dtype.bitwidth() return in_width def get_outstream_width(self): dtype", "self.code_gen_dict[\"$VERILOG_DIR$\"] = [\".\"] for key in self.code_gen_dict: # transform list", "code_gen_line) f = open(os.path.join(verilog_dir, \"package_ip.tcl\"), \"w\") f.write(template) f.close() # create", "specific prior written permission. # # THIS SOFTWARE IS PROVIDED", "folded shape of input/output \"folded_shape\": (\"ints\", True, []), # FINN", "exec_mode! Is currently set to: {} has to be set", "out_npy_path = \"{}/output.npy\".format(code_gen_dir) out_shape = self.get_folded_output_shape() rtlsim_output_to_npy( output, out_npy_path, odt,", "# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE", "get_nodeattr_types(self): my_attrs = { # FIFO depth \"depth\": (\"i\", True,", "% impl_style ) def bram_estimation(self): \"\"\"Calculates resource estimation for BRAM\"\"\"", "URAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\")", "provided that the following conditions are met: # # *", "math.ceil(depth / 16384) elif W == 2: return math.ceil(depth /", "* (math.ceil(W / 2)) else: ram_luts = 0 return int(address_luts", "this node.\" node = self.onnx_node prefixed_top_name = \"%s\" % (node.name)", "above copyright notice, this # list of conditions and the", "self.get_rtlsim() nbits = self.get_instream_width() inp = npy_to_rtlsim_input( \"{}/input_0.npy\".format(code_gen_dir), export_idt, nbits", "vals=values.flatten().astype(float), ), ) def infer_node_datatype(self, model): node = self.onnx_node idt", "= [] node_name = self.onnx_node.name depth = self.get_nodeattr(\"depth\") ram_style =", "pe) # with nf (neuron folding): mh // pe #", "folded_shape[-1] * dtype.bitwidth() return in_width def execute_node(self, context, graph): mode", "reshaped_input) sim = self.get_rtlsim() nbits = self.get_instream_width() inp = npy_to_rtlsim_input(", "store bipolar activations as binary reshaped_input = (reshaped_input + 1)", "= self.get_normal_output_shape() output = np.asarray([output], dtype=np.float32).reshape(*oshape) context[node.output[0]] = output else:", "nf (neuron folding): mh // pe # the normal input", "\"auto\", {\"auto\", \"block\", \"distributed\", \"ultra\"}, ), } my_attrs.update(super().get_nodeattr_types()) return my_attrs", "= templates.ip_package_tcl self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] # note: setting the", "%s/fifo/s_axis_aclk]\" % (node_name, clk_name, node_name) ) return cmd else: raise", "4096)) * (math.ceil(W / 4)) elif W <= 9: return", "\"-vlnv xilinx.com:ip:axis_data_fifo:2.0 /%s/fifo\" % node_name ) cmd.append( \"set_property -dict [list", "HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER", "inserted in between fpgadataflow nodes # the folded shape could", ") cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/S_AXIS] \" \"[get_bd_intf_pins %s/%s]\" % (node_name,", "= open(os.path.join(verilog_dir, \"{}.v\".format(self.onnx_node.name)), \"w\") f.write(template) f.close() self.code_gen_dict.clear() def ipgen_singlenode_code(self): code_gen_dir", "4096)) * (math.ceil(W / 72)) def bram_efficiency_estimation(self): depth = self.get_nodeattr(\"depth\")", "style %s not supported, please use rtl or vivado\" %", "call Vivado to invoke the IP pkg script make_project_sh =", "1) / 2 export_idt = DataType.BINARY else: export_idt = DataType[self.get_nodeattr(\"dataType\")]", "* Redistributions of source code must retain the above copyright", "folding_factor = folded_shape[-2] * inner_dim normal_ishape = [] # create", "/%s/%s\" % (node_name, dout_name) ) cmd.append( \"create_bd_intf_pin -mode Slave \"", "could be for example (1, nf, pe) # with nf", "be invoked from the sources dir so root_dir=. is OK", "reshaped_input = (reshaped_input + 1) / 2 export_idt = DataType.BINARY", ") cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/M_AXIS] \" \"[get_bd_intf_pins %s/%s]\" % (node_name,", "IP during stitching # vivado - use the AXI Infrastructure", "input shape is in this case (1, mh) # so", ". import templates class StreamingFIFO(HLSCustomOp): def __init__(self, onnx_node): super().__init__(onnx_node) self.strm_fifo_wrapper", "memstream_dir = \"/workspace/finn/finn-rtllib/memstream/hdl/\" Q_file = os.path.join(memstream_dir, \"Q_srl.v\") copy(Q_file, verilog_dir) #", "is too low\"\"\" if depth > 256 and self.get_nodeattr(\"impl_style\") ==", "= folded_shape[-1] # multiply with the next inner dimension folding_factor", "axi interface in_width = self.get_instream_width_padded() count_width = int(self.get_nodeattr(\"depth\") - 1).bit_length()", "rst /%s/%s\" % (node_name, rst_name)) cmd.append( \"create_bd_intf_pin -mode Master \"", "/ 9)) elif W <= 18 or depth > 512:", "{}\\n\".format(working_dir)) bash_command = [\"bash\", make_project_sh] process_compile = subprocess.Popen(bash_command, stdout=subprocess.PIPE) process_compile.communicate()", "-dict [list CONFIG.FIFO_MEMORY_TYPE {%s}] \" \"[get_bd_cells /%s/fifo]\" % (ram_style, node_name)", "or promote products derived from # this software without specific", "// pe # the normal input shape is in this", "between 2 and 256 with the current # StreamingFIFO implementation", "OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA,", "changing for %s: %s -> %s \" % ( node.name,", "idt.name) # data type stays the same model.set_tensor_datatype(node.output[0], idt) def", "ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES", "-mode batch -source package_ip.tcl\\n\") f.write(\"cd {}\\n\".format(working_dir)) bash_command = [\"bash\", make_project_sh]", ") ) def get_number_output_values(self): folded_oshape = self.get_folded_output_shape() return np.prod(folded_oshape[:-1]) def", "self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] self.code_gen_dict[\"$LAYER_NAME$\"] = [ \"{}_{}\".format(self.onnx_node.name, self.onnx_node.name) ]", "extract inner dimension inner_dim = folded_shape[-1] # multiply with the", "/%s/fifo]\" % (ram_style, node_name) ) cmd.append( \"set_property -dict [list CONFIG.TDATA_NUM_BYTES", "INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF", "def save_as_npy(self): pass def blackboxfunction(self): pass def pragmas(self): pass def", "in range(len(folded_shape) - 2): normal_ishape.append(folded_shape[i]) normal_ishape.append(folding_factor) return normal_ishape def get_normal_output_shape(self):", "== 2: return math.ceil(depth / 8192) elif W <= 4:", "input/output \"folded_shape\": (\"ints\", True, []), # FINN DataTypes for inputs/outputs", "promote products derived from # this software without specific prior", "inner dimension folding_factor = folded_shape[-2] * inner_dim normal_ishape = []", "\"vivado\"}), # FPGA resource type for FIFOs when impl_style is", "npy file for the input of the node assert (", "\"inputDataType changing for %s: %s -> %s \" % (", "(math.ceil(W / 2)) else: ram_luts = 0 return int(address_luts +", "template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir, \"package_ip.tcl\"), \"w\") f.write(template) f.close() #", "W <= 18 or depth > 512: return (math.ceil(depth /", "(node_name, node_name, din_name) ) cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins", "W = self.get_instream_width() bram16_est = self.bram_estimation() if bram16_est == 0:", "\"/make_ip.sh\" working_dir = os.environ[\"PWD\"] with open(make_project_sh, \"w\") as f: f.write(\"#!/bin/bash", "self.onnx_node.name depth = self.get_nodeattr(\"depth\") ram_style = self.get_nodeattr(\"ram_style\") # create a", "def execute_node(self, context, graph): mode = self.get_nodeattr(\"exec_mode\") node = self.onnx_node", "assert self.get_nodeattr(\"impl_style\") != \"vivado\", ( \"StreamingFIFO impl_style \" \"cannot be", "shape values = np.random.randn(*oshape).astype(np.float32) return helper.make_node( \"Constant\", inputs=[], outputs=[self.onnx_node.output[0]], value=helper.make_tensor(", "(reshaped_input + 1) / 2 export_idt = DataType.BINARY else: export_idt", "All rights reserved. # # Redistribution and use in source", "CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF", "xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, din_name) ) # instantiate and configure", "BRAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\")", "\"\"\"Invalid value for attribute exec_mode! Is currently set to: {}", "impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\") W", "(node_name, clk_name, node_name) ) return cmd else: raise Exception( \"FIFO", "[\"{}\".format(self.onnx_node.name)] self.code_gen_dict[\"$LAYER_NAME$\"] = [ \"{}_{}\".format(self.onnx_node.name, self.onnx_node.name) ] # make instream", "dtype.bitwidth() return in_width def execute_node(self, context, graph): mode = self.get_nodeattr(\"exec_mode\")", "implementation return 0 else: return (math.ceil(depth / 4096)) * (math.ceil(W", "FIFO depth \"depth\": (\"i\", True, 0), # folded shape of", "used to endorse or promote products derived from # this", "correct shape values = np.random.randn(*oshape).astype(np.float32) return helper.make_node( \"Constant\", inputs=[], outputs=[self.onnx_node.output[0]],", "the two inner dimensions are multiplied # and together with", "LUTRAM # ultra -- use URAM (on UltraScale+) \"ram_style\": (", "self.get_nodeattr(\"depth\") W = self.get_instream_width() address_luts = 2 * math.ceil(math.log(depth, 2))", "get_folded_output_shape(self): return self.get_nodeattr(\"folded_shape\") def get_instream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape =", "1)] self.code_gen_dict[\"$WIDTH$\"] = [str(in_width)] self.code_gen_dict[\"$DEPTH$\"] = [str(self.get_nodeattr(\"depth\"))] template = self.strm_fifo_wrapper", "code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) #", "% node_name ) cmd.append( \"set_property -dict [list CONFIG.FIFO_DEPTH {%d}] \"", "# FINN DataTypes for inputs/outputs \"dataType\": (\"s\", True, \"\"), #", "rst_name, node_name) ) cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aclk]\"", "distribution. # # * Neither the name of FINN nor", "FINN DataTypes for inputs/outputs \"dataType\": (\"s\", True, \"\"), # Toggle", "self.bram_estimation() if bram16_est == 0: return 1 wbits = W", "depth \"depth\": (\"i\", True, 0), # folded shape of input/output", "hls generated IP during stitching # vivado - use the", "dout_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/S_AXIS] \" \"[get_bd_intf_pins %s/%s]\" %", "\"[get_bd_intf_pins %s/%s]\" % (node_name, node_name, dout_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins", "= templates.strm_fifo_wrapper def get_nodeattr_types(self): my_attrs = { # FIFO depth", "folded_shape[-2] * inner_dim normal_ishape = [] # create the normal_ishape", "rst_name)) cmd.append( \"create_bd_intf_pin -mode Master \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" %", "= self.get_nodeattr(\"depth\") W = self.get_instream_width() if impl == \"rtl\" or", "npy_to_rtlsim_input( \"{}/input_0.npy\".format(code_gen_dir), export_idt, nbits ) super().reset_rtlsim(sim) super().toggle_clk(sim) output = self.rtlsim(sim,", "= self.get_folded_output_shape() return np.prod(folded_oshape[:-1]) def global_includes(self): pass def defines(self, var):", "copy Q_srl.v from finn-rtllib to verilog directory memstream_dir = \"/workspace/finn/finn-rtllib/memstream/hdl/\"", "# * Redistributions of source code must retain the above", "\"package_ip.tcl\"), \"w\") f.write(template) f.close() # create a shell script and", "/%s/%s\" % (node_name, rst_name)) cmd.append( \"create_bd_intf_pin -mode Master \" \"-vlnv", "to point to the new packaged IP self.set_nodeattr(\"ipgen_path\", verilog_dir) self.set_nodeattr(\"ip_path\",", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"", "\"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, dout_name) ) cmd.append( \"create_bd_intf_pin -mode", "export_idt, nbits ) super().reset_rtlsim(sim) super().toggle_clk(sim) output = self.rtlsim(sim, inp) odt", "* 512 return wbits / bram16_est_capacity def lut_estimation(self): \"\"\"Calculates resource", "input of the node assert ( str(inp.dtype) == \"float32\" ),", "STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING", "\"impl_style\": (\"s\", False, \"rtl\", {\"rtl\", \"vivado\"}), # FPGA resource type", ") cmd.append( \"create_bd_intf_pin -mode Slave \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" %", "256 for efficient SRL implementation\" ) # derive normal shape", "context, graph): mode = self.get_nodeattr(\"exec_mode\") node = self.onnx_node inp =", "from finn.core.datatype import DataType from onnx import TensorProto, helper from", "note: setting the root dir as absolute can cause path", "let Vivado decide # block -- use BRAM # distributed", "to endorse or promote products derived from # this software", "def pragmas(self): pass def code_generation_ipi(self): impl_style = self.get_nodeattr(\"impl_style\") if impl_style", "return int(address_luts + ram_luts) def prepare_rtlsim(self): assert self.get_nodeattr(\"impl_style\") != \"vivado\",", "the normal input shape is in this case (1, mh)", "\"\"\"Calculates resource estimation for URAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type =", "from finn.util.data_packing import npy_to_rtlsim_input, rtlsim_output_to_npy from . import templates class", "\"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) # prepare the IP packaging tcl", "self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\") W = self.get_instream_width()", "BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY", "its # contributors may be used to endorse or promote", "INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY,", "StreamingFIFO.\" # implement tensor with correct shape values = np.random.randn(*oshape).astype(np.float32)", "or IPI implementation # rtl - use the hls generated", "in_width def execute_node(self, context, graph): mode = self.get_nodeattr(\"exec_mode\") node =", "a multiple of 8 for axi interface in_width = self.get_instream_width_padded()", "INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT", "- use the AXI Infrastructure FIFO \"impl_style\": (\"s\", False, \"rtl\",", "exp_ishape = self.get_normal_input_shape() oshape = self.get_normal_output_shape() ishape = tuple(model.get_tensor_shape(self.onnx_node.input[0])) assert", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS", "verilog directory memstream_dir = \"/workspace/finn/finn-rtllib/memstream/hdl/\" Q_file = os.path.join(memstream_dir, \"Q_srl.v\") copy(Q_file,", "IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os", "= self.get_instream_width() inp = npy_to_rtlsim_input( \"{}/input_0.npy\".format(code_gen_dir), export_idt, nbits ) super().reset_rtlsim(sim)", "of its # contributors may be used to endorse or", "dtype=np.float32).reshape(*exp_shape) context[node.output[0]] = output elif mode == \"rtlsim\": code_gen_dir =", "self.code_gen_dict[\"$LAYER_NAME$\"] = [ \"{}_{}\".format(self.onnx_node.name, self.onnx_node.name) ] # make instream width", "for StreamingFIFO.\" # implement tensor with correct shape values =", "# depth has to be between 2 and 256 with", "separated by '\\n' code_gen_line = \"\\n\".join(self.code_gen_dict[key]) template = template.replace(key, code_gen_line)", "bipolar activations as binary reshaped_input = (reshaped_input + 1) /", "THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A", ") # derive normal shape from folded shape # StreamingFIFOs", "import subprocess import math import warnings from finn.custom_op.fpgadataflow.hlscustomop import HLSCustomOp", "absolute can cause path problems # the ipgen script will", "output output = np.load(out_npy_path) oshape = self.get_normal_output_shape() output = np.asarray([output],", "( str(inp.dtype) == \"float32\" ), \"\"\"Input datatype is not float32", ") def infer_node_datatype(self, model): node = self.onnx_node idt = model.get_tensor_datatype(node.input[0])", "DataType[self.get_nodeattr(\"dataType\")] # make copy before saving the array reshaped_input =", "resource estimations for LUTs\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\")", "same model.set_tensor_datatype(node.output[0], idt) def verify_node(self): pass def get_verilog_top_module_name(self): \"Return the", "dimension inner_dim = folded_shape[-1] # multiply with the next inner", "import HLSCustomOp from finn.core.datatype import DataType from onnx import TensorProto,", "# this gives the normal input shape folded_shape = self.get_nodeattr(\"folded_shape\")", "= self.get_nodeattr(\"ram_style\") # create a hierarchy for this layer, with", "import warnings from finn.custom_op.fpgadataflow.hlscustomop import HLSCustomOp from finn.core.datatype import DataType", "values = np.random.randn(*oshape).astype(np.float32) return helper.make_node( \"Constant\", inputs=[], outputs=[self.onnx_node.output[0]], value=helper.make_tensor( name=\"const_tensor\",", "to one of the following value (\"cppsim\", \"rtlsim\")\"\"\".format( mode )", "\"w\") f.write(template) f.close() # create a shell script and call", "self.get_normal_input_shape() oshape = self.get_normal_output_shape() ishape = tuple(model.get_tensor_shape(self.onnx_node.input[0])) assert ishape ==", "dimension folding_factor = folded_shape[-2] * inner_dim normal_ishape = [] #", "\"block\", \"distributed\", \"ultra\"}, ), } my_attrs.update(super().get_nodeattr_types()) return my_attrs def make_shape_compatible_op(self,", "/%s/fifo]\" % (np.ceil(self.get_outstream_width() / 8), node_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins", "process_compile.communicate() # set ipgen_path and ip_path to point to the", "f.write(\"#!/bin/bash \\n\") f.write(\"cd {}\\n\".format(verilog_dir)) f.write(\"vivado -mode batch -source package_ip.tcl\\n\") f.write(\"cd", "the normal_ishape for i in range(len(folded_shape) - 2): normal_ishape.append(folded_shape[i]) normal_ishape.append(folding_factor)", "- 1)] self.code_gen_dict[\"$IN_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$OUT_RANGE$\"] = [\"[{}:0]\".format(in_width", "get_outstream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\") in_width = folded_shape[-1]", "return math.ceil(depth / 16384) elif W == 2: return math.ceil(depth", "resource estimation for URAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\")", "EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO,", "= bram16_est * 36 * 512 return wbits / bram16_est_capacity", "= self.get_folded_output_shape() rtlsim_output_to_npy( output, out_npy_path, odt, out_shape, packed_bits, target_bits )", "root_dir=. is OK self.code_gen_dict[\"$VERILOG_DIR$\"] = [\".\"] for key in self.code_gen_dict:", "must reproduce the above copyright notice, # this list of", "normal_ishape.append(folded_shape[i]) normal_ishape.append(folding_factor) return normal_ishape def get_normal_output_shape(self): return self.get_normal_input_shape() def get_folded_input_shape(self):", "return (math.ceil(depth / 2048)) * (math.ceil(W / 9)) elif W", "!= \"ultra\"): # Non-BRAM based implementation return 0 else: return", "0: return 1 wbits = W * depth bram16_est_capacity =", "from finn-rtllib to verilog directory memstream_dir = \"/workspace/finn/finn-rtllib/memstream/hdl/\" Q_file =", "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT", "templates.strm_fifo_wrapper def get_nodeattr_types(self): my_attrs = { # FIFO depth \"depth\":", ") cmd.append( \"set_property -dict [list CONFIG.TDATA_NUM_BYTES {%d}] \" \"[get_bd_cells /%s/fifo]\"", "A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL", ") cmd.append( \"set_property -dict [list CONFIG.FIFO_DEPTH {%d}] \" \"[get_bd_cells /%s/fifo]\"", "ishape == tuple(exp_ishape), \"Unexpect input shape for StreamingFIFO.\" # implement", "% (np.ceil(self.get_outstream_width() / 8), node_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/M_AXIS]", "np.prod(folded_oshape[:-1]) def global_includes(self): pass def defines(self, var): pass def read_npy_data(self):", "template = templates.ip_package_tcl self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] # note: setting", "node_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/M_AXIS] \" \"[get_bd_intf_pins %s/%s]\" %", "low\"\"\" if depth > 256 and self.get_nodeattr(\"impl_style\") == \"rtl\": warnings.warn(", "cmd.append(\"create_bd_pin -dir I -type rst /%s/%s\" % (node_name, rst_name)) cmd.append(", "return wbits / bram16_est_capacity def lut_estimation(self): \"\"\"Calculates resource estimations for", "\\n\") f.write(\"cd {}\\n\".format(verilog_dir)) f.write(\"vivado -mode batch -source package_ip.tcl\\n\") f.write(\"cd {}\\n\".format(working_dir))", "folded_shape = self.get_nodeattr(\"folded_shape\") in_width = folded_shape[-1] * dtype.bitwidth() return in_width", "previous dimensions # this gives the normal input shape folded_shape", "wbits / bram16_est_capacity def lut_estimation(self): \"\"\"Calculates resource estimations for LUTs\"\"\"", "if mode == \"cppsim\": output = inp output = np.asarray([output],", "of source code must retain the above copyright notice, this", "from folded shape # StreamingFIFOs are inserted in between fpgadataflow", "SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR", "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED.", "(1, nf, pe) # with nf (neuron folding): mh //", "f.close() self.code_gen_dict.clear() def ipgen_singlenode_code(self): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format(", "AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED", "\"distributed\"): ram_luts = (math.ceil(depth / 32)) * (math.ceil(W / 2))", "for this node.\" node = self.onnx_node prefixed_top_name = \"%s\" %", "depth bram16_est_capacity = bram16_est * 36 * 512 return wbits", "idt != self.get_input_datatype(): warn_str = \"inputDataType changing for %s: %s", "self.get_input_datatype(): warn_str = \"inputDataType changing for %s: %s -> %s", "folded_shape[-1] # multiply with the next inner dimension folding_factor =", "= self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\") W =", "self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() if impl ==", "USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE", "self.code_gen_dict[\"$COUNT_RANGE$\"] = [\"[{}:0]\".format(count_width - 1)] self.code_gen_dict[\"$IN_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)]", "] # make instream width a multiple of 8 for", "# create a npy file for the input of the", "self.get_instream_width() if impl == \"rtl\" or (impl == \"vivado\" and", "rtlsim_output_to_npy from . import templates class StreamingFIFO(HLSCustomOp): def __init__(self, onnx_node):", "names clk_name = self.get_verilog_top_module_intf_names()[\"clk\"][0] rst_name = self.get_verilog_top_module_intf_names()[\"rst\"][0] dout_name = self.get_verilog_top_module_intf_names()[\"m_axis\"][0][0]", "this software without specific prior written permission. # # THIS", "OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY", "== \"vivado\" and ram_type != \"ultra\"): # Non-BRAM based implementation", "process_compile = subprocess.Popen(bash_command, stdout=subprocess.PIPE) process_compile.communicate() # set ipgen_path and ip_path", "and configure DWC cmd.append( \"create_bd_cell -type ip \" \"-vlnv xilinx.com:ip:axis_data_fifo:2.0", "math import warnings from finn.custom_op.fpgadataflow.hlscustomop import HLSCustomOp from finn.core.datatype import", "Master \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, dout_name) ) cmd.append(", "/ 512)) * (math.ceil(W / 36)) def uram_estimation(self): \"\"\"Calculates resource", "be set to one of the following value (\"cppsim\", \"rtlsim\")\"\"\".format(", "# the folded shape could be for example (1, nf,", "* Redistributions in binary form must reproduce the above copyright", "the ipgen script will be invoked from the sources dir", "self.strm_fifo_wrapper for key in self.code_gen_dict: # transform list into long", "finn.custom_op.fpgadataflow.hlscustomop import HLSCustomOp from finn.core.datatype import DataType from onnx import", "= npy_to_rtlsim_input( \"{}/input_0.npy\".format(code_gen_dir), export_idt, nbits ) super().reset_rtlsim(sim) super().toggle_clk(sim) output =", "OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY", "CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,", "else: export_idt = DataType[self.get_nodeattr(\"dataType\")] # make copy before saving the", "\"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "= [ \"{}_{}\".format(self.onnx_node.name, self.onnx_node.name) ] # make instream width a", "str(inp.dtype) == \"float32\" ), \"\"\"Input datatype is not float32 as", "* Neither the name of FINN nor the names of", "W = self.get_instream_width() if impl == \"rtl\" or (impl ==", "* inner_dim normal_ishape = [] # create the normal_ishape for", "based implementation return 0 if W == 1: return math.ceil(depth", "CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES,", "return my_attrs def make_shape_compatible_op(self, model): exp_ishape = self.get_normal_input_shape() oshape =", "= [\"bash\", make_project_sh] process_compile = subprocess.Popen(bash_command, stdout=subprocess.PIPE) process_compile.communicate() # set", "dimensions are multiplied # and together with all previous dimensions", "\"rtl\": return super().code_generation_ipi() elif impl_style == \"vivado\": cmd = []", "= output else: raise Exception( \"\"\"Invalid value for attribute exec_mode!", "# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR", "2020, Xilinx # All rights reserved. # # Redistribution and", "for key in self.code_gen_dict: # transform list into long string", "self.code_gen_dict[\"$DEPTH$\"] = [str(self.get_nodeattr(\"depth\"))] template = self.strm_fifo_wrapper for key in self.code_gen_dict:", "\"set_property -dict [list CONFIG.FIFO_MEMORY_TYPE {%s}] \" \"[get_bd_cells /%s/fifo]\" % (ram_style,", "(impl == \"vivado\" and ram_type != \"block\"): # Non-BRAM based", "self.code_gen_dict: # transform list into long string separated by '\\n'", "cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aclk]\" % (node_name, clk_name,", "[]), # FINN DataTypes for inputs/outputs \"dataType\": (\"s\", True, \"\"),", "nodes # the folded shape could be for example (1,", "/ 4)) elif W <= 9: return (math.ceil(depth / 2048))", "open(os.path.join(verilog_dir, \"package_ip.tcl\"), \"w\") f.write(template) f.close() # create a shell script", "and self.get_nodeattr(\"impl_style\") == \"rtl\": warnings.warn( \"Depth is high, set between", "1)] self.code_gen_dict[\"$IN_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$OUT_RANGE$\"] = [\"[{}:0]\".format(in_width -", "import DataType from onnx import TensorProto, helper from finn.util.data_packing import", "IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE", "or without # modification, are permitted provided that the following", "( \"s\", False, \"auto\", {\"auto\", \"block\", \"distributed\", \"ultra\"}, ), }", "self.code_gen_dict[\"$IN_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$OUT_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)]", "mode == \"cppsim\": output = inp output = np.asarray([output], dtype=np.float32).reshape(*exp_shape)", "HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT,", "shape from folded shape # StreamingFIFOs are inserted in between", "high, set between 2 and 256 for efficient SRL implementation\"", "f = open(os.path.join(verilog_dir, \"{}.v\".format(self.onnx_node.name)), \"w\") f.write(template) f.close() self.code_gen_dict.clear() def ipgen_singlenode_code(self):", "def defines(self, var): pass def read_npy_data(self): pass def strm_decl(self): pass", "= [\".\"] for key in self.code_gen_dict: # transform list into", "CONFIG.FIFO_DEPTH {%d}] \" \"[get_bd_cells /%s/fifo]\" % (depth, node_name) ) cmd.append(", "SRL implementation\" ) # derive normal shape from folded shape", "\" \"cannot be vivado for rtlsim. Only impl_style=rtl supported.\" )", "# prepare the IP packaging tcl template template = templates.ip_package_tcl", "self.get_nodeattr(\"depth\") ram_style = self.get_nodeattr(\"ram_style\") # create a hierarchy for this", "the sources dir so root_dir=. is OK self.code_gen_dict[\"$VERILOG_DIR$\"] = [\".\"]", "onnx import TensorProto, helper from finn.util.data_packing import npy_to_rtlsim_input, rtlsim_output_to_npy from", "\" \"[get_bd_intf_pins %s/%s]\" % (node_name, node_name, dout_name) ) cmd.append( \"connect_bd_intf_net", "super().reset_rtlsim(sim) super().toggle_clk(sim) output = self.rtlsim(sim, inp) odt = DataType[self.get_nodeattr(\"dataType\")] target_bits", "wbits = W * depth bram16_est_capacity = bram16_est * 36", "= self.get_rtlsim() nbits = self.get_instream_width() inp = npy_to_rtlsim_input( \"{}/input_0.npy\".format(code_gen_dir), export_idt,", "in this case (1, mh) # so to achieve this", "= np.random.randn(*oshape).astype(np.float32) return helper.make_node( \"Constant\", inputs=[], outputs=[self.onnx_node.output[0]], value=helper.make_tensor( name=\"const_tensor\", data_type=TensorProto.FLOAT,", "prefixed_top_name = \"%s\" % (node.name) return prefixed_top_name def code_generation_ipgen(self, model,", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL #", "folded_shape = self.get_nodeattr(\"folded_shape\") # extract inner dimension inner_dim = folded_shape[-1]", "StreamingFIFO implementation assert depth >= 2, \"\"\"Depth is too low\"\"\"", "self.get_nodeattr(\"depth\") W = self.get_instream_width() bram16_est = self.bram_estimation() if bram16_est ==", "def __init__(self, onnx_node): super().__init__(onnx_node) self.strm_fifo_wrapper = templates.strm_fifo_wrapper def get_nodeattr_types(self): my_attrs", "and ram_type != \"ultra\"): # Non-BRAM based implementation return 0", "are inserted in between fpgadataflow nodes # the folded shape", "so to achieve this the two inner dimensions are multiplied", "def verify_node(self): pass def get_verilog_top_module_name(self): \"Return the Verilog top module", "\" \"[get_bd_pins %s/fifo/s_axis_aclk]\" % (node_name, clk_name, node_name) ) return cmd", "I -type clk /%s/%s\" % (node_name, clk_name)) cmd.append(\"create_bd_pin -dir I", "name=\"const_tensor\", data_type=TensorProto.FLOAT, dims=values.shape, vals=values.flatten().astype(float), ), ) def infer_node_datatype(self, model): node", "import os import numpy as np from shutil import copy", "out_shape = self.get_folded_output_shape() rtlsim_output_to_npy( output, out_npy_path, odt, out_shape, packed_bits, target_bits", "a shell script and call Vivado to invoke the IP", "empty code gen dictionary for new entries self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] =", "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND", "as f: f.write(\"#!/bin/bash \\n\") f.write(\"cd {}\\n\".format(verilog_dir)) f.write(\"vivado -mode batch -source", "one of the following value (\"cppsim\", \"rtlsim\")\"\"\".format( mode ) )", "use in source and binary forms, with or without #", "def ipgen_singlenode_code(self): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name", "out_npy_path, odt, out_shape, packed_bits, target_bits ) # load and reshape", "self.get_instream_width() inp = npy_to_rtlsim_input( \"{}/input_0.npy\".format(code_gen_dir), export_idt, nbits ) super().reset_rtlsim(sim) super().toggle_clk(sim)", "to invoke the IP pkg script make_project_sh = verilog_dir +", "self.code_gen_dict.clear() def ipgen_singlenode_code(self): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir,", "# create a shell script and call Vivado to invoke", "= self.get_instream_width() address_luts = 2 * math.ceil(math.log(depth, 2)) if impl", "def uram_estimation(self): \"\"\"Calculates resource estimation for URAM\"\"\" impl = self.get_nodeattr(\"impl_style\")", "return self.get_normal_input_shape() def get_folded_input_shape(self): return self.get_nodeattr(\"folded_shape\") def get_folded_output_shape(self): return self.get_nodeattr(\"folded_shape\")", "not supported, please use rtl or vivado\" % impl_style )", "# distributed -- use LUTRAM # ultra -- use URAM", "ram_luts = (math.ceil(depth / 32)) * (math.ceil(W / 2)) else:", "and the following disclaimer. # # * Redistributions in binary", "(node_name, dout_name) ) cmd.append( \"create_bd_intf_pin -mode Slave \" \"-vlnv xilinx.com:interface:axis_rtl:1.0", "and call Vivado to invoke the IP pkg script make_project_sh", "= [\"{}\".format(self.onnx_node.name)] self.code_gen_dict[\"$LAYER_NAME$\"] = [ \"{}_{}\".format(self.onnx_node.name, self.onnx_node.name) ] # make", "<= 18 or depth > 512: return (math.ceil(depth / 1024))", "# note: setting the root dir as absolute can cause", "context[node.output[0]] = output elif mode == \"rtlsim\": code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\")", "COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT,", "set between 2 and 256 for efficient SRL implementation\" )", "point to the new packaged IP self.set_nodeattr(\"ipgen_path\", verilog_dir) self.set_nodeattr(\"ip_path\", verilog_dir)", "# # * Redistributions of source code must retain the", "== tuple(exp_ishape), \"Unexpect input shape for StreamingFIFO.\" # implement tensor", "shape for StreamingFIFO.\" # implement tensor with correct shape values", "clk_name, node_name) ) return cmd else: raise Exception( \"FIFO implementation", "\" \"[get_bd_cells /%s/fifo]\" % (ram_style, node_name) ) cmd.append( \"set_property -dict", "odt, out_shape, packed_bits, target_bits ) # load and reshape output", "\"set_property -dict [list CONFIG.TDATA_NUM_BYTES {%d}] \" \"[get_bd_cells /%s/fifo]\" % (np.ceil(self.get_outstream_width()", "use LUTRAM # ultra -- use URAM (on UltraScale+) \"ram_style\":", "multiple of 8 for axi interface in_width = self.get_instream_width_padded() count_width", "module name for this node.\" node = self.onnx_node prefixed_top_name =", "implementation style %s not supported, please use rtl or vivado\"", "of the following value (\"cppsim\", \"rtlsim\")\"\"\".format( mode ) ) def", "dir so root_dir=. is OK self.code_gen_dict[\"$VERILOG_DIR$\"] = [\".\"] for key", "same port names clk_name = self.get_verilog_top_module_intf_names()[\"clk\"][0] rst_name = self.get_verilog_top_module_intf_names()[\"rst\"][0] dout_name", "# derive normal shape from folded shape # StreamingFIFOs are", "(math.ceil(W / 36)) def uram_estimation(self): \"\"\"Calculates resource estimation for URAM\"\"\"", "open(make_project_sh, \"w\") as f: f.write(\"#!/bin/bash \\n\") f.write(\"cd {}\\n\".format(verilog_dir)) f.write(\"vivado -mode", "\"Depth is high, set between 2 and 256 for efficient", "return normal_ishape def get_normal_output_shape(self): return self.get_normal_input_shape() def get_folded_input_shape(self): return self.get_nodeattr(\"folded_shape\")", "prior written permission. # # THIS SOFTWARE IS PROVIDED BY", "* dtype.bitwidth() return in_width def execute_node(self, context, graph): mode =", "9)) elif W <= 18 or depth > 512: return", "== \"float32\" ), \"\"\"Input datatype is not float32 as expected.\"\"\"", "a hierarchy for this layer, with the same port names", "[\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$OUT_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$WIDTH$\"] =", "Q_file = os.path.join(memstream_dir, \"Q_srl.v\") copy(Q_file, verilog_dir) # empty code gen", "HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR", "\"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aclk]\" % (node_name, clk_name, node_name)", "my_attrs = { # FIFO depth \"depth\": (\"i\", True, 0),", "{\"rtl\", \"vivado\"}), # FPGA resource type for FIFOs when impl_style", "cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aresetn]\" % (node_name, rst_name,", "%s\" % node_name) cmd.append(\"create_bd_pin -dir I -type clk /%s/%s\" %", "+ ram_luts) def prepare_rtlsim(self): assert self.get_nodeattr(\"impl_style\") != \"vivado\", ( \"StreamingFIFO", "get_normal_output_shape(self): return self.get_normal_input_shape() def get_folded_input_shape(self): return self.get_nodeattr(\"folded_shape\") def get_folded_output_shape(self): return", "= self.get_instream_width() if impl == \"rtl\" or (impl == \"vivado\"", "with all previous dimensions # this gives the normal input", "# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS", "%s -> %s \" % ( node.name, str(self.get_input_datatype()), str(idt), )", "mode ) ) def get_number_output_values(self): folded_oshape = self.get_folded_output_shape() return np.prod(folded_oshape[:-1])", "= int(self.get_nodeattr(\"depth\") - 1).bit_length() self.code_gen_dict[\"$COUNT_RANGE$\"] = [\"[{}:0]\".format(count_width - 1)] self.code_gen_dict[\"$IN_RANGE$\"]", "9: return (math.ceil(depth / 2048)) * (math.ceil(W / 9)) elif", "AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT", "read_npy_data(self): pass def strm_decl(self): pass def docompute(self): pass def dataoutstrm(self):", "raise Exception( \"FIFO implementation style %s not supported, please use", "gives the normal input shape folded_shape = self.get_nodeattr(\"folded_shape\") # extract", "if impl_style == \"rtl\": return super().code_generation_ipi() elif impl_style == \"vivado\":", "for new entries self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] self.code_gen_dict[\"$LAYER_NAME$\"] = [", "shape could be for example (1, nf, pe) # with", "self.get_nodeattr(\"exec_mode\") node = self.onnx_node inp = context[node.input[0]] exp_shape = self.get_normal_input_shape()", "DataType[self.get_nodeattr(\"dataType\")] target_bits = odt.bitwidth() packed_bits = self.get_outstream_width() out_npy_path = \"{}/output.npy\".format(code_gen_dir)", "== \"rtl\" or (impl == \"vivado\" and ram_type != \"ultra\"):", "True, []), # FINN DataTypes for inputs/outputs \"dataType\": (\"s\", True,", "\"connect_bd_intf_net [get_bd_intf_pins %s/fifo/M_AXIS] \" \"[get_bd_intf_pins %s/%s]\" % (node_name, node_name, dout_name)", "[get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aclk]\" % (node_name, clk_name, node_name) )", "helper from finn.util.data_packing import npy_to_rtlsim_input, rtlsim_output_to_npy from . import templates", "export_idt = DataType.BINARY else: export_idt = DataType[self.get_nodeattr(\"dataType\")] # make copy", "f: f.write(\"#!/bin/bash \\n\") f.write(\"cd {}\\n\".format(verilog_dir)) f.write(\"vivado -mode batch -source package_ip.tcl\\n\")", "to the new packaged IP self.set_nodeattr(\"ipgen_path\", verilog_dir) self.set_nodeattr(\"ip_path\", verilog_dir) vlnv", "this the two inner dimensions are multiplied # and together", "depth = self.get_nodeattr(\"depth\") ram_style = self.get_nodeattr(\"ram_style\") # create a hierarchy", "two inner dimensions are multiplied # and together with all", "np.load(out_npy_path) oshape = self.get_normal_output_shape() output = np.asarray([output], dtype=np.float32).reshape(*oshape) context[node.output[0]] =", "# list of conditions and the following disclaimer. # #", "packed_bits, target_bits ) # load and reshape output output =", "( \"StreamingFIFO impl_style \" \"cannot be vivado for rtlsim. Only", "= self.get_nodeattr(\"depth\") ram_style = self.get_nodeattr(\"ram_style\") # create a hierarchy for", "Redistributions in binary form must reproduce the above copyright notice,", "oshape = self.get_normal_output_shape() output = np.asarray([output], dtype=np.float32).reshape(*oshape) context[node.output[0]] = output", "(node_name, din_name) ) # instantiate and configure DWC cmd.append( \"create_bd_cell", "= (math.ceil(depth / 32)) * (math.ceil(W / 2)) else: ram_luts", "AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN", "shell script and call Vivado to invoke the IP pkg", "set ipgen_path and ip_path to point to the new packaged", "dims=values.shape, vals=values.flatten().astype(float), ), ) def infer_node_datatype(self, model): node = self.onnx_node", "36 * 512 return wbits / bram16_est_capacity def lut_estimation(self): \"\"\"Calculates", "reshaped_input = inp.reshape(expected_inp_shape) if DataType[self.get_nodeattr(\"dataType\")] == DataType.BIPOLAR: # store bipolar", "in_width = folded_shape[-1] * dtype.bitwidth() return in_width def execute_node(self, context,", "self.get_nodeattr(\"impl_style\") != \"vivado\", ( \"StreamingFIFO impl_style \" \"cannot be vivado", "% node_name) cmd.append(\"create_bd_pin -dir I -type clk /%s/%s\" % (node_name,", "copy(Q_file, verilog_dir) # empty code gen dictionary for new entries", "return in_width def execute_node(self, context, graph): mode = self.get_nodeattr(\"exec_mode\") node", "inp = npy_to_rtlsim_input( \"{}/input_0.npy\".format(code_gen_dir), export_idt, nbits ) super().reset_rtlsim(sim) super().toggle_clk(sim) output", "ram_type == \"distributed\"): ram_luts = (math.ceil(depth / 32)) * (math.ceil(W", "2)) else: ram_luts = 0 return int(address_luts + ram_luts) def", "between 2 and 256 for efficient SRL implementation\" ) #", "self.code_gen_dict[\"$OUT_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$WIDTH$\"] = [str(in_width)] self.code_gen_dict[\"$DEPTH$\"] =", "out_shape, packed_bits, target_bits ) # load and reshape output output", "the Verilog top module name for this node.\" node =", "from finn.custom_op.fpgadataflow.hlscustomop import HLSCustomOp from finn.core.datatype import DataType from onnx", "exp_shape = self.get_normal_input_shape() if mode == \"cppsim\": output = inp", "= self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) os.makedirs(verilog_dir) #", "FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO", "node = self.onnx_node idt = model.get_tensor_datatype(node.input[0]) if idt != self.get_input_datatype():", "# Toggle between hls or IPI implementation # rtl -", "W == 2: return math.ceil(depth / 8192) elif W <=", "= \"inputDataType changing for %s: %s -> %s \" %", "subprocess import math import warnings from finn.custom_op.fpgadataflow.hlscustomop import HLSCustomOp from", "helper.make_node( \"Constant\", inputs=[], outputs=[self.onnx_node.output[0]], value=helper.make_tensor( name=\"const_tensor\", data_type=TensorProto.FLOAT, dims=values.shape, vals=values.flatten().astype(float), ),", "bram_efficiency_estimation(self): depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() bram16_est = self.bram_estimation()", "depth > 256 and self.get_nodeattr(\"impl_style\") == \"rtl\": warnings.warn( \"Depth is", "implementation # rtl - use the hls generated IP during", "the folded shape could be for example (1, nf, pe)", "def get_nodeattr_types(self): my_attrs = { # FIFO depth \"depth\": (\"i\",", "copyright notice, # this list of conditions and the following", "be for example (1, nf, pe) # with nf (neuron", "\"rtl\" or (impl == \"vivado\" and ram_type == \"distributed\"): ram_luts", "save_as_npy(self): pass def blackboxfunction(self): pass def pragmas(self): pass def code_generation_ipi(self):", "inp output = np.asarray([output], dtype=np.float32).reshape(*exp_shape) context[node.output[0]] = output elif mode", "interface in_width = self.get_instream_width_padded() count_width = int(self.get_nodeattr(\"depth\") - 1).bit_length() self.code_gen_dict[\"$COUNT_RANGE$\"]", "the input of the node assert ( str(inp.dtype) == \"float32\"", "new entries self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] self.code_gen_dict[\"$LAYER_NAME$\"] = [ \"{}_{}\".format(self.onnx_node.name,", "model): node = self.onnx_node idt = model.get_tensor_datatype(node.input[0]) if idt !=", "# # * Neither the name of FINN nor the", "import TensorProto, helper from finn.util.data_packing import npy_to_rtlsim_input, rtlsim_output_to_npy from .", "W <= 9: return (math.ceil(depth / 2048)) * (math.ceil(W /", "dir as absolute can cause path problems # the ipgen", "# Non-BRAM based implementation return 0 else: return (math.ceil(depth /", "def dataoutstrm(self): pass def save_as_npy(self): pass def blackboxfunction(self): pass def", "LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", ">= 2, \"\"\"Depth is too low\"\"\" if depth > 256", "ram_type = self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() if", "docompute(self): pass def dataoutstrm(self): pass def save_as_npy(self): pass def blackboxfunction(self):", "without # modification, are permitted provided that the following conditions", "# ultra -- use URAM (on UltraScale+) \"ram_style\": ( \"s\",", "ip \" \"-vlnv xilinx.com:ip:axis_data_fifo:2.0 /%s/fifo\" % node_name ) cmd.append( \"set_property", "float32 as expected.\"\"\" expected_inp_shape = self.get_folded_input_shape() reshaped_input = inp.reshape(expected_inp_shape) if", "= self.get_nodeattr(\"exec_mode\") node = self.onnx_node inp = context[node.input[0]] exp_shape =", "W = self.get_instream_width() address_luts = 2 * math.ceil(math.log(depth, 2)) if", "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY", "model.set_tensor_datatype(node.output[0], idt) def verify_node(self): pass def get_verilog_top_module_name(self): \"Return the Verilog", "IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR", "THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF", "depth >= 2, \"\"\"Depth is too low\"\"\" if depth >", "invoked from the sources dir so root_dir=. is OK self.code_gen_dict[\"$VERILOG_DIR$\"]", "(math.ceil(depth / 32)) * (math.ceil(W / 2)) else: ram_luts =", "node_name) ) return cmd else: raise Exception( \"FIFO implementation style", "create the normal_ishape for i in range(len(folded_shape) - 2): normal_ishape.append(folded_shape[i])", "depth > 512: return (math.ceil(depth / 1024)) * (math.ceil(W /", "ip_path to point to the new packaged IP self.set_nodeattr(\"ipgen_path\", verilog_dir)", "distributed -- use LUTRAM # ultra -- use URAM (on", "as expected.\"\"\" expected_inp_shape = self.get_folded_input_shape() reshaped_input = inp.reshape(expected_inp_shape) if DataType[self.get_nodeattr(\"dataType\")]", "pass def blackboxfunction(self): pass def pragmas(self): pass def code_generation_ipi(self): impl_style", "- 1)] self.code_gen_dict[\"$OUT_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$WIDTH$\"] = [str(in_width)]", "False, \"rtl\", {\"rtl\", \"vivado\"}), # FPGA resource type for FIFOs", "warn_str = \"inputDataType changing for %s: %s -> %s \"", "as absolute can cause path problems # the ipgen script", "== \"vivado\" and ram_type != \"block\"): # Non-BRAM based implementation", "/ 2048)) * (math.ceil(W / 9)) elif W <= 18", "with nf (neuron folding): mh // pe # the normal", "-type ip \" \"-vlnv xilinx.com:ip:axis_data_fifo:2.0 /%s/fifo\" % node_name ) cmd.append(", "[str(in_width)] self.code_gen_dict[\"$DEPTH$\"] = [str(self.get_nodeattr(\"depth\"))] template = self.strm_fifo_wrapper for key in", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "invoke the IP pkg script make_project_sh = verilog_dir + \"/make_ip.sh\"", "super().__init__(onnx_node) self.strm_fifo_wrapper = templates.strm_fifo_wrapper def get_nodeattr_types(self): my_attrs = { #", "impl_style = self.get_nodeattr(\"impl_style\") if impl_style == \"rtl\": return super().code_generation_ipi() elif", "18)) else: return (math.ceil(depth / 512)) * (math.ceil(W / 36))", "impl_style \" \"cannot be vivado for rtlsim. Only impl_style=rtl supported.\"", "= \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) os.makedirs(verilog_dir) # copy Q_srl.v from", "folded shape # StreamingFIFOs are inserted in between fpgadataflow nodes", "return self.get_nodeattr(\"folded_shape\") def get_instream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\")", "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #", "permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "use URAM (on UltraScale+) \"ram_style\": ( \"s\", False, \"auto\", {\"auto\",", "\"{}.v\".format(self.onnx_node.name)), \"w\") f.write(template) f.close() self.code_gen_dict.clear() def ipgen_singlenode_code(self): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\")", "input shape for StreamingFIFO.\" # implement tensor with correct shape", "\"rtl\", {\"rtl\", \"vivado\"}), # FPGA resource type for FIFOs when", "into long string separated by '\\n' code_gen_line = \"\\n\".join(self.code_gen_dict[key]) template", "USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED", "pass def strm_decl(self): pass def docompute(self): pass def dataoutstrm(self): pass", "IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "= np.asarray([output], dtype=np.float32).reshape(*oshape) context[node.output[0]] = output else: raise Exception( \"\"\"Invalid", "[\"bash\", make_project_sh] process_compile = subprocess.Popen(bash_command, stdout=subprocess.PIPE) process_compile.communicate() # set ipgen_path", "else: return (math.ceil(depth / 512)) * (math.ceil(W / 36)) def", "value=helper.make_tensor( name=\"const_tensor\", data_type=TensorProto.FLOAT, dims=values.shape, vals=values.flatten().astype(float), ), ) def infer_node_datatype(self, model):", "self.onnx_node.name) ] # make instream width a multiple of 8", "== \"rtl\": return super().code_generation_ipi() elif impl_style == \"vivado\": cmd =", "inputs=[], outputs=[self.onnx_node.output[0]], value=helper.make_tensor( name=\"const_tensor\", data_type=TensorProto.FLOAT, dims=values.shape, vals=values.flatten().astype(float), ), ) def", "* 36 * 512 return wbits / bram16_est_capacity def lut_estimation(self):", "mode == \"rtlsim\": code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") # create a npy", "\" % ( node.name, str(self.get_input_datatype()), str(idt), ) warnings.warn(warn_str) self.set_nodeattr(\"dataType\", idt.name)", "set to one of the following value (\"cppsim\", \"rtlsim\")\"\"\".format( mode", "Verilog top module name for this node.\" node = self.onnx_node", "address_luts = 2 * math.ceil(math.log(depth, 2)) if impl == \"rtl\"", "# copy Q_srl.v from finn-rtllib to verilog directory memstream_dir =", "global_includes(self): pass def defines(self, var): pass def read_npy_data(self): pass def", "is high, set between 2 and 256 for efficient SRL", "impl_style is vivado # auto -- let Vivado decide #", "\"ram_style\": ( \"s\", False, \"auto\", {\"auto\", \"block\", \"distributed\", \"ultra\"}, ),", "\"[get_bd_intf_pins %s/%s]\" % (node_name, node_name, din_name) ) cmd.append( \"connect_bd_net [get_bd_pins", "f.write(template) f.close() # create a shell script and call Vivado", "TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT", "(\"cppsim\", \"rtlsim\")\"\"\".format( mode ) ) def get_number_output_values(self): folded_oshape = self.get_folded_output_shape()", "and 256 for efficient SRL implementation\" ) # derive normal", "POSSIBILITY OF SUCH DAMAGE. import os import numpy as np", "finn.util.data_packing import npy_to_rtlsim_input, rtlsim_output_to_npy from . import templates class StreamingFIFO(HLSCustomOp):", "graph): mode = self.get_nodeattr(\"exec_mode\") node = self.onnx_node inp = context[node.input[0]]", "= self.get_normal_output_shape() ishape = tuple(model.get_tensor_shape(self.onnx_node.input[0])) assert ishape == tuple(exp_ishape), \"Unexpect", "instantiate and configure DWC cmd.append( \"create_bd_cell -type ip \" \"-vlnv", ") warnings.warn(warn_str) self.set_nodeattr(\"dataType\", idt.name) # data type stays the same", "\"[get_bd_cells /%s/fifo]\" % (depth, node_name) ) cmd.append( \"set_property -dict [list", "bram16_est_capacity = bram16_est * 36 * 512 return wbits /", "* dtype.bitwidth() return in_width def get_outstream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape", "with correct shape values = np.random.randn(*oshape).astype(np.float32) return helper.make_node( \"Constant\", inputs=[],", "resource estimation for BRAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\")", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND", "= context[node.input[0]] exp_shape = self.get_normal_input_shape() if mode == \"cppsim\": output", "[] node_name = self.onnx_node.name depth = self.get_nodeattr(\"depth\") ram_style = self.get_nodeattr(\"ram_style\")", "%s/fifo/M_AXIS] \" \"[get_bd_intf_pins %s/%s]\" % (node_name, node_name, dout_name) ) cmd.append(", "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF", "Neither the name of FINN nor the names of its", "<= 9: return (math.ceil(depth / 2048)) * (math.ceil(W / 9))", "above copyright notice, # this list of conditions and the", "(math.ceil(depth / 1024)) * (math.ceil(W / 18)) else: return (math.ceil(depth", "# # Redistribution and use in source and binary forms,", "# StreamingFIFOs are inserted in between fpgadataflow nodes # the", "the next inner dimension folding_factor = folded_shape[-2] * inner_dim normal_ishape", "THE POSSIBILITY OF SUCH DAMAGE. import os import numpy as", "\" \"-vlnv xilinx.com:ip:axis_data_fifo:2.0 /%s/fifo\" % node_name ) cmd.append( \"set_property -dict", "with the distribution. # # * Neither the name of", "node_name) cmd.append(\"create_bd_pin -dir I -type clk /%s/%s\" % (node_name, clk_name))", "# FPGA resource type for FIFOs when impl_style is vivado", "so root_dir=. is OK self.code_gen_dict[\"$VERILOG_DIR$\"] = [\".\"] for key in", "use rtl or vivado\" % impl_style ) def bram_estimation(self): \"\"\"Calculates", "= [\"{}\".format(self.onnx_node.name)] # note: setting the root dir as absolute", "uram_estimation(self): \"\"\"Calculates resource estimation for URAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type", "self.set_nodeattr(\"ip_vlnv\", vlnv) self.code_gen_dict.clear() def get_normal_input_shape(self): depth = self.get_nodeattr(\"depth\") # depth", "tuple(model.get_tensor_shape(self.onnx_node.input[0])) assert ishape == tuple(exp_ishape), \"Unexpect input shape for StreamingFIFO.\"", "code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) os.makedirs(verilog_dir)", "\"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aresetn]\" % (node_name, rst_name, node_name)", "from # this software without specific prior written permission. #", "model.get_tensor_datatype(node.input[0]) if idt != self.get_input_datatype(): warn_str = \"inputDataType changing for", "FIFOs when impl_style is vivado # auto -- let Vivado", "= [\"[{}:0]\".format(count_width - 1)] self.code_gen_dict[\"$IN_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$OUT_RANGE$\"]", "my_attrs def make_shape_compatible_op(self, model): exp_ishape = self.get_normal_input_shape() oshape = self.get_normal_output_shape()", "(\"ints\", True, []), # FINN DataTypes for inputs/outputs \"dataType\": (\"s\",", "to be set to one of the following value (\"cppsim\",", "self.set_nodeattr(\"ip_path\", verilog_dir) vlnv = \"xilinx.com:hls:%s:1.0\" % (self.onnx_node.name) self.set_nodeattr(\"ip_vlnv\", vlnv) self.code_gen_dict.clear()", "[get_bd_intf_pins %s/fifo/M_AXIS] \" \"[get_bd_intf_pins %s/%s]\" % (node_name, node_name, dout_name) )", "sim = self.get_rtlsim() nbits = self.get_instream_width() inp = npy_to_rtlsim_input( \"{}/input_0.npy\".format(code_gen_dir),", "(node.name) return prefixed_top_name def code_generation_ipgen(self, model, fpgapart, clk): code_gen_dir =", "[\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$WIDTH$\"] = [str(in_width)] self.code_gen_dict[\"$DEPTH$\"] = [str(self.get_nodeattr(\"depth\"))] template", "source and binary forms, with or without # modification, are", "* (math.ceil(W / 9)) elif W <= 18 or depth", "PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE", "get_verilog_top_module_name(self): \"Return the Verilog top module name for this node.\"", "Exception( \"\"\"Invalid value for attribute exec_mode! Is currently set to:", "ANY WAY OUT OF THE USE # OF THIS SOFTWARE,", "self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] self.code_gen_dict[\"$LAYER_NAME$\"] = [ \"{}_{}\".format(self.onnx_node.name, self.onnx_node.name) ] #", "== 1: return math.ceil(depth / 16384) elif W == 2:", "rtlsim_output_to_npy( output, out_npy_path, odt, out_shape, packed_bits, target_bits ) # load", "ipgen script will be invoked from the sources dir so", "use the AXI Infrastructure FIFO \"impl_style\": (\"s\", False, \"rtl\", {\"rtl\",", "set to: {} has to be set to one of", "36)) def uram_estimation(self): \"\"\"Calculates resource estimation for URAM\"\"\" impl =", "\"\\n\".join(self.code_gen_dict[key]) template = template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir, \"package_ip.tcl\"), \"w\")", "for inputs/outputs \"dataType\": (\"s\", True, \"\"), # Toggle between hls", "verilog_dir) # empty code gen dictionary for new entries self.code_gen_dict.clear()", "% (node_name, rst_name, node_name) ) cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \"", "OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR", "to be between 2 and 256 with the current #", "# transform list into long string separated by '\\n' code_gen_line", "path problems # the ipgen script will be invoked from", "[\"[{}:0]\".format(count_width - 1)] self.code_gen_dict[\"$IN_RANGE$\"] = [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$OUT_RANGE$\"] =", "/ 32)) * (math.ceil(W / 2)) else: ram_luts = 0", "return self.get_nodeattr(\"folded_shape\") def get_folded_output_shape(self): return self.get_nodeattr(\"folded_shape\") def get_instream_width(self): dtype =", "current # StreamingFIFO implementation assert depth >= 2, \"\"\"Depth is", "the same port names clk_name = self.get_verilog_top_module_intf_names()[\"clk\"][0] rst_name = self.get_verilog_top_module_intf_names()[\"rst\"][0]", "f.write(template) f.close() self.code_gen_dict.clear() def ipgen_singlenode_code(self): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir =", "* (math.ceil(W / 4)) elif W <= 9: return (math.ceil(depth", "% (node_name, node_name, dout_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/S_AXIS] \"", "warnings.warn( \"Depth is high, set between 2 and 256 for", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE", "multiply with the next inner dimension folding_factor = folded_shape[-2] *", "self.set_nodeattr(\"dataType\", idt.name) # data type stays the same model.set_tensor_datatype(node.output[0], idt)", "OF THE POSSIBILITY OF SUCH DAMAGE. import os import numpy", "= folded_shape[-2] * inner_dim normal_ishape = [] # create the", "notice, # this list of conditions and the following disclaimer", "\"%s\" % (node.name) return prefixed_top_name def code_generation_ipgen(self, model, fpgapart, clk):", "self.rtlsim(sim, inp) odt = DataType[self.get_nodeattr(\"dataType\")] target_bits = odt.bitwidth() packed_bits =", "DataType.BINARY else: export_idt = DataType[self.get_nodeattr(\"dataType\")] # make copy before saving", "retain the above copyright notice, this # list of conditions", "-source package_ip.tcl\\n\") f.write(\"cd {}\\n\".format(working_dir)) bash_command = [\"bash\", make_project_sh] process_compile =", "OUT OF THE USE # OF THIS SOFTWARE, EVEN IF", "for %s: %s -> %s \" % ( node.name, str(self.get_input_datatype()),", "# FIFO depth \"depth\": (\"i\", True, 0), # folded shape", "= [str(self.get_nodeattr(\"depth\"))] template = self.strm_fifo_wrapper for key in self.code_gen_dict: #", "vivado - use the AXI Infrastructure FIFO \"impl_style\": (\"s\", False,", "256 and self.get_nodeattr(\"impl_style\") == \"rtl\": warnings.warn( \"Depth is high, set", "self.get_instream_width_padded() count_width = int(self.get_nodeattr(\"depth\") - 1).bit_length() self.code_gen_dict[\"$COUNT_RANGE$\"] = [\"[{}:0]\".format(count_width -", "bram16_est_capacity def lut_estimation(self): \"\"\"Calculates resource estimations for LUTs\"\"\" impl =", "disclaimer in the documentation # and/or other materials provided with", "cmd = [] node_name = self.onnx_node.name depth = self.get_nodeattr(\"depth\") ram_style", "bash_command = [\"bash\", make_project_sh] process_compile = subprocess.Popen(bash_command, stdout=subprocess.PIPE) process_compile.communicate() #", "(\"i\", True, 0), # folded shape of input/output \"folded_shape\": (\"ints\",", "= reshaped_input.copy() np.save(os.path.join(code_gen_dir, \"input_0.npy\"), reshaped_input) sim = self.get_rtlsim() nbits =", "ram_type != \"ultra\"): # Non-BRAM based implementation return 0 else:", "-> %s \" % ( node.name, str(self.get_input_datatype()), str(idt), ) warnings.warn(warn_str)", "= self.get_instream_width_padded() count_width = int(self.get_nodeattr(\"depth\") - 1).bit_length() self.code_gen_dict[\"$COUNT_RANGE$\"] = [\"[{}:0]\".format(count_width", "# create the normal_ishape for i in range(len(folded_shape) - 2):", "this case (1, mh) # so to achieve this the", "disclaimer. # # * Redistributions in binary form must reproduce", "== \"vivado\" and ram_type == \"distributed\"): ram_luts = (math.ceil(depth /", "verify_node(self): pass def get_verilog_top_module_name(self): \"Return the Verilog top module name", "cmd.append( \"create_bd_intf_pin -mode Master \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name,", "CONFIG.TDATA_NUM_BYTES {%d}] \" \"[get_bd_cells /%s/fifo]\" % (np.ceil(self.get_outstream_width() / 8), node_name)", "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF", "saving the array reshaped_input = reshaped_input.copy() np.save(os.path.join(code_gen_dir, \"input_0.npy\"), reshaped_input) sim", "0), # folded shape of input/output \"folded_shape\": (\"ints\", True, []),", "clk /%s/%s\" % (node_name, clk_name)) cmd.append(\"create_bd_pin -dir I -type rst", "# instantiate and configure DWC cmd.append( \"create_bd_cell -type ip \"", "instream width a multiple of 8 for axi interface in_width", "return np.prod(folded_oshape[:-1]) def global_includes(self): pass def defines(self, var): pass def", "# auto -- let Vivado decide # block -- use", "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS", "efficient SRL implementation\" ) # derive normal shape from folded", "# implement tensor with correct shape values = np.random.randn(*oshape).astype(np.float32) return", "CONFIG.FIFO_MEMORY_TYPE {%s}] \" \"[get_bd_cells /%s/fifo]\" % (ram_style, node_name) ) cmd.append(", "next inner dimension folding_factor = folded_shape[-2] * inner_dim normal_ishape =", "{%s}] \" \"[get_bd_cells /%s/fifo]\" % (ram_style, node_name) ) cmd.append( \"set_property", "CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)", "decide # block -- use BRAM # distributed -- use", "dtype.bitwidth() return in_width def get_outstream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape =", "\"float32\" ), \"\"\"Input datatype is not float32 as expected.\"\"\" expected_inp_shape", "= os.environ[\"PWD\"] with open(make_project_sh, \"w\") as f: f.write(\"#!/bin/bash \\n\") f.write(\"cd", "= self.get_nodeattr(\"folded_shape\") # extract inner dimension inner_dim = folded_shape[-1] #", "cmd.append(\"create_bd_cell -type hier %s\" % node_name) cmd.append(\"create_bd_pin -dir I -type", "= self.onnx_node prefixed_top_name = \"%s\" % (node.name) return prefixed_top_name def", "and/or other materials provided with the distribution. # # *", "-dict [list CONFIG.TDATA_NUM_BYTES {%d}] \" \"[get_bd_cells /%s/fifo]\" % (np.ceil(self.get_outstream_width() /", "elif W <= 18 or depth > 512: return (math.ceil(depth", "for example (1, nf, pe) # with nf (neuron folding):", "that the following conditions are met: # # * Redistributions", "Redistribution and use in source and binary forms, with or", "code must retain the above copyright notice, this # list", "xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, dout_name) ) cmd.append( \"create_bd_intf_pin -mode Slave", "cmd.append( \"create_bd_cell -type ip \" \"-vlnv xilinx.com:ip:axis_data_fifo:2.0 /%s/fifo\" % node_name", "elif W <= 9: return (math.ceil(depth / 2048)) * (math.ceil(W", "package_ip.tcl\\n\") f.write(\"cd {}\\n\".format(working_dir)) bash_command = [\"bash\", make_project_sh] process_compile = subprocess.Popen(bash_command,", "node.\" node = self.onnx_node prefixed_top_name = \"%s\" % (node.name) return", "2 and 256 with the current # StreamingFIFO implementation assert", "this # list of conditions and the following disclaimer. #", "for this layer, with the same port names clk_name =", "= self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() if impl", "please use rtl or vivado\" % impl_style ) def bram_estimation(self):", "\"[get_bd_pins %s/fifo/s_axis_aresetn]\" % (node_name, rst_name, node_name) ) cmd.append( \"connect_bd_net [get_bd_pins", "= np.load(out_npy_path) oshape = self.get_normal_output_shape() output = np.asarray([output], dtype=np.float32).reshape(*oshape) context[node.output[0]]", "== 0: return 1 wbits = W * depth bram16_est_capacity", "is in this case (1, mh) # so to achieve", "prepare_rtlsim(self): assert self.get_nodeattr(\"impl_style\") != \"vivado\", ( \"StreamingFIFO impl_style \" \"cannot", "rights reserved. # # Redistribution and use in source and", "# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY", "top module name for this node.\" node = self.onnx_node prefixed_top_name", "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING,", "context[node.output[0]] = output else: raise Exception( \"\"\"Invalid value for attribute", "= self.get_nodeattr(\"depth\") W = self.get_instream_width() bram16_est = self.bram_estimation() if bram16_est", "get_folded_input_shape(self): return self.get_nodeattr(\"folded_shape\") def get_folded_output_shape(self): return self.get_nodeattr(\"folded_shape\") def get_instream_width(self): dtype", "template = template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir, \"package_ip.tcl\"), \"w\") f.write(template)", "binary form must reproduce the above copyright notice, # this", "ram_type = self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() address_luts", "dout_name = self.get_verilog_top_module_intf_names()[\"m_axis\"][0][0] din_name = self.get_verilog_top_module_intf_names()[\"s_axis\"][0][0] cmd.append(\"create_bd_cell -type hier %s\"", "for the input of the node assert ( str(inp.dtype) ==", "Xilinx # All rights reserved. # # Redistribution and use", "72)) def bram_efficiency_estimation(self): depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() bram16_est", "-dict [list CONFIG.FIFO_DEPTH {%d}] \" \"[get_bd_cells /%s/fifo]\" % (depth, node_name)", "if idt != self.get_input_datatype(): warn_str = \"inputDataType changing for %s:", "binary reshaped_input = (reshaped_input + 1) / 2 export_idt =", "during stitching # vivado - use the AXI Infrastructure FIFO", "/ 2 export_idt = DataType.BINARY else: export_idt = DataType[self.get_nodeattr(\"dataType\")] #", "make copy before saving the array reshaped_input = reshaped_input.copy() np.save(os.path.join(code_gen_dir,", "pass def save_as_npy(self): pass def blackboxfunction(self): pass def pragmas(self): pass", "1 wbits = W * depth bram16_est_capacity = bram16_est *", "self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() address_luts = 2", "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING", "2)) if impl == \"rtl\" or (impl == \"vivado\" and", "list of conditions and the following disclaimer. # # *", "for i in range(len(folded_shape) - 2): normal_ishape.append(folded_shape[i]) normal_ishape.append(folding_factor) return normal_ishape", "8 for axi interface in_width = self.get_instream_width_padded() count_width = int(self.get_nodeattr(\"depth\")", "vivado # auto -- let Vivado decide # block --", "inner_dim normal_ishape = [] # create the normal_ishape for i", "of conditions and the following disclaimer in the documentation #", "DWC cmd.append( \"create_bd_cell -type ip \" \"-vlnv xilinx.com:ip:axis_data_fifo:2.0 /%s/fifo\" %", "products derived from # this software without specific prior written", "import templates class StreamingFIFO(HLSCustomOp): def __init__(self, onnx_node): super().__init__(onnx_node) self.strm_fifo_wrapper =", "my_attrs.update(super().get_nodeattr_types()) return my_attrs def make_shape_compatible_op(self, model): exp_ishape = self.get_normal_input_shape() oshape", "import math import warnings from finn.custom_op.fpgadataflow.hlscustomop import HLSCustomOp from finn.core.datatype", "\"rtl\": warnings.warn( \"Depth is high, set between 2 and 256", "dimensions # this gives the normal input shape folded_shape =", "= [str(in_width)] self.code_gen_dict[\"$DEPTH$\"] = [str(self.get_nodeattr(\"depth\"))] template = self.strm_fifo_wrapper for key", "for axi interface in_width = self.get_instream_width_padded() count_width = int(self.get_nodeattr(\"depth\") -", "\"rtlsim\")\"\"\".format( mode ) ) def get_number_output_values(self): folded_oshape = self.get_folded_output_shape() return", "pass def defines(self, var): pass def read_npy_data(self): pass def strm_decl(self):", "EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import", ") os.makedirs(verilog_dir) # copy Q_srl.v from finn-rtllib to verilog directory", "create a shell script and call Vivado to invoke the", "create a npy file for the input of the node", "def bram_estimation(self): \"\"\"Calculates resource estimation for BRAM\"\"\" impl = self.get_nodeattr(\"impl_style\")", "% (depth, node_name) ) cmd.append( \"set_property -dict [list CONFIG.FIFO_MEMORY_TYPE {%s}]", "def get_folded_output_shape(self): return self.get_nodeattr(\"folded_shape\") def get_instream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape", "= self.get_normal_input_shape() if mode == \"cppsim\": output = inp output", "(c) 2020, Xilinx # All rights reserved. # # Redistribution", "def docompute(self): pass def dataoutstrm(self): pass def save_as_npy(self): pass def", "Q_srl.v from finn-rtllib to verilog directory memstream_dir = \"/workspace/finn/finn-rtllib/memstream/hdl/\" Q_file", "ram_luts) def prepare_rtlsim(self): assert self.get_nodeattr(\"impl_style\") != \"vivado\", ( \"StreamingFIFO impl_style", "fpgadataflow nodes # the folded shape could be for example", "estimations for LUTs\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth", "/ 16384) elif W == 2: return math.ceil(depth / 8192)", "1024)) * (math.ceil(W / 18)) else: return (math.ceil(depth / 512))", "make_project_sh] process_compile = subprocess.Popen(bash_command, stdout=subprocess.PIPE) process_compile.communicate() # set ipgen_path and", "def strm_decl(self): pass def docompute(self): pass def dataoutstrm(self): pass def", "(math.ceil(W / 72)) def bram_efficiency_estimation(self): depth = self.get_nodeattr(\"depth\") W =", "1).bit_length() self.code_gen_dict[\"$COUNT_RANGE$\"] = [\"[{}:0]\".format(count_width - 1)] self.code_gen_dict[\"$IN_RANGE$\"] = [\"[{}:0]\".format(in_width -", "copy before saving the array reshaped_input = reshaped_input.copy() np.save(os.path.join(code_gen_dir, \"input_0.npy\"),", "), \"\"\"Input datatype is not float32 as expected.\"\"\" expected_inp_shape =", "name for this node.\" node = self.onnx_node prefixed_top_name = \"%s\"", "= output elif mode == \"rtlsim\": code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") #", "%s/fifo/s_axis_aresetn]\" % (node_name, rst_name, node_name) ) cmd.append( \"connect_bd_net [get_bd_pins %s/%s]", "use the hls generated IP during stitching # vivado -", "\"set_property -dict [list CONFIG.FIFO_DEPTH {%d}] \" \"[get_bd_cells /%s/fifo]\" % (depth,", "def blackboxfunction(self): pass def pragmas(self): pass def code_generation_ipi(self): impl_style =", "% (node_name, din_name) ) # instantiate and configure DWC cmd.append(", "\"\"\"Calculates resource estimations for LUTs\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type =", "target_bits = odt.bitwidth() packed_bits = self.get_outstream_width() out_npy_path = \"{}/output.npy\".format(code_gen_dir) out_shape", "= self.get_nodeattr(\"folded_shape\") in_width = folded_shape[-1] * dtype.bitwidth() return in_width def", "reshape output output = np.load(out_npy_path) oshape = self.get_normal_output_shape() output =", "return (math.ceil(depth / 512)) * (math.ceil(W / 36)) def uram_estimation(self):", "to achieve this the two inner dimensions are multiplied #", ") cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aresetn]\" % (node_name,", "based implementation return 0 else: return (math.ceil(depth / 4096)) *", "super().toggle_clk(sim) output = self.rtlsim(sim, inp) odt = DataType[self.get_nodeattr(\"dataType\")] target_bits =", "IN ANY WAY OUT OF THE USE # OF THIS", "0 if W == 1: return math.ceil(depth / 16384) elif", "- 1)] self.code_gen_dict[\"$WIDTH$\"] = [str(in_width)] self.code_gen_dict[\"$DEPTH$\"] = [str(self.get_nodeattr(\"depth\"))] template =", "folded shape could be for example (1, nf, pe) #", "if DataType[self.get_nodeattr(\"dataType\")] == DataType.BIPOLAR: # store bipolar activations as binary", "def prepare_rtlsim(self): assert self.get_nodeattr(\"impl_style\") != \"vivado\", ( \"StreamingFIFO impl_style \"", "self.get_normal_input_shape() if mode == \"cppsim\": output = inp output =", "pass def pragmas(self): pass def code_generation_ipi(self): impl_style = self.get_nodeattr(\"impl_style\") if", "and use in source and binary forms, with or without", "root dir as absolute can cause path problems # the", "= self.get_nodeattr(\"depth\") W = self.get_instream_width() address_luts = 2 * math.ceil(math.log(depth,", "(neuron folding): mh // pe # the normal input shape", "output else: raise Exception( \"\"\"Invalid value for attribute exec_mode! Is", "/ 72)) def bram_efficiency_estimation(self): depth = self.get_nodeattr(\"depth\") W = self.get_instream_width()", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE", "SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR", "-type clk /%s/%s\" % (node_name, clk_name)) cmd.append(\"create_bd_pin -dir I -type", "%s/%s]\" % (node_name, node_name, din_name) ) cmd.append( \"connect_bd_net [get_bd_pins %s/%s]", "np.random.randn(*oshape).astype(np.float32) return helper.make_node( \"Constant\", inputs=[], outputs=[self.onnx_node.output[0]], value=helper.make_tensor( name=\"const_tensor\", data_type=TensorProto.FLOAT, dims=values.shape,", "= self.get_folded_input_shape() reshaped_input = inp.reshape(expected_inp_shape) if DataType[self.get_nodeattr(\"dataType\")] == DataType.BIPOLAR: #", "inner_dim = folded_shape[-1] # multiply with the next inner dimension", "or vivado\" % impl_style ) def bram_estimation(self): \"\"\"Calculates resource estimation", "2048)) * (math.ceil(W / 9)) elif W <= 18 or", "(depth, node_name) ) cmd.append( \"set_property -dict [list CONFIG.FIFO_MEMORY_TYPE {%s}] \"", "conditions and the following disclaimer in the documentation # and/or", "%s/%s]\" % (node_name, node_name, dout_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/S_AXIS]", "512)) * (math.ceil(W / 36)) def uram_estimation(self): \"\"\"Calculates resource estimation", "numpy as np from shutil import copy import subprocess import", "[\"{}\".format(self.onnx_node.name)] # note: setting the root dir as absolute can", "cmd.append(\"create_bd_pin -dir I -type clk /%s/%s\" % (node_name, clk_name)) cmd.append(\"create_bd_pin", "reproduce the above copyright notice, # this list of conditions", "(math.ceil(W / 9)) elif W <= 18 or depth >", "= W * depth bram16_est_capacity = bram16_est * 36 *", "def lut_estimation(self): \"\"\"Calculates resource estimations for LUTs\"\"\" impl = self.get_nodeattr(\"impl_style\")", "dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\") in_width = folded_shape[-1] *", "self.code_gen_dict.clear() def get_normal_input_shape(self): depth = self.get_nodeattr(\"depth\") # depth has to", "expected.\"\"\" expected_inp_shape = self.get_folded_input_shape() reshaped_input = inp.reshape(expected_inp_shape) if DataType[self.get_nodeattr(\"dataType\")] ==", "be used to endorse or promote products derived from #", "as binary reshaped_input = (reshaped_input + 1) / 2 export_idt", "forms, with or without # modification, are permitted provided that", "the name of FINN nor the names of its #", "normal_ishape = [] # create the normal_ishape for i in", "width a multiple of 8 for axi interface in_width =", "# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR", "type for FIFOs when impl_style is vivado # auto --", "ultra -- use URAM (on UltraScale+) \"ram_style\": ( \"s\", False,", "LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN", "rtl or vivado\" % impl_style ) def bram_estimation(self): \"\"\"Calculates resource", "the documentation # and/or other materials provided with the distribution.", "= self.get_verilog_top_module_intf_names()[\"clk\"][0] rst_name = self.get_verilog_top_module_intf_names()[\"rst\"][0] dout_name = self.get_verilog_top_module_intf_names()[\"m_axis\"][0][0] din_name =", "node_name) ) cmd.append( \"set_property -dict [list CONFIG.FIFO_MEMORY_TYPE {%s}] \" \"[get_bd_cells", "template = self.strm_fifo_wrapper for key in self.code_gen_dict: # transform list", "are permitted provided that the following conditions are met: #", "%s \" % ( node.name, str(self.get_input_datatype()), str(idt), ) warnings.warn(warn_str) self.set_nodeattr(\"dataType\",", "(math.ceil(depth / 2048)) * (math.ceil(W / 9)) elif W <=", "\"vivado\" and ram_type != \"ultra\"): # Non-BRAM based implementation return", "target_bits ) # load and reshape output output = np.load(out_npy_path)", "-type hier %s\" % node_name) cmd.append(\"create_bd_pin -dir I -type clk", "the IP pkg script make_project_sh = verilog_dir + \"/make_ip.sh\" working_dir", "elif W == 2: return math.ceil(depth / 8192) elif W", "/ 2)) else: ram_luts = 0 return int(address_luts + ram_luts)", "of input/output \"folded_shape\": (\"ints\", True, []), # FINN DataTypes for", "# Redistribution and use in source and binary forms, with", "vivado\" % impl_style ) def bram_estimation(self): \"\"\"Calculates resource estimation for", "the node assert ( str(inp.dtype) == \"float32\" ), \"\"\"Input datatype", ") return cmd else: raise Exception( \"FIFO implementation style %s", "<= 4: return (math.ceil(depth / 4096)) * (math.ceil(W / 4))", "the above copyright notice, # this list of conditions and", "the following conditions are met: # # * Redistributions of", "\"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) os.makedirs(verilog_dir) # copy Q_srl.v from finn-rtllib", "din_name) ) cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aresetn]\" %", "if bram16_est == 0: return 1 wbits = W *", "DataTypes for inputs/outputs \"dataType\": (\"s\", True, \"\"), # Toggle between", "gen dictionary for new entries self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] self.code_gen_dict[\"$LAYER_NAME$\"]", "depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() bram16_est = self.bram_estimation() if", "ram_luts = 0 return int(address_luts + ram_luts) def prepare_rtlsim(self): assert", "return (math.ceil(depth / 4096)) * (math.ceil(W / 4)) elif W", "create a hierarchy for this layer, with the same port", "self.get_verilog_top_module_intf_names()[\"m_axis\"][0][0] din_name = self.get_verilog_top_module_intf_names()[\"s_axis\"][0][0] cmd.append(\"create_bd_cell -type hier %s\" % node_name)", "% (node_name, rst_name)) cmd.append( \"create_bd_intf_pin -mode Master \" \"-vlnv xilinx.com:interface:axis_rtl:1.0", "hier %s\" % node_name) cmd.append(\"create_bd_pin -dir I -type clk /%s/%s\"", "to verilog directory memstream_dir = \"/workspace/finn/finn-rtllib/memstream/hdl/\" Q_file = os.path.join(memstream_dir, \"Q_srl.v\")", "= verilog_dir + \"/make_ip.sh\" working_dir = os.environ[\"PWD\"] with open(make_project_sh, \"w\")", "the following disclaimer. # # * Redistributions in binary form", "self.get_normal_input_shape() def get_folded_input_shape(self): return self.get_nodeattr(\"folded_shape\") def get_folded_output_shape(self): return self.get_nodeattr(\"folded_shape\") def", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS", "np.asarray([output], dtype=np.float32).reshape(*exp_shape) context[node.output[0]] = output elif mode == \"rtlsim\": code_gen_dir", "), ) def infer_node_datatype(self, model): node = self.onnx_node idt =", "), } my_attrs.update(super().get_nodeattr_types()) return my_attrs def make_shape_compatible_op(self, model): exp_ishape =", "script make_project_sh = verilog_dir + \"/make_ip.sh\" working_dir = os.environ[\"PWD\"] with", "pass def dataoutstrm(self): pass def save_as_npy(self): pass def blackboxfunction(self): pass", "before saving the array reshaped_input = reshaped_input.copy() np.save(os.path.join(code_gen_dir, \"input_0.npy\"), reshaped_input)", "return (math.ceil(depth / 1024)) * (math.ceil(W / 18)) else: return", "= self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) # prepare", "normal_ishape def get_normal_output_shape(self): return self.get_normal_input_shape() def get_folded_input_shape(self): return self.get_nodeattr(\"folded_shape\") def", "tcl template template = templates.ip_package_tcl self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] #", "entries self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] self.code_gen_dict[\"$LAYER_NAME$\"] = [ \"{}_{}\".format(self.onnx_node.name, self.onnx_node.name)", "DAMAGE. import os import numpy as np from shutil import", "# # * Redistributions in binary form must reproduce the", "\"connect_bd_intf_net [get_bd_intf_pins %s/fifo/S_AXIS] \" \"[get_bd_intf_pins %s/%s]\" % (node_name, node_name, din_name)", "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED", "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE", "= self.get_outstream_width() out_npy_path = \"{}/output.npy\".format(code_gen_dir) out_shape = self.get_folded_output_shape() rtlsim_output_to_npy( output,", "OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE", "folded_oshape = self.get_folded_output_shape() return np.prod(folded_oshape[:-1]) def global_includes(self): pass def defines(self,", "def get_folded_input_shape(self): return self.get_nodeattr(\"folded_shape\") def get_folded_output_shape(self): return self.get_nodeattr(\"folded_shape\") def get_instream_width(self):", "self.get_verilog_top_module_intf_names()[\"clk\"][0] rst_name = self.get_verilog_top_module_intf_names()[\"rst\"][0] dout_name = self.get_verilog_top_module_intf_names()[\"m_axis\"][0][0] din_name = self.get_verilog_top_module_intf_names()[\"s_axis\"][0][0]", "\"ultra\"): # Non-BRAM based implementation return 0 else: return (math.ceil(depth", "with open(make_project_sh, \"w\") as f: f.write(\"#!/bin/bash \\n\") f.write(\"cd {}\\n\".format(verilog_dir)) f.write(\"vivado", "for attribute exec_mode! Is currently set to: {} has to", "the names of its # contributors may be used to", "the above copyright notice, this # list of conditions and", "and the following disclaimer in the documentation # and/or other", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() if impl == \"rtl\"", "os.makedirs(verilog_dir) # copy Q_srl.v from finn-rtllib to verilog directory memstream_dir", "together with all previous dimensions # this gives the normal", "(ram_style, node_name) ) cmd.append( \"set_property -dict [list CONFIG.TDATA_NUM_BYTES {%d}] \"", "os import numpy as np from shutil import copy import", "pass def code_generation_ipi(self): impl_style = self.get_nodeattr(\"impl_style\") if impl_style == \"rtl\":", "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS", "(impl == \"vivado\" and ram_type != \"ultra\"): # Non-BRAM based", "packaged IP self.set_nodeattr(\"ipgen_path\", verilog_dir) self.set_nodeattr(\"ip_path\", verilog_dir) vlnv = \"xilinx.com:hls:%s:1.0\" %", "\"Q_srl.v\") copy(Q_file, verilog_dir) # empty code gen dictionary for new", "template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir, \"{}.v\".format(self.onnx_node.name)), \"w\") f.write(template) f.close() self.code_gen_dict.clear()", "-- use LUTRAM # ultra -- use URAM (on UltraScale+)", "implementation assert depth >= 2, \"\"\"Depth is too low\"\"\" if", "string separated by '\\n' code_gen_line = \"\\n\".join(self.code_gen_dict[key]) template = template.replace(key,", "load and reshape output output = np.load(out_npy_path) oshape = self.get_normal_output_shape()", "__init__(self, onnx_node): super().__init__(onnx_node) self.strm_fifo_wrapper = templates.strm_fifo_wrapper def get_nodeattr_types(self): my_attrs =", "= os.path.join(memstream_dir, \"Q_srl.v\") copy(Q_file, verilog_dir) # empty code gen dictionary", "modification, are permitted provided that the following conditions are met:", "= \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) # prepare the IP packaging", "# extract inner dimension inner_dim = folded_shape[-1] # multiply with", "IPI implementation # rtl - use the hls generated IP", "pass def read_npy_data(self): pass def strm_decl(self): pass def docompute(self): pass", "inp.reshape(expected_inp_shape) if DataType[self.get_nodeattr(\"dataType\")] == DataType.BIPOLAR: # store bipolar activations as", "Vivado to invoke the IP pkg script make_project_sh = verilog_dir", "bram_estimation(self): \"\"\"Calculates resource estimation for BRAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type", "by '\\n' code_gen_line = \"\\n\".join(self.code_gen_dict[key]) template = template.replace(key, code_gen_line) f", "pass def get_verilog_top_module_name(self): \"Return the Verilog top module name for", "= self.get_verilog_top_module_intf_names()[\"s_axis\"][0][0] cmd.append(\"create_bd_cell -type hier %s\" % node_name) cmd.append(\"create_bd_pin -dir", "= 2 * math.ceil(math.log(depth, 2)) if impl == \"rtl\" or", "str(idt), ) warnings.warn(warn_str) self.set_nodeattr(\"dataType\", idt.name) # data type stays the", "reserved. # # Redistribution and use in source and binary", "# load and reshape output output = np.load(out_npy_path) oshape =", "attribute exec_mode! Is currently set to: {} has to be", "else: raise Exception( \"\"\"Invalid value for attribute exec_mode! Is currently", "OF SUCH DAMAGE. import os import numpy as np from", "= self.get_nodeattr(\"depth\") # depth has to be between 2 and", "and reshape output output = np.load(out_npy_path) oshape = self.get_normal_output_shape() output", "f.write(\"cd {}\\n\".format(verilog_dir)) f.write(\"vivado -mode batch -source package_ip.tcl\\n\") f.write(\"cd {}\\n\".format(working_dir)) bash_command", "long string separated by '\\n' code_gen_line = \"\\n\".join(self.code_gen_dict[key]) template =", "0 return int(address_luts + ram_luts) def prepare_rtlsim(self): assert self.get_nodeattr(\"impl_style\") !=", "hierarchy for this layer, with the same port names clk_name", "8192) elif W <= 4: return (math.ceil(depth / 4096)) *", "(math.ceil(depth / 4096)) * (math.ceil(W / 72)) def bram_efficiency_estimation(self): depth", "/ 36)) def uram_estimation(self): \"\"\"Calculates resource estimation for URAM\"\"\" impl", "import copy import subprocess import math import warnings from finn.custom_op.fpgadataflow.hlscustomop", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #", "# the ipgen script will be invoked from the sources", "def code_generation_ipi(self): impl_style = self.get_nodeattr(\"impl_style\") if impl_style == \"rtl\": return", "cmd.append( \"set_property -dict [list CONFIG.FIFO_DEPTH {%d}] \" \"[get_bd_cells /%s/fifo]\" %", "\"cannot be vivado for rtlsim. Only impl_style=rtl supported.\" ) super().prepare_rtlsim()", "batch -source package_ip.tcl\\n\") f.write(\"cd {}\\n\".format(working_dir)) bash_command = [\"bash\", make_project_sh] process_compile", "4: return (math.ceil(depth / 4096)) * (math.ceil(W / 4)) elif", "[list CONFIG.FIFO_DEPTH {%d}] \" \"[get_bd_cells /%s/fifo]\" % (depth, node_name) )", "make instream width a multiple of 8 for axi interface", "W == 1: return math.ceil(depth / 16384) elif W ==", "code_gen_line = \"\\n\".join(self.code_gen_dict[key]) template = template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir,", "256 with the current # StreamingFIFO implementation assert depth >=", ") # instantiate and configure DWC cmd.append( \"create_bd_cell -type ip", "/ bram16_est_capacity def lut_estimation(self): \"\"\"Calculates resource estimations for LUTs\"\"\" impl", "file for the input of the node assert ( str(inp.dtype)", "self.onnx_node.name ) # prepare the IP packaging tcl template template", "import numpy as np from shutil import copy import subprocess", "{} has to be set to one of the following", "bram16_est * 36 * 512 return wbits / bram16_est_capacity def", "\"Return the Verilog top module name for this node.\" node", "2 * math.ceil(math.log(depth, 2)) if impl == \"rtl\" or (impl", "self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] # note: setting the root dir", "cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/M_AXIS] \" \"[get_bd_intf_pins %s/%s]\" % (node_name, node_name,", "== \"rtlsim\": code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") # create a npy file", "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #", "packed_bits = self.get_outstream_width() out_npy_path = \"{}/output.npy\".format(code_gen_dir) out_shape = self.get_folded_output_shape() rtlsim_output_to_npy(", "int(address_luts + ram_luts) def prepare_rtlsim(self): assert self.get_nodeattr(\"impl_style\") != \"vivado\", (", "\"Unexpect input shape for StreamingFIFO.\" # implement tensor with correct", "are multiplied # and together with all previous dimensions #", "== \"rtl\": warnings.warn( \"Depth is high, set between 2 and", "COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS", "def bram_efficiency_estimation(self): depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() bram16_est =", "normal_ishape for i in range(len(folded_shape) - 2): normal_ishape.append(folded_shape[i]) normal_ishape.append(folding_factor) return", "(impl == \"vivado\" and ram_type == \"distributed\"): ram_luts = (math.ceil(depth", "from . import templates class StreamingFIFO(HLSCustomOp): def __init__(self, onnx_node): super().__init__(onnx_node)", "def get_number_output_values(self): folded_oshape = self.get_folded_output_shape() return np.prod(folded_oshape[:-1]) def global_includes(self): pass", "node_name, dout_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/S_AXIS] \" \"[get_bd_intf_pins %s/%s]\"", "or (impl == \"vivado\" and ram_type == \"distributed\"): ram_luts =", "xilinx.com:ip:axis_data_fifo:2.0 /%s/fifo\" % node_name ) cmd.append( \"set_property -dict [list CONFIG.FIFO_DEPTH", "self.get_normal_output_shape() ishape = tuple(model.get_tensor_shape(self.onnx_node.input[0])) assert ishape == tuple(exp_ishape), \"Unexpect input", "/%s/fifo]\" % (depth, node_name) ) cmd.append( \"set_property -dict [list CONFIG.FIFO_MEMORY_TYPE", "def make_shape_compatible_op(self, model): exp_ishape = self.get_normal_input_shape() oshape = self.get_normal_output_shape() ishape", "np.save(os.path.join(code_gen_dir, \"input_0.npy\"), reshaped_input) sim = self.get_rtlsim() nbits = self.get_instream_width() inp", "W * depth bram16_est_capacity = bram16_est * 36 * 512", "conditions are met: # # * Redistributions of source code", "PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY", "for URAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth =", "all previous dimensions # this gives the normal input shape", "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED", "verilog_dir) self.set_nodeattr(\"ip_path\", verilog_dir) vlnv = \"xilinx.com:hls:%s:1.0\" % (self.onnx_node.name) self.set_nodeattr(\"ip_vlnv\", vlnv)", "(node_name, clk_name)) cmd.append(\"create_bd_pin -dir I -type rst /%s/%s\" % (node_name,", "count_width = int(self.get_nodeattr(\"depth\") - 1).bit_length() self.code_gen_dict[\"$COUNT_RANGE$\"] = [\"[{}:0]\".format(count_width - 1)]", "= self.get_instream_width() bram16_est = self.bram_estimation() if bram16_est == 0: return", "self.get_nodeattr(\"folded_shape\") def get_folded_output_shape(self): return self.get_nodeattr(\"folded_shape\") def get_instream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")]", "def get_normal_output_shape(self): return self.get_normal_input_shape() def get_folded_input_shape(self): return self.get_nodeattr(\"folded_shape\") def get_folded_output_shape(self):", "self.code_gen_dict[\"$TOPNAME$\"] = [\"{}\".format(self.onnx_node.name)] # note: setting the root dir as", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY", "blackboxfunction(self): pass def pragmas(self): pass def code_generation_ipi(self): impl_style = self.get_nodeattr(\"impl_style\")", "# create a hierarchy for this layer, with the same", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,", "the current # StreamingFIFO implementation assert depth >= 2, \"\"\"Depth", "> 256 and self.get_nodeattr(\"impl_style\") == \"rtl\": warnings.warn( \"Depth is high,", "- 2): normal_ishape.append(folded_shape[i]) normal_ishape.append(folding_factor) return normal_ishape def get_normal_output_shape(self): return self.get_normal_input_shape()", "DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\") in_width = folded_shape[-1] * dtype.bitwidth() return", "# so to achieve this the two inner dimensions are", ") cmd.append( \"set_property -dict [list CONFIG.FIFO_MEMORY_TYPE {%s}] \" \"[get_bd_cells /%s/fifo]\"", "will be invoked from the sources dir so root_dir=. is", "{%d}] \" \"[get_bd_cells /%s/fifo]\" % (depth, node_name) ) cmd.append( \"set_property", "cmd.append( \"set_property -dict [list CONFIG.TDATA_NUM_BYTES {%d}] \" \"[get_bd_cells /%s/fifo]\" %", "self.get_nodeattr(\"depth\") # depth has to be between 2 and 256", "warnings.warn(warn_str) self.set_nodeattr(\"dataType\", idt.name) # data type stays the same model.set_tensor_datatype(node.output[0],", "np.asarray([output], dtype=np.float32).reshape(*oshape) context[node.output[0]] = output else: raise Exception( \"\"\"Invalid value", "output, out_npy_path, odt, out_shape, packed_bits, target_bits ) # load and", "2 export_idt = DataType.BINARY else: export_idt = DataType[self.get_nodeattr(\"dataType\")] # make", "in self.code_gen_dict: # transform list into long string separated by", "code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") # create a npy file for the", "Non-BRAM based implementation return 0 if W == 1: return", ") # load and reshape output output = np.load(out_npy_path) oshape", "and ram_type != \"block\"): # Non-BRAM based implementation return 0", "% (node_name, node_name, din_name) ) cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \"", "super().code_generation_ipi() elif impl_style == \"vivado\": cmd = [] node_name =", "endorse or promote products derived from # this software without", "copyright notice, this # list of conditions and the following", "# and together with all previous dimensions # this gives", "\" \"[get_bd_pins %s/fifo/s_axis_aresetn]\" % (node_name, rst_name, node_name) ) cmd.append( \"connect_bd_net", "templates class StreamingFIFO(HLSCustomOp): def __init__(self, onnx_node): super().__init__(onnx_node) self.strm_fifo_wrapper = templates.strm_fifo_wrapper", "of FINN nor the names of its # contributors may", "tuple(exp_ishape), \"Unexpect input shape for StreamingFIFO.\" # implement tensor with", "cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/S_AXIS] \" \"[get_bd_intf_pins %s/%s]\" % (node_name, node_name,", "impl_style == \"vivado\": cmd = [] node_name = self.onnx_node.name depth", "has to be between 2 and 256 with the current", "idt = model.get_tensor_datatype(node.input[0]) if idt != self.get_input_datatype(): warn_str = \"inputDataType", "= \"\\n\".join(self.code_gen_dict[key]) template = template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir, \"{}.v\".format(self.onnx_node.name)),", "# Copyright (c) 2020, Xilinx # All rights reserved. #", "self.onnx_node.name ) os.makedirs(verilog_dir) # copy Q_srl.v from finn-rtllib to verilog", "inp) odt = DataType[self.get_nodeattr(\"dataType\")] target_bits = odt.bitwidth() packed_bits = self.get_outstream_width()", "\"[get_bd_cells /%s/fifo]\" % (ram_style, node_name) ) cmd.append( \"set_property -dict [list", "= self.bram_estimation() if bram16_est == 0: return 1 wbits =", "# the normal input shape is in this case (1,", "= (reshaped_input + 1) / 2 export_idt = DataType.BINARY else:", "# empty code gen dictionary for new entries self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"]", "def get_instream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\") in_width =", "code_generation_ipgen(self, model, fpgapart, clk): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format(", "= { # FIFO depth \"depth\": (\"i\", True, 0), #", "\" \"[get_bd_intf_pins %s/%s]\" % (node_name, node_name, din_name) ) cmd.append( \"connect_bd_net", "= self.onnx_node.name depth = self.get_nodeattr(\"depth\") ram_style = self.get_nodeattr(\"ram_style\") # create", "ishape = tuple(model.get_tensor_shape(self.onnx_node.input[0])) assert ishape == tuple(exp_ishape), \"Unexpect input shape", "depth has to be between 2 and 256 with the", "code_gen_dir, self.onnx_node.name ) os.makedirs(verilog_dir) # copy Q_srl.v from finn-rtllib to", "BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,", "# Non-BRAM based implementation return 0 if W == 1:", "def get_normal_input_shape(self): depth = self.get_nodeattr(\"depth\") # depth has to be", "self.onnx_node idt = model.get_tensor_datatype(node.input[0]) if idt != self.get_input_datatype(): warn_str =", "type stays the same model.set_tensor_datatype(node.output[0], idt) def verify_node(self): pass def", "% (ram_style, node_name) ) cmd.append( \"set_property -dict [list CONFIG.TDATA_NUM_BYTES {%d}]", "node assert ( str(inp.dtype) == \"float32\" ), \"\"\"Input datatype is", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE", "(\"s\", False, \"rtl\", {\"rtl\", \"vivado\"}), # FPGA resource type for", "get_number_output_values(self): folded_oshape = self.get_folded_output_shape() return np.prod(folded_oshape[:-1]) def global_includes(self): pass def", "not float32 as expected.\"\"\" expected_inp_shape = self.get_folded_input_shape() reshaped_input = inp.reshape(expected_inp_shape)", "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES;", ") def bram_estimation(self): \"\"\"Calculates resource estimation for BRAM\"\"\" impl =", "self.onnx_node prefixed_top_name = \"%s\" % (node.name) return prefixed_top_name def code_generation_ipgen(self,", "# StreamingFIFO implementation assert depth >= 2, \"\"\"Depth is too", "shape # StreamingFIFOs are inserted in between fpgadataflow nodes #", "in_width def get_outstream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\") in_width", "self.get_verilog_top_module_intf_names()[\"rst\"][0] dout_name = self.get_verilog_top_module_intf_names()[\"m_axis\"][0][0] din_name = self.get_verilog_top_module_intf_names()[\"s_axis\"][0][0] cmd.append(\"create_bd_cell -type hier", "value for attribute exec_mode! Is currently set to: {} has", "= \"\\n\".join(self.code_gen_dict[key]) template = template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir, \"package_ip.tcl\"),", "get_instream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\") in_width = folded_shape[-1]", "reshaped_input = reshaped_input.copy() np.save(os.path.join(code_gen_dir, \"input_0.npy\"), reshaped_input) sim = self.get_rtlsim() nbits", "depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() address_luts = 2 *", "\"Constant\", inputs=[], outputs=[self.onnx_node.output[0]], value=helper.make_tensor( name=\"const_tensor\", data_type=TensorProto.FLOAT, dims=values.shape, vals=values.flatten().astype(float), ), )", "HLSCustomOp from finn.core.datatype import DataType from onnx import TensorProto, helper", "are met: # # * Redistributions of source code must", "pass def docompute(self): pass def dataoutstrm(self): pass def save_as_npy(self): pass", "W <= 4: return (math.ceil(depth / 4096)) * (math.ceil(W /", "= open(os.path.join(verilog_dir, \"package_ip.tcl\"), \"w\") f.write(template) f.close() # create a shell", "multiplied # and together with all previous dimensions # this", "= self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\") W = self.get_instream_width() address_luts =", "ram_type != \"block\"): # Non-BRAM based implementation return 0 if", "UltraScale+) \"ram_style\": ( \"s\", False, \"auto\", {\"auto\", \"block\", \"distributed\", \"ultra\"},", "strm_decl(self): pass def docompute(self): pass def dataoutstrm(self): pass def save_as_npy(self):", "clk_name)) cmd.append(\"create_bd_pin -dir I -type rst /%s/%s\" % (node_name, rst_name))", "of 8 for axi interface in_width = self.get_instream_width_padded() count_width =", "provided with the distribution. # # * Neither the name", "% (node_name, clk_name, node_name) ) return cmd else: raise Exception(", "self.get_folded_output_shape() return np.prod(folded_oshape[:-1]) def global_includes(self): pass def defines(self, var): pass", "\"block\"): # Non-BRAM based implementation return 0 if W ==", "materials provided with the distribution. # # * Neither the", "inner dimensions are multiplied # and together with all previous", "\"create_bd_intf_pin -mode Master \" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, dout_name)", "documentation # and/or other materials provided with the distribution. #", "warnings from finn.custom_op.fpgadataflow.hlscustomop import HLSCustomOp from finn.core.datatype import DataType from", "OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT", "bram16_est = self.bram_estimation() if bram16_est == 0: return 1 wbits", "pragmas(self): pass def code_generation_ipi(self): impl_style = self.get_nodeattr(\"impl_style\") if impl_style ==", "LUTs\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth = self.get_nodeattr(\"depth\")", "working_dir = os.environ[\"PWD\"] with open(make_project_sh, \"w\") as f: f.write(\"#!/bin/bash \\n\")", "lut_estimation(self): \"\"\"Calculates resource estimations for LUTs\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type", "# data type stays the same model.set_tensor_datatype(node.output[0], idt) def verify_node(self):", "with the current # StreamingFIFO implementation assert depth >= 2,", "== \"rtl\" or (impl == \"vivado\" and ram_type == \"distributed\"):", "# store bipolar activations as binary reshaped_input = (reshaped_input +", "URAM (on UltraScale+) \"ram_style\": ( \"s\", False, \"auto\", {\"auto\", \"block\",", "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "for BRAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth =", "i in range(len(folded_shape) - 2): normal_ishape.append(folded_shape[i]) normal_ishape.append(folding_factor) return normal_ishape def", "self.code_gen_dict[\"$WIDTH$\"] = [str(in_width)] self.code_gen_dict[\"$DEPTH$\"] = [str(self.get_nodeattr(\"depth\"))] template = self.strm_fifo_wrapper for", "or (impl == \"vivado\" and ram_type != \"block\"): # Non-BRAM", "stays the same model.set_tensor_datatype(node.output[0], idt) def verify_node(self): pass def get_verilog_top_module_name(self):", "else: return (math.ceil(depth / 4096)) * (math.ceil(W / 72)) def", "prefixed_top_name def code_generation_ipgen(self, model, fpgapart, clk): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir", "(math.ceil(depth / 4096)) * (math.ceil(W / 4)) elif W <=", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" #", "impl == \"rtl\" or (impl == \"vivado\" and ram_type ==", "( node.name, str(self.get_input_datatype()), str(idt), ) warnings.warn(warn_str) self.set_nodeattr(\"dataType\", idt.name) # data", "\"rtl\" or (impl == \"vivado\" and ram_type != \"block\"): #", "\"vivado\" and ram_type != \"block\"): # Non-BRAM based implementation return", "normal shape from folded shape # StreamingFIFOs are inserted in", "in source and binary forms, with or without # modification,", "self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) os.makedirs(verilog_dir) # copy", "bram16_est == 0: return 1 wbits = W * depth", "# folded shape of input/output \"folded_shape\": (\"ints\", True, []), #", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED", "permitted provided that the following conditions are met: # #", "= DataType[self.get_nodeattr(\"dataType\")] target_bits = odt.bitwidth() packed_bits = self.get_outstream_width() out_npy_path =", "= self.get_normal_input_shape() oshape = self.get_normal_output_shape() ishape = tuple(model.get_tensor_shape(self.onnx_node.input[0])) assert ishape", "node_name = self.onnx_node.name depth = self.get_nodeattr(\"depth\") ram_style = self.get_nodeattr(\"ram_style\") #", "EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE #", "in the documentation # and/or other materials provided with the", "the array reshaped_input = reshaped_input.copy() np.save(os.path.join(code_gen_dir, \"input_0.npy\"), reshaped_input) sim =", "(math.ceil(W / 4)) elif W <= 9: return (math.ceil(depth /", "self.get_nodeattr(\"folded_shape\") # extract inner dimension inner_dim = folded_shape[-1] # multiply", "copy import subprocess import math import warnings from finn.custom_op.fpgadataflow.hlscustomop import", "LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR", "value (\"cppsim\", \"rtlsim\")\"\"\".format( mode ) ) def get_number_output_values(self): folded_oshape =", "the same model.set_tensor_datatype(node.output[0], idt) def verify_node(self): pass def get_verilog_top_module_name(self): \"Return", "\"w\") f.write(template) f.close() self.code_gen_dict.clear() def ipgen_singlenode_code(self): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir", "WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN", "int(self.get_nodeattr(\"depth\") - 1).bit_length() self.code_gen_dict[\"$COUNT_RANGE$\"] = [\"[{}:0]\".format(count_width - 1)] self.code_gen_dict[\"$IN_RANGE$\"] =", "expected_inp_shape = self.get_folded_input_shape() reshaped_input = inp.reshape(expected_inp_shape) if DataType[self.get_nodeattr(\"dataType\")] == DataType.BIPOLAR:", "output = np.asarray([output], dtype=np.float32).reshape(*oshape) context[node.output[0]] = output else: raise Exception(", "and ram_type == \"distributed\"): ram_luts = (math.ceil(depth / 32)) *", "% (self.onnx_node.name) self.set_nodeattr(\"ip_vlnv\", vlnv) self.code_gen_dict.clear() def get_normal_input_shape(self): depth = self.get_nodeattr(\"depth\")", "pkg script make_project_sh = verilog_dir + \"/make_ip.sh\" working_dir = os.environ[\"PWD\"]", "configure DWC cmd.append( \"create_bd_cell -type ip \" \"-vlnv xilinx.com:ip:axis_data_fifo:2.0 /%s/fifo\"", "[get_bd_intf_pins %s/fifo/S_AXIS] \" \"[get_bd_intf_pins %s/%s]\" % (node_name, node_name, din_name) )", "FINN nor the names of its # contributors may be", "reshaped_input.copy() np.save(os.path.join(code_gen_dir, \"input_0.npy\"), reshaped_input) sim = self.get_rtlsim() nbits = self.get_instream_width()", "supported, please use rtl or vivado\" % impl_style ) def", "\"distributed\", \"ultra\"}, ), } my_attrs.update(super().get_nodeattr_types()) return my_attrs def make_shape_compatible_op(self, model):", "= self.get_verilog_top_module_intf_names()[\"rst\"][0] dout_name = self.get_verilog_top_module_intf_names()[\"m_axis\"][0][0] din_name = self.get_verilog_top_module_intf_names()[\"s_axis\"][0][0] cmd.append(\"create_bd_cell -type", "\" \"[get_bd_cells /%s/fifo]\" % (depth, node_name) ) cmd.append( \"set_property -dict", "> 512: return (math.ceil(depth / 1024)) * (math.ceil(W / 18))", "== \"cppsim\": output = inp output = np.asarray([output], dtype=np.float32).reshape(*exp_shape) context[node.output[0]]", "OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED", "self.get_instream_width() address_luts = 2 * math.ceil(math.log(depth, 2)) if impl ==", "16384) elif W == 2: return math.ceil(depth / 8192) elif", "/%s/%s\" % (node_name, din_name) ) # instantiate and configure DWC", "= self.onnx_node idt = model.get_tensor_datatype(node.input[0]) if idt != self.get_input_datatype(): warn_str", "mode = self.get_nodeattr(\"exec_mode\") node = self.onnx_node inp = context[node.input[0]] exp_shape", "mh // pe # the normal input shape is in", "return 0 if W == 1: return math.ceil(depth / 16384)", "with or without # modification, are permitted provided that the", "True, 0), # folded shape of input/output \"folded_shape\": (\"ints\", True,", "following value (\"cppsim\", \"rtlsim\")\"\"\".format( mode ) ) def get_number_output_values(self): folded_oshape", "(node_name, node_name, dout_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/S_AXIS] \" \"[get_bd_intf_pins", "output elif mode == \"rtlsim\": code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") # create", "False, \"auto\", {\"auto\", \"block\", \"distributed\", \"ultra\"}, ), } my_attrs.update(super().get_nodeattr_types()) return", "-type rst /%s/%s\" % (node_name, rst_name)) cmd.append( \"create_bd_intf_pin -mode Master", "following disclaimer. # # * Redistributions in binary form must", "problems # the ipgen script will be invoked from the", "# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY", "* (math.ceil(W / 72)) def bram_efficiency_estimation(self): depth = self.get_nodeattr(\"depth\") W", "shape is in this case (1, mh) # so to", "self.get_verilog_top_module_intf_names()[\"s_axis\"][0][0] cmd.append(\"create_bd_cell -type hier %s\" % node_name) cmd.append(\"create_bd_pin -dir I", "else: ram_luts = 0 return int(address_luts + ram_luts) def prepare_rtlsim(self):", "folding): mh // pe # the normal input shape is", "= folded_shape[-1] * dtype.bitwidth() return in_width def execute_node(self, context, graph):", "inner dimension inner_dim = folded_shape[-1] # multiply with the next", "# this list of conditions and the following disclaimer in", "\"ultra\"}, ), } my_attrs.update(super().get_nodeattr_types()) return my_attrs def make_shape_compatible_op(self, model): exp_ishape", "\"xilinx.com:hls:%s:1.0\" % (self.onnx_node.name) self.set_nodeattr(\"ip_vlnv\", vlnv) self.code_gen_dict.clear() def get_normal_input_shape(self): depth =", "make_project_sh = verilog_dir + \"/make_ip.sh\" working_dir = os.environ[\"PWD\"] with open(make_project_sh,", "= DataType[self.get_nodeattr(\"dataType\")] # make copy before saving the array reshaped_input", "met: # # * Redistributions of source code must retain", "prepare the IP packaging tcl template template = templates.ip_package_tcl self.code_gen_dict.clear()", "np from shutil import copy import subprocess import math import", "and ip_path to point to the new packaged IP self.set_nodeattr(\"ipgen_path\",", "2 and 256 for efficient SRL implementation\" ) # derive", "depth = self.get_nodeattr(\"depth\") # depth has to be between 2", "\"{}/input_0.npy\".format(code_gen_dir), export_idt, nbits ) super().reset_rtlsim(sim) super().toggle_clk(sim) output = self.rtlsim(sim, inp)", "stdout=subprocess.PIPE) process_compile.communicate() # set ipgen_path and ip_path to point to", "of conditions and the following disclaimer. # # * Redistributions", "node_name) ) cmd.append( \"set_property -dict [list CONFIG.TDATA_NUM_BYTES {%d}] \" \"[get_bd_cells", "2, \"\"\"Depth is too low\"\"\" if depth > 256 and", "2): normal_ishape.append(folded_shape[i]) normal_ishape.append(folding_factor) return normal_ishape def get_normal_output_shape(self): return self.get_normal_input_shape() def", "in_width = self.get_instream_width_padded() count_width = int(self.get_nodeattr(\"depth\") - 1).bit_length() self.code_gen_dict[\"$COUNT_RANGE$\"] =", "PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE,", "ipgen_singlenode_code(self): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name )", "512 return wbits / bram16_est_capacity def lut_estimation(self): \"\"\"Calculates resource estimations", "\"rtlsim\": code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") # create a npy file for", "} my_attrs.update(super().get_nodeattr_types()) return my_attrs def make_shape_compatible_op(self, model): exp_ishape = self.get_normal_input_shape()", "elif mode == \"rtlsim\": code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") # create a", "export_idt = DataType[self.get_nodeattr(\"dataType\")] # make copy before saving the array", "IP pkg script make_project_sh = verilog_dir + \"/make_ip.sh\" working_dir =", "defines(self, var): pass def read_npy_data(self): pass def strm_decl(self): pass def", "4)) elif W <= 9: return (math.ceil(depth / 2048)) *", "18 or depth > 512: return (math.ceil(depth / 1024)) *", "\"vivado\": cmd = [] node_name = self.onnx_node.name depth = self.get_nodeattr(\"depth\")", "\"{}/output.npy\".format(code_gen_dir) out_shape = self.get_folded_output_shape() rtlsim_output_to_npy( output, out_npy_path, odt, out_shape, packed_bits,", "in binary form must reproduce the above copyright notice, #", "ARISING IN ANY WAY OUT OF THE USE # OF", "os.path.join(memstream_dir, \"Q_srl.v\") copy(Q_file, verilog_dir) # empty code gen dictionary for", "binary forms, with or without # modification, are permitted provided", "case (1, mh) # so to achieve this the two", "# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN", "the distribution. # # * Neither the name of FINN", "[] # create the normal_ishape for i in range(len(folded_shape) -", "1: return math.ceil(depth / 16384) elif W == 2: return", "\" \"[get_bd_cells /%s/fifo]\" % (np.ceil(self.get_outstream_width() / 8), node_name) ) cmd.append(", "port names clk_name = self.get_verilog_top_module_intf_names()[\"clk\"][0] rst_name = self.get_verilog_top_module_intf_names()[\"rst\"][0] dout_name =", "oshape = self.get_normal_output_shape() ishape = tuple(model.get_tensor_shape(self.onnx_node.input[0])) assert ishape == tuple(exp_ishape),", "= \"/workspace/finn/finn-rtllib/memstream/hdl/\" Q_file = os.path.join(memstream_dir, \"Q_srl.v\") copy(Q_file, verilog_dir) # empty", "% (node_name, dout_name) ) cmd.append( \"create_bd_intf_pin -mode Slave \" \"-vlnv", "contributors may be used to endorse or promote products derived", "Exception( \"FIFO implementation style %s not supported, please use rtl", "FPGA resource type for FIFOs when impl_style is vivado #", "make_shape_compatible_op(self, model): exp_ishape = self.get_normal_input_shape() oshape = self.get_normal_output_shape() ishape =", "derive normal shape from folded shape # StreamingFIFOs are inserted", "# make copy before saving the array reshaped_input = reshaped_input.copy()", "TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF", "== DataType.BIPOLAR: # store bipolar activations as binary reshaped_input =", "= template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir, \"package_ip.tcl\"), \"w\") f.write(template) f.close()", "SUCH DAMAGE. import os import numpy as np from shutil", "script and call Vivado to invoke the IP pkg script", "\"[get_bd_cells /%s/fifo]\" % (np.ceil(self.get_outstream_width() / 8), node_name) ) cmd.append( \"connect_bd_intf_net", "template = template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir, \"{}.v\".format(self.onnx_node.name)), \"w\") f.write(template)", "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER", "/ 4096)) * (math.ceil(W / 72)) def bram_efficiency_estimation(self): depth =", "verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) os.makedirs(verilog_dir) # copy Q_srl.v", "# All rights reserved. # # Redistribution and use in", "os.environ[\"PWD\"] with open(make_project_sh, \"w\") as f: f.write(\"#!/bin/bash \\n\") f.write(\"cd {}\\n\".format(verilog_dir))", "= template.replace(key, code_gen_line) f = open(os.path.join(verilog_dir, \"{}.v\".format(self.onnx_node.name)), \"w\") f.write(template) f.close()", "verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) # prepare the IP", "(\"s\", True, \"\"), # Toggle between hls or IPI implementation", "Infrastructure FIFO \"impl_style\": (\"s\", False, \"rtl\", {\"rtl\", \"vivado\"}), # FPGA", "\"/workspace/finn/finn-rtllib/memstream/hdl/\" Q_file = os.path.join(memstream_dir, \"Q_srl.v\") copy(Q_file, verilog_dir) # empty code", "idt) def verify_node(self): pass def get_verilog_top_module_name(self): \"Return the Verilog top", "/ 1024)) * (math.ceil(W / 18)) else: return (math.ceil(depth /", "\"input_0.npy\"), reshaped_input) sim = self.get_rtlsim() nbits = self.get_instream_width() inp =", "= self.get_verilog_top_module_intf_names()[\"m_axis\"][0][0] din_name = self.get_verilog_top_module_intf_names()[\"s_axis\"][0][0] cmd.append(\"create_bd_cell -type hier %s\" %", "self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir, self.onnx_node.name ) # prepare the", "verilog_dir + \"/make_ip.sh\" working_dir = os.environ[\"PWD\"] with open(make_project_sh, \"w\") as", "= inp output = np.asarray([output], dtype=np.float32).reshape(*exp_shape) context[node.output[0]] = output elif", "clk_name = self.get_verilog_top_module_intf_names()[\"clk\"][0] rst_name = self.get_verilog_top_module_intf_names()[\"rst\"][0] dout_name = self.get_verilog_top_module_intf_names()[\"m_axis\"][0][0] din_name", "list of conditions and the following disclaimer in the documentation", "or depth > 512: return (math.ceil(depth / 1024)) * (math.ceil(W", "OK self.code_gen_dict[\"$VERILOG_DIR$\"] = [\".\"] for key in self.code_gen_dict: # transform", "shape folded_shape = self.get_nodeattr(\"folded_shape\") # extract inner dimension inner_dim =", "# modification, are permitted provided that the following conditions are", "layer, with the same port names clk_name = self.get_verilog_top_module_intf_names()[\"clk\"][0] rst_name", "resource type for FIFOs when impl_style is vivado # auto", "block -- use BRAM # distributed -- use LUTRAM #", "data_type=TensorProto.FLOAT, dims=values.shape, vals=values.flatten().astype(float), ), ) def infer_node_datatype(self, model): node =", "/ 8), node_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/M_AXIS] \" \"[get_bd_intf_pins", "from onnx import TensorProto, helper from finn.util.data_packing import npy_to_rtlsim_input, rtlsim_output_to_npy", "/ 4096)) * (math.ceil(W / 4)) elif W <= 9:", "following disclaimer in the documentation # and/or other materials provided", "node.name, str(self.get_input_datatype()), str(idt), ) warnings.warn(warn_str) self.set_nodeattr(\"dataType\", idt.name) # data type", "the hls generated IP during stitching # vivado - use", "may be used to endorse or promote products derived from", "the IP packaging tcl template template = templates.ip_package_tcl self.code_gen_dict.clear() self.code_gen_dict[\"$TOPNAME$\"]", "return cmd else: raise Exception( \"FIFO implementation style %s not", "currently set to: {} has to be set to one", "raise Exception( \"\"\"Invalid value for attribute exec_mode! Is currently set", "-- use URAM (on UltraScale+) \"ram_style\": ( \"s\", False, \"auto\",", "return prefixed_top_name def code_generation_ipgen(self, model, fpgapart, clk): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\")", "following conditions are met: # # * Redistributions of source", "sources dir so root_dir=. is OK self.code_gen_dict[\"$VERILOG_DIR$\"] = [\".\"] for", "normal_ishape.append(folding_factor) return normal_ishape def get_normal_output_shape(self): return self.get_normal_input_shape() def get_folded_input_shape(self): return", "= self.get_nodeattr(\"impl_style\") if impl_style == \"rtl\": return super().code_generation_ipi() elif impl_style", "is OK self.code_gen_dict[\"$VERILOG_DIR$\"] = [\".\"] for key in self.code_gen_dict: #", "\"[get_bd_pins %s/fifo/s_axis_aclk]\" % (node_name, clk_name, node_name) ) return cmd else:", "OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "%s not supported, please use rtl or vivado\" % impl_style", "conditions and the following disclaimer. # # * Redistributions in", "can cause path problems # the ipgen script will be", "mh) # so to achieve this the two inner dimensions", "vlnv) self.code_gen_dict.clear() def get_normal_input_shape(self): depth = self.get_nodeattr(\"depth\") # depth has", "def global_includes(self): pass def defines(self, var): pass def read_npy_data(self): pass", "din_name = self.get_verilog_top_module_intf_names()[\"s_axis\"][0][0] cmd.append(\"create_bd_cell -type hier %s\" % node_name) cmd.append(\"create_bd_pin", "self.get_folded_output_shape() rtlsim_output_to_npy( output, out_npy_path, odt, out_shape, packed_bits, target_bits ) #", "finn-rtllib to verilog directory memstream_dir = \"/workspace/finn/finn-rtllib/memstream/hdl/\" Q_file = os.path.join(memstream_dir,", "return (math.ceil(depth / 4096)) * (math.ceil(W / 72)) def bram_efficiency_estimation(self):", "has to be set to one of the following value", "input shape folded_shape = self.get_nodeattr(\"folded_shape\") # extract inner dimension inner_dim", "cmd else: raise Exception( \"FIFO implementation style %s not supported,", "from the sources dir so root_dir=. is OK self.code_gen_dict[\"$VERILOG_DIR$\"] =", "f.write(\"cd {}\\n\".format(working_dir)) bash_command = [\"bash\", make_project_sh] process_compile = subprocess.Popen(bash_command, stdout=subprocess.PIPE)", "node_name, din_name) ) cmd.append( \"connect_bd_net [get_bd_pins %s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aresetn]\"", "-- let Vivado decide # block -- use BRAM #", "elif W <= 4: return (math.ceil(depth / 4096)) * (math.ceil(W", "self.onnx_node inp = context[node.input[0]] exp_shape = self.get_normal_input_shape() if mode ==", "this list of conditions and the following disclaimer in the", "(self.onnx_node.name) self.set_nodeattr(\"ip_vlnv\", vlnv) self.code_gen_dict.clear() def get_normal_input_shape(self): depth = self.get_nodeattr(\"depth\") #", "var): pass def read_npy_data(self): pass def strm_decl(self): pass def docompute(self):", "32)) * (math.ceil(W / 2)) else: ram_luts = 0 return", "str(self.get_input_datatype()), str(idt), ) warnings.warn(warn_str) self.set_nodeattr(\"dataType\", idt.name) # data type stays", "Is currently set to: {} has to be set to", "the following value (\"cppsim\", \"rtlsim\")\"\"\".format( mode ) ) def get_number_output_values(self):", "name of FINN nor the names of its # contributors", "return helper.make_node( \"Constant\", inputs=[], outputs=[self.onnx_node.output[0]], value=helper.make_tensor( name=\"const_tensor\", data_type=TensorProto.FLOAT, dims=values.shape, vals=values.flatten().astype(float),", "a npy file for the input of the node assert", "= folded_shape[-1] * dtype.bitwidth() return in_width def get_outstream_width(self): dtype =", "model, fpgapart, clk): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir = \"{}/project_{}/sol1/impl/verilog\".format( code_gen_dir,", "\"depth\": (\"i\", True, 0), # folded shape of input/output \"folded_shape\":", "assert ishape == tuple(exp_ishape), \"Unexpect input shape for StreamingFIFO.\" #", "output = self.rtlsim(sim, inp) odt = DataType[self.get_nodeattr(\"dataType\")] target_bits = odt.bitwidth()", "vlnv = \"xilinx.com:hls:%s:1.0\" % (self.onnx_node.name) self.set_nodeattr(\"ip_vlnv\", vlnv) self.code_gen_dict.clear() def get_normal_input_shape(self):", "this layer, with the same port names clk_name = self.get_verilog_top_module_intf_names()[\"clk\"][0]", "= self.strm_fifo_wrapper for key in self.code_gen_dict: # transform list into", "self.get_outstream_width() out_npy_path = \"{}/output.npy\".format(code_gen_dir) out_shape = self.get_folded_output_shape() rtlsim_output_to_npy( output, out_npy_path,", "Non-BRAM based implementation return 0 else: return (math.ceil(depth / 4096))", "odt = DataType[self.get_nodeattr(\"dataType\")] target_bits = odt.bitwidth() packed_bits = self.get_outstream_width() out_npy_path", "\"\"\"Calculates resource estimation for BRAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type =", "/ 18)) else: return (math.ceil(depth / 512)) * (math.ceil(W /", "!= \"vivado\", ( \"StreamingFIFO impl_style \" \"cannot be vivado for", "code_generation_ipi(self): impl_style = self.get_nodeattr(\"impl_style\") if impl_style == \"rtl\": return super().code_generation_ipi()", "estimation for URAM\"\"\" impl = self.get_nodeattr(\"impl_style\") ram_type = self.get_nodeattr(\"ram_style\") depth", "ipgen_path and ip_path to point to the new packaged IP", "DataType.BIPOLAR: # store bipolar activations as binary reshaped_input = (reshaped_input", "din_name) ) # instantiate and configure DWC cmd.append( \"create_bd_cell -type", "TensorProto, helper from finn.util.data_packing import npy_to_rtlsim_input, rtlsim_output_to_npy from . import", "8), node_name) ) cmd.append( \"connect_bd_intf_net [get_bd_intf_pins %s/fifo/M_AXIS] \" \"[get_bd_intf_pins %s/%s]\"", "onnx_node): super().__init__(onnx_node) self.strm_fifo_wrapper = templates.strm_fifo_wrapper def get_nodeattr_types(self): my_attrs = {", "{%d}] \" \"[get_bd_cells /%s/fifo]\" % (np.ceil(self.get_outstream_width() / 8), node_name) )", "{ # FIFO depth \"depth\": (\"i\", True, 0), # folded", "-dir I -type rst /%s/%s\" % (node_name, rst_name)) cmd.append( \"create_bd_intf_pin", "math.ceil(depth / 8192) elif W <= 4: return (math.ceil(depth /", "NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND", "use BRAM # distributed -- use LUTRAM # ultra --", "def infer_node_datatype(self, model): node = self.onnx_node idt = model.get_tensor_datatype(node.input[0]) if", "IP self.set_nodeattr(\"ipgen_path\", verilog_dir) self.set_nodeattr(\"ip_path\", verilog_dir) vlnv = \"xilinx.com:hls:%s:1.0\" % (self.onnx_node.name)", "DataType from onnx import TensorProto, helper from finn.util.data_packing import npy_to_rtlsim_input,", "range(len(folded_shape) - 2): normal_ishape.append(folded_shape[i]) normal_ishape.append(folding_factor) return normal_ishape def get_normal_output_shape(self): return", "- use the hls generated IP during stitching # vivado", "\" \"-vlnv xilinx.com:interface:axis_rtl:1.0 /%s/%s\" % (node_name, dout_name) ) cmd.append( \"create_bd_intf_pin", "directory memstream_dir = \"/workspace/finn/finn-rtllib/memstream/hdl/\" Q_file = os.path.join(memstream_dir, \"Q_srl.v\") copy(Q_file, verilog_dir)", "this gives the normal input shape folded_shape = self.get_nodeattr(\"folded_shape\") #", "\"vivado\" and ram_type == \"distributed\"): ram_luts = (math.ceil(depth / 32))", "ram_style = self.get_nodeattr(\"ram_style\") # create a hierarchy for this layer,", "return super().code_generation_ipi() elif impl_style == \"vivado\": cmd = [] node_name", "shape of input/output \"folded_shape\": (\"ints\", True, []), # FINN DataTypes", "hls or IPI implementation # rtl - use the hls", "self.get_nodeattr(\"folded_shape\") def get_instream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\") in_width", "(on UltraScale+) \"ram_style\": ( \"s\", False, \"auto\", {\"auto\", \"block\", \"distributed\",", "output = inp output = np.asarray([output], dtype=np.float32).reshape(*exp_shape) context[node.output[0]] = output", "normal input shape folded_shape = self.get_nodeattr(\"folded_shape\") # extract inner dimension", "derived from # this software without specific prior written permission.", "open(os.path.join(verilog_dir, \"{}.v\".format(self.onnx_node.name)), \"w\") f.write(template) f.close() self.code_gen_dict.clear() def ipgen_singlenode_code(self): code_gen_dir =", "= [\"[{}:0]\".format(in_width - 1)] self.code_gen_dict[\"$WIDTH$\"] = [str(in_width)] self.code_gen_dict[\"$DEPTH$\"] = [str(self.get_nodeattr(\"depth\"))]", "512: return (math.ceil(depth / 1024)) * (math.ceil(W / 18)) else:", "-- use BRAM # distributed -- use LUTRAM # ultra", "else: raise Exception( \"FIFO implementation style %s not supported, please", "impl_style ) def bram_estimation(self): \"\"\"Calculates resource estimation for BRAM\"\"\" impl", "ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,", "def code_generation_ipgen(self, model, fpgapart, clk): code_gen_dir = self.get_nodeattr(\"code_gen_dir_ipgen\") verilog_dir =", "self.strm_fifo_wrapper = templates.strm_fifo_wrapper def get_nodeattr_types(self): my_attrs = { # FIFO", "finn.core.datatype import DataType from onnx import TensorProto, helper from finn.util.data_packing", "of the node assert ( str(inp.dtype) == \"float32\" ), \"\"\"Input", "OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #", "BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #", "%s/%s] \" \"[get_bd_pins %s/fifo/s_axis_aclk]\" % (node_name, clk_name, node_name) ) return", "* math.ceil(math.log(depth, 2)) if impl == \"rtl\" or (impl ==", "= self.rtlsim(sim, inp) odt = DataType[self.get_nodeattr(\"dataType\")] target_bits = odt.bitwidth() packed_bits", "with the same port names clk_name = self.get_verilog_top_module_intf_names()[\"clk\"][0] rst_name =", "return in_width def get_outstream_width(self): dtype = DataType[self.get_nodeattr(\"dataType\")] folded_shape = self.get_nodeattr(\"folded_shape\")" ]
[ "sf['file_size'] = sf['file_size'].apply(lambda sz: (sz / pow(2, 20))) sf.rename(columns =", "df = df.merge(emoji.metadata().drop(columns=['emoji_level']), on='codepoints') df = df[df['status'] == 'fully-qualified'] df", "import os import pandas as pd _SUPPORT_CACHE_CSV = emoji.datafile('emoji_support.csv') _API_LEVELS", "\"7.0\"), 25: (\"Nougat\", \"7.1\"), 26: (\"Oreo\", \"8.0.0\"), 27: (\"Oreo\", \"8.1.0\"),", "\"4.4 - 4.4.4\"), 21: (\"Lollipop\", \"5.0\"), 22: (\"Lollipop\", \"5.1\"), 23:", "df = emoji_support() # merge emoji metadata to gain the", "25: (\"Nougat\", \"7.1\"), 26: (\"Oreo\", \"8.0.0\"), 27: (\"Oreo\", \"8.1.0\"), 28:", "\"7.1\"), 26: (\"Oreo\", \"8.0.0\"), 27: (\"Oreo\", \"8.1.0\"), 28: (\"Pie\", \"9\"),", "converters={'cp_seq': ast.literal_eval}) .rename(columns={'cp_seq': 'codepoints'})) def font_summary(): df = metadata() sf", "28: (\"Pie\", \"9\"), 29: (\"Android 10 (Q)\", \"10\"), 30: (\"Android", "(\"Android 12 (S)\", \"12\"), } def api_levels(): return _API_LEVELS def", "_, ext = os.path.splitext(file) return ext.lower() in {'.ttf', '.otf', '.ttc'}", "8: (\"Froyo\", \"2.2.x \"), 9: (\"Gingerbread\", \"2.3 - 2.3.2 \"),", "(df .groupby(['api_level']) .agg({'font_file': 'count', 'file_size': 'sum'})) sf['file_size'] = sf['file_size'].apply(lambda sz:", "(\"Eclair\", \"2.1 \"), 8: (\"Froyo\", \"2.2.x \"), 9: (\"Gingerbread\", \"2.3", "= df.supported.astype('int32') df['api_level'] = df.font_file.str.split('/').str[1] df.api_level = df.api_level.astype('int32') df['font_file'] =", "df.font_file.str.split('/').str[1] df.api_level = df.api_level.astype('int32') df['font_file'] = df.font_file.str.split('/').str[2] return df def", "in os.walk('api_level'): for file in files: if is_font_file(file): full_file =", "first') return (pd.read_csv(_SUPPORT_CACHE_CSV, converters={'cp_seq': ast.literal_eval}) .rename(columns={'cp_seq': 'codepoints'})) def font_summary(): df", "Sandwich\", \"4.0.3 - 4.0.4 \"), 16: (\"Jelly Bean\", \"4.1.x\"), 17:", "of populate_emoji_support.py\"\"\" if not os.path.isfile(_SUPPORT_CACHE_CSV): raise IOError('Please run populate_emoji_support.py first')", "(\"(no codename)\", \"1.1\"), 3: (\"Cupcake\", \"1.5 \"), 4: (\"Donut\", \"1.6", "12 (S)\", \"12\"), } def api_levels(): return _API_LEVELS def is_font_file(file):", "run populate_emoji_support.py first') return (pd.read_csv(_SUPPORT_CACHE_CSV, converters={'cp_seq': ast.literal_eval}) .rename(columns={'cp_seq': 'codepoints'})) def", "if is_font_file(file): full_file = os.path.join(root, file) api_level = int(os.path.basename(root)) size", "= int(os.path.basename(root)) size = os.stat(full_file).st_size records.append((api_level, full_file, size)) df =", "'size_MB', }, inplace=True) sf['delta_size_MB'] = sf['size_MB'] - sf['size_MB'].shift(1) sf.reset_index(inplace=True) return", "file) api_level = int(os.path.basename(root)) size = os.stat(full_file).st_size records.append((api_level, full_file, size))", "(df.groupby(['font_file', 'api_level', 'emoji_level']) .agg({'supported': ['sum', 'count']})) sf.columns = ['supported', 'total']", "_API_LEVELS = { 1: (\"(no codename)\", \"1.0\"), 2: (\"(no codename)\",", "os.path.splitext(file) return ext.lower() in {'.ttf', '.otf', '.ttc'} def metadata(): records", "column df = df.merge(emoji.metadata().drop(columns=['emoji_level']), on='codepoints') df = df[df['status'] == 'fully-qualified']", "metadata() sf = (df .groupby(['api_level']) .agg({'font_file': 'count', 'file_size': 'sum'})) sf['file_size']", "execution of populate_emoji_support.py\"\"\" if not os.path.isfile(_SUPPORT_CACHE_CSV): raise IOError('Please run populate_emoji_support.py", "22: (\"Lollipop\", \"5.1\"), 23: (\"Marshmallow\", \"6.0\"), 24: (\"Nougat\", \"7.0\"), 25:", "ast.literal_eval}) .rename(columns={'cp_seq': 'codepoints'})) def font_summary(): df = metadata() sf =", "to gain the status column df = df.merge(emoji.metadata().drop(columns=['emoji_level']), on='codepoints') df", "(\"Oreo\", \"8.0.0\"), 27: (\"Oreo\", \"8.1.0\"), 28: (\"Pie\", \"9\"), 29: (\"Android", "} def api_levels(): return _API_LEVELS def is_font_file(file): _, ext =", "(\"Gingerbread\", \"2.3 - 2.3.2 \"), 10: (\"Gingerbread\", \"2.3.3 - 2.3.7\"),", "pow(2, 20))) sf.rename(columns = { 'font_file': 'num_files', 'file_size': 'size_MB', },", "= emoji.datafile('emoji_support.csv') _API_LEVELS = { 1: (\"(no codename)\", \"1.0\"), 2:", "(R)\", \"11\"), 31: (\"Android 12 (S)\", \"12\"), } def api_levels():", "def api_levels(): return _API_LEVELS def is_font_file(file): _, ext = os.path.splitext(file)", "11 (R)\", \"11\"), 31: (\"Android 12 (S)\", \"12\"), } def", "['api_level', 'font_file', 'file_size'] return df def emoji_support(): \"\"\"Dataframe of [emoji_level,", "{ 'font_file': 'num_files', 'file_size': 'size_MB', }, inplace=True) sf['delta_size_MB'] = sf['size_MB']", "(\"Lollipop\", \"5.0\"), 22: (\"Lollipop\", \"5.1\"), 23: (\"Marshmallow\", \"6.0\"), 24: (\"Nougat\",", "records.append((api_level, full_file, size)) df = pd.DataFrame(records) df.columns = ['api_level', 'font_file',", "Bean\", \"4.2.x\"), 18: (\"Jelly Bean\", \"4.3.x\"), 19: (\"KitKat\", \"4.4 -", "(\"Marshmallow\", \"6.0\"), 24: (\"Nougat\", \"7.0\"), 25: (\"Nougat\", \"7.1\"), 26: (\"Oreo\",", "if not os.path.isfile(_SUPPORT_CACHE_CSV): raise IOError('Please run populate_emoji_support.py first') return (pd.read_csv(_SUPPORT_CACHE_CSV,", "\"2.2.x \"), 9: (\"Gingerbread\", \"2.3 - 2.3.2 \"), 10: (\"Gingerbread\",", "sf.reset_index(inplace=True) return sf def emoji_detail(): df = emoji_support() # merge", "4.4.4\"), 21: (\"Lollipop\", \"5.0\"), 22: (\"Lollipop\", \"5.1\"), 23: (\"Marshmallow\", \"6.0\"),", "records = [] for root, dirs, files in os.walk('api_level'): for", "'font_file': 'num_files', 'file_size': 'size_MB', }, inplace=True) sf['delta_size_MB'] = sf['size_MB'] -", "2.3.7\"), 11: (\"Honeycomb\", \"3.0\"), 12: (\"Honeycomb\", \"3.1 \"), 13: (\"Honeycomb\",", "sf2 = (sf.drop(columns='emoji_level') .groupby('api_level') .agg('sum') .reset_index()) sf2['delta'] = sf2['supported'] -", ".reset_index()) sf2['delta'] = sf2['supported'] - sf2['supported'].shift(1) sf2.fillna(0, inplace=True) return sf,", "df = df.drop(columns='status') df.supported = df.supported.astype('int32') df['api_level'] = df.font_file.str.split('/').str[1] df.api_level", "'api_level', 'emoji_level']) .agg({'supported': ['sum', 'count']})) sf.columns = ['supported', 'total'] sf.reset_index(inplace=True)", "= [] for root, dirs, files in os.walk('api_level'): for file", "= (sf.drop(columns='emoji_level') .groupby('api_level') .agg('sum') .reset_index()) sf2['delta'] = sf2['supported'] - sf2['supported'].shift(1)", "'file_size'] return df def emoji_support(): \"\"\"Dataframe of [emoji_level, font_file, codepoints,", "\"), 13: (\"Honeycomb\", \"3.2.x\"), 14: (\"Ice Cream Sandwich\", \"4.0.1 -", "\"8.0.0\"), 27: (\"Oreo\", \"8.1.0\"), 28: (\"Pie\", \"9\"), 29: (\"Android 10", "sf def emoji_detail(): df = emoji_support() # merge emoji metadata", "sf = (df.groupby(['font_file', 'api_level', 'emoji_level']) .agg({'supported': ['sum', 'count']})) sf.columns =", "= df.merge(emoji.metadata().drop(columns=['emoji_level']), on='codepoints') df = df[df['status'] == 'fully-qualified'] df =", "'.ttc'} def metadata(): records = [] for root, dirs, files", "11: (\"Honeycomb\", \"3.0\"), 12: (\"Honeycomb\", \"3.1 \"), 13: (\"Honeycomb\", \"3.2.x\"),", "size)) df = pd.DataFrame(records) df.columns = ['api_level', 'font_file', 'file_size'] return", "pd _SUPPORT_CACHE_CSV = emoji.datafile('emoji_support.csv') _API_LEVELS = { 1: (\"(no codename)\",", "\"\"\"Dataframe of [emoji_level, font_file, codepoints, supported]. Includes every sequence we", "3: (\"Cupcake\", \"1.5 \"), 4: (\"Donut\", \"1.6 \"), 5: (\"Eclair\",", "= df[df['status'] == 'fully-qualified'] df = df.drop(columns='status') df.supported = df.supported.astype('int32')", "= os.path.splitext(file) return ext.lower() in {'.ttf', '.otf', '.ttc'} def metadata():", "(\"Gingerbread\", \"2.3.3 - 2.3.7\"), 11: (\"Honeycomb\", \"3.0\"), 12: (\"Honeycomb\", \"3.1", "(\"Ice Cream Sandwich\", \"4.0.1 - 4.0.2 \"), 15: (\"Ice Cream", "sf['size_MB'] - sf['size_MB'].shift(1) sf.reset_index(inplace=True) return sf def emoji_detail(): df =", "12: (\"Honeycomb\", \"3.1 \"), 13: (\"Honeycomb\", \"3.2.x\"), 14: (\"Ice Cream", "return df def emoji_summary(): df = emoji_detail() sf = (df.groupby(['font_file',", "os.walk('api_level'): for file in files: if is_font_file(file): full_file = os.path.join(root,", "'file_size': 'size_MB', }, inplace=True) sf['delta_size_MB'] = sf['size_MB'] - sf['size_MB'].shift(1) sf.reset_index(inplace=True)", "29: (\"Android 10 (Q)\", \"10\"), 30: (\"Android 11 (R)\", \"11\"),", "ext = os.path.splitext(file) return ext.lower() in {'.ttf', '.otf', '.ttc'} def", "\"5.1\"), 23: (\"Marshmallow\", \"6.0\"), 24: (\"Nougat\", \"7.0\"), 25: (\"Nougat\", \"7.1\"),", "def metadata(): records = [] for root, dirs, files in", "os.path.isfile(_SUPPORT_CACHE_CSV): raise IOError('Please run populate_emoji_support.py first') return (pd.read_csv(_SUPPORT_CACHE_CSV, converters={'cp_seq': ast.literal_eval})", "- 4.0.4 \"), 16: (\"Jelly Bean\", \"4.1.x\"), 17: (\"Jelly Bean\",", "emoji metadata to gain the status column df = df.merge(emoji.metadata().drop(columns=['emoji_level']),", "df.drop(columns='status') df.supported = df.supported.astype('int32') df['api_level'] = df.font_file.str.split('/').str[1] df.api_level = df.api_level.astype('int32')", "df[df['status'] == 'fully-qualified'] df = df.drop(columns='status') df.supported = df.supported.astype('int32') df['api_level']", "the status column df = df.merge(emoji.metadata().drop(columns=['emoji_level']), on='codepoints') df = df[df['status']", "IOError('Please run populate_emoji_support.py first') return (pd.read_csv(_SUPPORT_CACHE_CSV, converters={'cp_seq': ast.literal_eval}) .rename(columns={'cp_seq': 'codepoints'}))", "4.0.4 \"), 16: (\"Jelly Bean\", \"4.1.x\"), 17: (\"Jelly Bean\", \"4.2.x\"),", "sf['file_size'].apply(lambda sz: (sz / pow(2, 20))) sf.rename(columns = { 'font_file':", "(\"Android 10 (Q)\", \"10\"), 30: (\"Android 11 (R)\", \"11\"), 31:", "24: (\"Nougat\", \"7.0\"), 25: (\"Nougat\", \"7.1\"), 26: (\"Oreo\", \"8.0.0\"), 27:", "pandas as pd _SUPPORT_CACHE_CSV = emoji.datafile('emoji_support.csv') _API_LEVELS = { 1:", "os.stat(full_file).st_size records.append((api_level, full_file, size)) df = pd.DataFrame(records) df.columns = ['api_level',", "- 4.0.2 \"), 15: (\"Ice Cream Sandwich\", \"4.0.3 - 4.0.4", "26: (\"Oreo\", \"8.0.0\"), 27: (\"Oreo\", \"8.1.0\"), 28: (\"Pie\", \"9\"), 29:", "(\"Oreo\", \"8.1.0\"), 28: (\"Pie\", \"9\"), 29: (\"Android 10 (Q)\", \"10\"),", "populate_emoji_support.py first') return (pd.read_csv(_SUPPORT_CACHE_CSV, converters={'cp_seq': ast.literal_eval}) .rename(columns={'cp_seq': 'codepoints'})) def font_summary():", "sf.reset_index(inplace=True) sf2 = (sf.drop(columns='emoji_level') .groupby('api_level') .agg('sum') .reset_index()) sf2['delta'] = sf2['supported']", "files: if is_font_file(file): full_file = os.path.join(root, file) api_level = int(os.path.basename(root))", "return sf def emoji_detail(): df = emoji_support() # merge emoji", "any type. Requires prior execution of populate_emoji_support.py\"\"\" if not os.path.isfile(_SUPPORT_CACHE_CSV):", "'count']})) sf.columns = ['supported', 'total'] sf.reset_index(inplace=True) sf2 = (sf.drop(columns='emoji_level') .groupby('api_level')", "font_file, codepoints, supported]. Includes every sequence we could find of", "\"), 4: (\"Donut\", \"1.6 \"), 5: (\"Eclair\", \"2.0\"), 6: (\"Eclair\",", "{ 1: (\"(no codename)\", \"1.0\"), 2: (\"(no codename)\", \"1.1\"), 3:", "'fully-qualified'] df = df.drop(columns='status') df.supported = df.supported.astype('int32') df['api_level'] = df.font_file.str.split('/').str[1]", "= sf['size_MB'] - sf['size_MB'].shift(1) sf.reset_index(inplace=True) return sf def emoji_detail(): df", "emoji_support() # merge emoji metadata to gain the status column", "df.merge(emoji.metadata().drop(columns=['emoji_level']), on='codepoints') df = df[df['status'] == 'fully-qualified'] df = df.drop(columns='status')", "root, dirs, files in os.walk('api_level'): for file in files: if", "\"3.2.x\"), 14: (\"Ice Cream Sandwich\", \"4.0.1 - 4.0.2 \"), 15:", "== 'fully-qualified'] df = df.drop(columns='status') df.supported = df.supported.astype('int32') df['api_level'] =", "(\"Nougat\", \"7.1\"), 26: (\"Oreo\", \"8.0.0\"), 27: (\"Oreo\", \"8.1.0\"), 28: (\"Pie\",", "of any type. Requires prior execution of populate_emoji_support.py\"\"\" if not", "['supported', 'total'] sf.reset_index(inplace=True) sf2 = (sf.drop(columns='emoji_level') .groupby('api_level') .agg('sum') .reset_index()) sf2['delta']", "= df.font_file.str.split('/').str[2] return df def emoji_summary(): df = emoji_detail() sf", "\"1.0\"), 2: (\"(no codename)\", \"1.1\"), 3: (\"Cupcake\", \"1.5 \"), 4:", "\"5.0\"), 22: (\"Lollipop\", \"5.1\"), 23: (\"Marshmallow\", \"6.0\"), 24: (\"Nougat\", \"7.0\"),", "= metadata() sf = (df .groupby(['api_level']) .agg({'font_file': 'count', 'file_size': 'sum'}))", "\"1.1\"), 3: (\"Cupcake\", \"1.5 \"), 4: (\"Donut\", \"1.6 \"), 5:", "status column df = df.merge(emoji.metadata().drop(columns=['emoji_level']), on='codepoints') df = df[df['status'] ==", "18: (\"Jelly Bean\", \"4.3.x\"), 19: (\"KitKat\", \"4.4 - 4.4.4\"), 21:", "_API_LEVELS def is_font_file(file): _, ext = os.path.splitext(file) return ext.lower() in", "pd.DataFrame(records) df.columns = ['api_level', 'font_file', 'file_size'] return df def emoji_support():", "16: (\"Jelly Bean\", \"4.1.x\"), 17: (\"Jelly Bean\", \"4.2.x\"), 18: (\"Jelly", "(\"Ice Cream Sandwich\", \"4.0.3 - 4.0.4 \"), 16: (\"Jelly Bean\",", "(\"Jelly Bean\", \"4.2.x\"), 18: (\"Jelly Bean\", \"4.3.x\"), 19: (\"KitKat\", \"4.4", "\"6.0\"), 24: (\"Nougat\", \"7.0\"), 25: (\"Nougat\", \"7.1\"), 26: (\"Oreo\", \"8.0.0\"),", "\"3.0\"), 12: (\"Honeycomb\", \"3.1 \"), 13: (\"Honeycomb\", \"3.2.x\"), 14: (\"Ice", "on='codepoints') df = df[df['status'] == 'fully-qualified'] df = df.drop(columns='status') df.supported", "supported]. Includes every sequence we could find of any type.", "import pandas as pd _SUPPORT_CACHE_CSV = emoji.datafile('emoji_support.csv') _API_LEVELS = {", "of [emoji_level, font_file, codepoints, supported]. Includes every sequence we could", "emoji_detail(): df = emoji_support() # merge emoji metadata to gain", "21: (\"Lollipop\", \"5.0\"), 22: (\"Lollipop\", \"5.1\"), 23: (\"Marshmallow\", \"6.0\"), 24:", "[emoji_level, font_file, codepoints, supported]. Includes every sequence we could find", "(\"Android 11 (R)\", \"11\"), 31: (\"Android 12 (S)\", \"12\"), }", "df.api_level.astype('int32') df['font_file'] = df.font_file.str.split('/').str[2] return df def emoji_summary(): df =", "dirs, files in os.walk('api_level'): for file in files: if is_font_file(file):", ".agg({'supported': ['sum', 'count']})) sf.columns = ['supported', 'total'] sf.reset_index(inplace=True) sf2 =", "= (df .groupby(['api_level']) .agg({'font_file': 'count', 'file_size': 'sum'})) sf['file_size'] = sf['file_size'].apply(lambda", "14: (\"Ice Cream Sandwich\", \"4.0.1 - 4.0.2 \"), 15: (\"Ice", "[] for root, dirs, files in os.walk('api_level'): for file in", "'num_files', 'file_size': 'size_MB', }, inplace=True) sf['delta_size_MB'] = sf['size_MB'] - sf['size_MB'].shift(1)", "5: (\"Eclair\", \"2.0\"), 6: (\"Eclair\", \"2.0.1\"), 7: (\"Eclair\", \"2.1 \"),", "df = df[df['status'] == 'fully-qualified'] df = df.drop(columns='status') df.supported =", "\"4.3.x\"), 19: (\"KitKat\", \"4.4 - 4.4.4\"), 21: (\"Lollipop\", \"5.0\"), 22:", "full_file, size)) df = pd.DataFrame(records) df.columns = ['api_level', 'font_file', 'file_size']", "raise IOError('Please run populate_emoji_support.py first') return (pd.read_csv(_SUPPORT_CACHE_CSV, converters={'cp_seq': ast.literal_eval}) .rename(columns={'cp_seq':", "gain the status column df = df.merge(emoji.metadata().drop(columns=['emoji_level']), on='codepoints') df =", "df = metadata() sf = (df .groupby(['api_level']) .agg({'font_file': 'count', 'file_size':", "10: (\"Gingerbread\", \"2.3.3 - 2.3.7\"), 11: (\"Honeycomb\", \"3.0\"), 12: (\"Honeycomb\",", "2.3.2 \"), 10: (\"Gingerbread\", \"2.3.3 - 2.3.7\"), 11: (\"Honeycomb\", \"3.0\"),", "= (df.groupby(['font_file', 'api_level', 'emoji_level']) .agg({'supported': ['sum', 'count']})) sf.columns = ['supported',", "(\"Donut\", \"1.6 \"), 5: (\"Eclair\", \"2.0\"), 6: (\"Eclair\", \"2.0.1\"), 7:", "7: (\"Eclair\", \"2.1 \"), 8: (\"Froyo\", \"2.2.x \"), 9: (\"Gingerbread\",", "- 2.3.2 \"), 10: (\"Gingerbread\", \"2.3.3 - 2.3.7\"), 11: (\"Honeycomb\",", "emoji_summary(): df = emoji_detail() sf = (df.groupby(['font_file', 'api_level', 'emoji_level']) .agg({'supported':", "full_file = os.path.join(root, file) api_level = int(os.path.basename(root)) size = os.stat(full_file).st_size", "- 2.3.7\"), 11: (\"Honeycomb\", \"3.0\"), 12: (\"Honeycomb\", \"3.1 \"), 13:", "13: (\"Honeycomb\", \"3.2.x\"), 14: (\"Ice Cream Sandwich\", \"4.0.1 - 4.0.2", "in files: if is_font_file(file): full_file = os.path.join(root, file) api_level =", "\"2.0\"), 6: (\"Eclair\", \"2.0.1\"), 7: (\"Eclair\", \"2.1 \"), 8: (\"Froyo\",", "we could find of any type. Requires prior execution of", "sf = (df .groupby(['api_level']) .agg({'font_file': 'count', 'file_size': 'sum'})) sf['file_size'] =", "os.path.join(root, file) api_level = int(os.path.basename(root)) size = os.stat(full_file).st_size records.append((api_level, full_file,", "as pd _SUPPORT_CACHE_CSV = emoji.datafile('emoji_support.csv') _API_LEVELS = { 1: (\"(no", "(\"Eclair\", \"2.0.1\"), 7: (\"Eclair\", \"2.1 \"), 8: (\"Froyo\", \"2.2.x \"),", "df def emoji_support(): \"\"\"Dataframe of [emoji_level, font_file, codepoints, supported]. Includes", "def font_summary(): df = metadata() sf = (df .groupby(['api_level']) .agg({'font_file':", "prior execution of populate_emoji_support.py\"\"\" if not os.path.isfile(_SUPPORT_CACHE_CSV): raise IOError('Please run", "(\"KitKat\", \"4.4 - 4.4.4\"), 21: (\"Lollipop\", \"5.0\"), 22: (\"Lollipop\", \"5.1\"),", "def emoji_detail(): df = emoji_support() # merge emoji metadata to", "is_font_file(file): full_file = os.path.join(root, file) api_level = int(os.path.basename(root)) size =", "}, inplace=True) sf['delta_size_MB'] = sf['size_MB'] - sf['size_MB'].shift(1) sf.reset_index(inplace=True) return sf", "= sf['file_size'].apply(lambda sz: (sz / pow(2, 20))) sf.rename(columns = {", "codename)\", \"1.0\"), 2: (\"(no codename)\", \"1.1\"), 3: (\"Cupcake\", \"1.5 \"),", "\"), 8: (\"Froyo\", \"2.2.x \"), 9: (\"Gingerbread\", \"2.3 - 2.3.2", "(Q)\", \"10\"), 30: (\"Android 11 (R)\", \"11\"), 31: (\"Android 12", "df.font_file.str.split('/').str[2] return df def emoji_summary(): df = emoji_detail() sf =", "return ext.lower() in {'.ttf', '.otf', '.ttc'} def metadata(): records =", "type. Requires prior execution of populate_emoji_support.py\"\"\" if not os.path.isfile(_SUPPORT_CACHE_CSV): raise", "sf2['delta'] = sf2['supported'] - sf2['supported'].shift(1) sf2.fillna(0, inplace=True) return sf, sf2", "(\"Honeycomb\", \"3.1 \"), 13: (\"Honeycomb\", \"3.2.x\"), 14: (\"Ice Cream Sandwich\",", "file in files: if is_font_file(file): full_file = os.path.join(root, file) api_level", "return df def emoji_support(): \"\"\"Dataframe of [emoji_level, font_file, codepoints, supported].", "(\"Pie\", \"9\"), 29: (\"Android 10 (Q)\", \"10\"), 30: (\"Android 11", "return _API_LEVELS def is_font_file(file): _, ext = os.path.splitext(file) return ext.lower()", "df.api_level = df.api_level.astype('int32') df['font_file'] = df.font_file.str.split('/').str[2] return df def emoji_summary():", "\"2.1 \"), 8: (\"Froyo\", \"2.2.x \"), 9: (\"Gingerbread\", \"2.3 -", "= os.path.join(root, file) api_level = int(os.path.basename(root)) size = os.stat(full_file).st_size records.append((api_level,", "Requires prior execution of populate_emoji_support.py\"\"\" if not os.path.isfile(_SUPPORT_CACHE_CSV): raise IOError('Please", "= { 'font_file': 'num_files', 'file_size': 'size_MB', }, inplace=True) sf['delta_size_MB'] =", "\"), 15: (\"Ice Cream Sandwich\", \"4.0.3 - 4.0.4 \"), 16:", "merge emoji metadata to gain the status column df =", "codepoints, supported]. Includes every sequence we could find of any", "'codepoints'})) def font_summary(): df = metadata() sf = (df .groupby(['api_level'])", "(\"Jelly Bean\", \"4.1.x\"), 17: (\"Jelly Bean\", \"4.2.x\"), 18: (\"Jelly Bean\",", "= ['supported', 'total'] sf.reset_index(inplace=True) sf2 = (sf.drop(columns='emoji_level') .groupby('api_level') .agg('sum') .reset_index())", "\"2.3 - 2.3.2 \"), 10: (\"Gingerbread\", \"2.3.3 - 2.3.7\"), 11:", "(sf.drop(columns='emoji_level') .groupby('api_level') .agg('sum') .reset_index()) sf2['delta'] = sf2['supported'] - sf2['supported'].shift(1) sf2.fillna(0,", "2: (\"(no codename)\", \"1.1\"), 3: (\"Cupcake\", \"1.5 \"), 4: (\"Donut\",", "Bean\", \"4.3.x\"), 19: (\"KitKat\", \"4.4 - 4.4.4\"), 21: (\"Lollipop\", \"5.0\"),", "df['api_level'] = df.font_file.str.split('/').str[1] df.api_level = df.api_level.astype('int32') df['font_file'] = df.font_file.str.split('/').str[2] return", "metadata(): records = [] for root, dirs, files in os.walk('api_level'):", "27: (\"Oreo\", \"8.1.0\"), 28: (\"Pie\", \"9\"), 29: (\"Android 10 (Q)\",", "['sum', 'count']})) sf.columns = ['supported', 'total'] sf.reset_index(inplace=True) sf2 = (sf.drop(columns='emoji_level')", "\"), 9: (\"Gingerbread\", \"2.3 - 2.3.2 \"), 10: (\"Gingerbread\", \"2.3.3", "Bean\", \"4.1.x\"), 17: (\"Jelly Bean\", \"4.2.x\"), 18: (\"Jelly Bean\", \"4.3.x\"),", "- sf['size_MB'].shift(1) sf.reset_index(inplace=True) return sf def emoji_detail(): df = emoji_support()", "31: (\"Android 12 (S)\", \"12\"), } def api_levels(): return _API_LEVELS", "could find of any type. Requires prior execution of populate_emoji_support.py\"\"\"", "Includes every sequence we could find of any type. Requires", "4: (\"Donut\", \"1.6 \"), 5: (\"Eclair\", \"2.0\"), 6: (\"Eclair\", \"2.0.1\"),", "'file_size': 'sum'})) sf['file_size'] = sf['file_size'].apply(lambda sz: (sz / pow(2, 20)))", "= ['api_level', 'font_file', 'file_size'] return df def emoji_support(): \"\"\"Dataframe of", "\"), 16: (\"Jelly Bean\", \"4.1.x\"), 17: (\"Jelly Bean\", \"4.2.x\"), 18:", "(S)\", \"12\"), } def api_levels(): return _API_LEVELS def is_font_file(file): _,", "(sz / pow(2, 20))) sf.rename(columns = { 'font_file': 'num_files', 'file_size':", "(\"Froyo\", \"2.2.x \"), 9: (\"Gingerbread\", \"2.3 - 2.3.2 \"), 10:", "df = emoji_detail() sf = (df.groupby(['font_file', 'api_level', 'emoji_level']) .agg({'supported': ['sum',", "(\"Nougat\", \"7.0\"), 25: (\"Nougat\", \"7.1\"), 26: (\"Oreo\", \"8.0.0\"), 27: (\"Oreo\",", "= { 1: (\"(no codename)\", \"1.0\"), 2: (\"(no codename)\", \"1.1\"),", "= df.drop(columns='status') df.supported = df.supported.astype('int32') df['api_level'] = df.font_file.str.split('/').str[1] df.api_level =", "ast import emoji import os import pandas as pd _SUPPORT_CACHE_CSV", "\"4.0.3 - 4.0.4 \"), 16: (\"Jelly Bean\", \"4.1.x\"), 17: (\"Jelly", "\"9\"), 29: (\"Android 10 (Q)\", \"10\"), 30: (\"Android 11 (R)\",", "23: (\"Marshmallow\", \"6.0\"), 24: (\"Nougat\", \"7.0\"), 25: (\"Nougat\", \"7.1\"), 26:", "size = os.stat(full_file).st_size records.append((api_level, full_file, size)) df = pd.DataFrame(records) df.columns", "(pd.read_csv(_SUPPORT_CACHE_CSV, converters={'cp_seq': ast.literal_eval}) .rename(columns={'cp_seq': 'codepoints'})) def font_summary(): df = metadata()", "sf.rename(columns = { 'font_file': 'num_files', 'file_size': 'size_MB', }, inplace=True) sf['delta_size_MB']", "emoji.datafile('emoji_support.csv') _API_LEVELS = { 1: (\"(no codename)\", \"1.0\"), 2: (\"(no", "- 4.4.4\"), 21: (\"Lollipop\", \"5.0\"), 22: (\"Lollipop\", \"5.1\"), 23: (\"Marshmallow\",", "15: (\"Ice Cream Sandwich\", \"4.0.3 - 4.0.4 \"), 16: (\"Jelly", "import ast import emoji import os import pandas as pd", "\"1.5 \"), 4: (\"Donut\", \"1.6 \"), 5: (\"Eclair\", \"2.0\"), 6:", "\"4.0.1 - 4.0.2 \"), 15: (\"Ice Cream Sandwich\", \"4.0.3 -", "find of any type. Requires prior execution of populate_emoji_support.py\"\"\" if", "def is_font_file(file): _, ext = os.path.splitext(file) return ext.lower() in {'.ttf',", "'sum'})) sf['file_size'] = sf['file_size'].apply(lambda sz: (sz / pow(2, 20))) sf.rename(columns", "= df.font_file.str.split('/').str[1] df.api_level = df.api_level.astype('int32') df['font_file'] = df.font_file.str.split('/').str[2] return df", "int(os.path.basename(root)) size = os.stat(full_file).st_size records.append((api_level, full_file, size)) df = pd.DataFrame(records)", "'font_file', 'file_size'] return df def emoji_support(): \"\"\"Dataframe of [emoji_level, font_file,", "30: (\"Android 11 (R)\", \"11\"), 31: (\"Android 12 (S)\", \"12\"),", ".groupby('api_level') .agg('sum') .reset_index()) sf2['delta'] = sf2['supported'] - sf2['supported'].shift(1) sf2.fillna(0, inplace=True)", "sf['size_MB'].shift(1) sf.reset_index(inplace=True) return sf def emoji_detail(): df = emoji_support() #", "1: (\"(no codename)\", \"1.0\"), 2: (\"(no codename)\", \"1.1\"), 3: (\"Cupcake\",", "{'.ttf', '.otf', '.ttc'} def metadata(): records = [] for root,", "(\"Eclair\", \"2.0\"), 6: (\"Eclair\", \"2.0.1\"), 7: (\"Eclair\", \"2.1 \"), 8:", "df['font_file'] = df.font_file.str.split('/').str[2] return df def emoji_summary(): df = emoji_detail()", "df = pd.DataFrame(records) df.columns = ['api_level', 'font_file', 'file_size'] return df", "/ pow(2, 20))) sf.rename(columns = { 'font_file': 'num_files', 'file_size': 'size_MB',", "\"8.1.0\"), 28: (\"Pie\", \"9\"), 29: (\"Android 10 (Q)\", \"10\"), 30:", "files in os.walk('api_level'): for file in files: if is_font_file(file): full_file", "emoji_detail() sf = (df.groupby(['font_file', 'api_level', 'emoji_level']) .agg({'supported': ['sum', 'count']})) sf.columns", "Cream Sandwich\", \"4.0.1 - 4.0.2 \"), 15: (\"Ice Cream Sandwich\",", "emoji_support(): \"\"\"Dataframe of [emoji_level, font_file, codepoints, supported]. Includes every sequence", "os import pandas as pd _SUPPORT_CACHE_CSV = emoji.datafile('emoji_support.csv') _API_LEVELS =", ".rename(columns={'cp_seq': 'codepoints'})) def font_summary(): df = metadata() sf = (df", ".agg('sum') .reset_index()) sf2['delta'] = sf2['supported'] - sf2['supported'].shift(1) sf2.fillna(0, inplace=True) return", ".groupby(['api_level']) .agg({'font_file': 'count', 'file_size': 'sum'})) sf['file_size'] = sf['file_size'].apply(lambda sz: (sz", "font_summary(): df = metadata() sf = (df .groupby(['api_level']) .agg({'font_file': 'count',", "metadata to gain the status column df = df.merge(emoji.metadata().drop(columns=['emoji_level']), on='codepoints')", "sequence we could find of any type. Requires prior execution", "= emoji_support() # merge emoji metadata to gain the status", "for root, dirs, files in os.walk('api_level'): for file in files:", "4.0.2 \"), 15: (\"Ice Cream Sandwich\", \"4.0.3 - 4.0.4 \"),", "is_font_file(file): _, ext = os.path.splitext(file) return ext.lower() in {'.ttf', '.otf',", "inplace=True) sf['delta_size_MB'] = sf['size_MB'] - sf['size_MB'].shift(1) sf.reset_index(inplace=True) return sf def", "\"), 5: (\"Eclair\", \"2.0\"), 6: (\"Eclair\", \"2.0.1\"), 7: (\"Eclair\", \"2.1", "20))) sf.rename(columns = { 'font_file': 'num_files', 'file_size': 'size_MB', }, inplace=True)", "Cream Sandwich\", \"4.0.3 - 4.0.4 \"), 16: (\"Jelly Bean\", \"4.1.x\"),", "\"3.1 \"), 13: (\"Honeycomb\", \"3.2.x\"), 14: (\"Ice Cream Sandwich\", \"4.0.1", "_SUPPORT_CACHE_CSV = emoji.datafile('emoji_support.csv') _API_LEVELS = { 1: (\"(no codename)\", \"1.0\"),", "'.otf', '.ttc'} def metadata(): records = [] for root, dirs,", "\"11\"), 31: (\"Android 12 (S)\", \"12\"), } def api_levels(): return", "populate_emoji_support.py\"\"\" if not os.path.isfile(_SUPPORT_CACHE_CSV): raise IOError('Please run populate_emoji_support.py first') return", "17: (\"Jelly Bean\", \"4.2.x\"), 18: (\"Jelly Bean\", \"4.3.x\"), 19: (\"KitKat\",", "\"2.0.1\"), 7: (\"Eclair\", \"2.1 \"), 8: (\"Froyo\", \"2.2.x \"), 9:", "(\"(no codename)\", \"1.0\"), 2: (\"(no codename)\", \"1.1\"), 3: (\"Cupcake\", \"1.5", "import emoji import os import pandas as pd _SUPPORT_CACHE_CSV =", "'emoji_level']) .agg({'supported': ['sum', 'count']})) sf.columns = ['supported', 'total'] sf.reset_index(inplace=True) sf2", "# merge emoji metadata to gain the status column df", "codename)\", \"1.1\"), 3: (\"Cupcake\", \"1.5 \"), 4: (\"Donut\", \"1.6 \"),", "sf.columns = ['supported', 'total'] sf.reset_index(inplace=True) sf2 = (sf.drop(columns='emoji_level') .groupby('api_level') .agg('sum')", "(\"Jelly Bean\", \"4.3.x\"), 19: (\"KitKat\", \"4.4 - 4.4.4\"), 21: (\"Lollipop\",", "= emoji_detail() sf = (df.groupby(['font_file', 'api_level', 'emoji_level']) .agg({'supported': ['sum', 'count']}))", "api_levels(): return _API_LEVELS def is_font_file(file): _, ext = os.path.splitext(file) return", "def emoji_support(): \"\"\"Dataframe of [emoji_level, font_file, codepoints, supported]. Includes every", "sz: (sz / pow(2, 20))) sf.rename(columns = { 'font_file': 'num_files',", "for file in files: if is_font_file(file): full_file = os.path.join(root, file)", "emoji import os import pandas as pd _SUPPORT_CACHE_CSV = emoji.datafile('emoji_support.csv')", "every sequence we could find of any type. Requires prior", "df.supported = df.supported.astype('int32') df['api_level'] = df.font_file.str.split('/').str[1] df.api_level = df.api_level.astype('int32') df['font_file']", "sf['delta_size_MB'] = sf['size_MB'] - sf['size_MB'].shift(1) sf.reset_index(inplace=True) return sf def emoji_detail():", "api_level = int(os.path.basename(root)) size = os.stat(full_file).st_size records.append((api_level, full_file, size)) df", "ext.lower() in {'.ttf', '.otf', '.ttc'} def metadata(): records = []", "19: (\"KitKat\", \"4.4 - 4.4.4\"), 21: (\"Lollipop\", \"5.0\"), 22: (\"Lollipop\",", "(\"Honeycomb\", \"3.0\"), 12: (\"Honeycomb\", \"3.1 \"), 13: (\"Honeycomb\", \"3.2.x\"), 14:", "\"1.6 \"), 5: (\"Eclair\", \"2.0\"), 6: (\"Eclair\", \"2.0.1\"), 7: (\"Eclair\",", "10 (Q)\", \"10\"), 30: (\"Android 11 (R)\", \"11\"), 31: (\"Android", "\"2.3.3 - 2.3.7\"), 11: (\"Honeycomb\", \"3.0\"), 12: (\"Honeycomb\", \"3.1 \"),", "not os.path.isfile(_SUPPORT_CACHE_CSV): raise IOError('Please run populate_emoji_support.py first') return (pd.read_csv(_SUPPORT_CACHE_CSV, converters={'cp_seq':", "\"), 10: (\"Gingerbread\", \"2.3.3 - 2.3.7\"), 11: (\"Honeycomb\", \"3.0\"), 12:", "in {'.ttf', '.otf', '.ttc'} def metadata(): records = [] for", "= os.stat(full_file).st_size records.append((api_level, full_file, size)) df = pd.DataFrame(records) df.columns =", "= df.api_level.astype('int32') df['font_file'] = df.font_file.str.split('/').str[2] return df def emoji_summary(): df", "(\"Cupcake\", \"1.5 \"), 4: (\"Donut\", \"1.6 \"), 5: (\"Eclair\", \"2.0\"),", "return (pd.read_csv(_SUPPORT_CACHE_CSV, converters={'cp_seq': ast.literal_eval}) .rename(columns={'cp_seq': 'codepoints'})) def font_summary(): df =", "\"4.1.x\"), 17: (\"Jelly Bean\", \"4.2.x\"), 18: (\"Jelly Bean\", \"4.3.x\"), 19:", "'total'] sf.reset_index(inplace=True) sf2 = (sf.drop(columns='emoji_level') .groupby('api_level') .agg('sum') .reset_index()) sf2['delta'] =", ".agg({'font_file': 'count', 'file_size': 'sum'})) sf['file_size'] = sf['file_size'].apply(lambda sz: (sz /", "\"10\"), 30: (\"Android 11 (R)\", \"11\"), 31: (\"Android 12 (S)\",", "\"4.2.x\"), 18: (\"Jelly Bean\", \"4.3.x\"), 19: (\"KitKat\", \"4.4 - 4.4.4\"),", "= pd.DataFrame(records) df.columns = ['api_level', 'font_file', 'file_size'] return df def", "(\"Honeycomb\", \"3.2.x\"), 14: (\"Ice Cream Sandwich\", \"4.0.1 - 4.0.2 \"),", "6: (\"Eclair\", \"2.0.1\"), 7: (\"Eclair\", \"2.1 \"), 8: (\"Froyo\", \"2.2.x", "def emoji_summary(): df = emoji_detail() sf = (df.groupby(['font_file', 'api_level', 'emoji_level'])", "'count', 'file_size': 'sum'})) sf['file_size'] = sf['file_size'].apply(lambda sz: (sz / pow(2,", "(\"Lollipop\", \"5.1\"), 23: (\"Marshmallow\", \"6.0\"), 24: (\"Nougat\", \"7.0\"), 25: (\"Nougat\",", "df.columns = ['api_level', 'font_file', 'file_size'] return df def emoji_support(): \"\"\"Dataframe", "\"12\"), } def api_levels(): return _API_LEVELS def is_font_file(file): _, ext", "9: (\"Gingerbread\", \"2.3 - 2.3.2 \"), 10: (\"Gingerbread\", \"2.3.3 -", "df.supported.astype('int32') df['api_level'] = df.font_file.str.split('/').str[1] df.api_level = df.api_level.astype('int32') df['font_file'] = df.font_file.str.split('/').str[2]", "Sandwich\", \"4.0.1 - 4.0.2 \"), 15: (\"Ice Cream Sandwich\", \"4.0.3", "df def emoji_summary(): df = emoji_detail() sf = (df.groupby(['font_file', 'api_level'," ]
[ "a 403 Forbidden response to anonymous users if the FORBID_ANONYMOUS_CREATE", "import constant, create_snippet, create_user class SnippetListTestCase(SnippetListTestCaseMixin, APITestCase): \"\"\"Tests for the", "self.assertEqual(response.data[1]['content'], 'bar') def test_get_private(self): \"\"\"Snippet list GET must return private", "self.post(content='foo', title=title) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_invalid(self): \"\"\"Snippet list POST must", "Bad Request response if the title field consists of more", "import APITestCase from paste import constants from tests.mixins import SnippetListTestCaseMixin", "def test_post_success(self): \"\"\"Snippet list POST must create a new snippet.\"\"\"", "the proper content-type, and return the response. \"\"\" return self.client.post(", "return private snippets only to those authorized to view them.", "status.HTTP_201_CREATED) self.assertEqual(response.data['content'], 'foo') self.assertEqual(response.data['title'], '') self.assertEqual(response.data['language'], '') self.assertEqual(response.data['style'], 'friendly') self.assertEqual(", "users who attempt to create a private snippet. \"\"\" response", "expected = ( [status.HTTP_403_FORBIDDEN] + [status.HTTP_400_BAD_REQUEST] * 2) def check(i):", "self.check_post_forbid_anonymous('FORBID_ANONYMOUS') def test_post_forbid_anonymous_create(self): \"\"\"Snippet list POST must return a 403", "def check(i): response = self.get() self.assertEqual(len(response.data), expected[i]) with constant('LIST_FOREIGN', False):", "if no content field is set. \"\"\" response = self.post(title='foo')", "[status.HTTP_400_BAD_REQUEST] * 2) def check(i): response = self.post() self.assertEqual(response.status_code, expected[i])", "POST must store currently authenticated user as the newly created", "list view.\"\"\" def url(self): \"\"\"Return the snippet list URL.\"\"\" return", "'foo', field: '123-invalid-abc'}) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST) def check_post_forbid_anonymous(self, setting): \"\"\"Check", "import constants from tests.mixins import SnippetListTestCaseMixin from tests.utils import constant,", "test_post_forbid_anonymous(self): \"\"\"Snippet list POST must return a 403 Forbidden response", "True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS') def test_post_forbid_anonymous_create(self): \"\"\"Snippet list POST must return", "if the FORBID_ANONYMOUS_CREATE setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS_CREATE') def test_post_anonymous_private(self):", "user. \"\"\" create_snippet('foo') create_snippet('bar', owner=self.user) expected = [0, 1, 2]", "users if the LIST_FOREIGN setting is True, unless requested by", "check(i): response = self.get() self.assertEqual(len(response.data), expected[i]) with constant('LIST_FOREIGN', False): self.check_for_users(check)", "consists of more characters than the TITLE_MAX_LENGTH setting indicates. \"\"\"", "set. \"\"\" response = self.post(title='foo') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_oversized_title(self): \"\"\"Snippet", "the view's URL with data indicated by given kwargs, as", "who attempt to create a private snippet. \"\"\" response =", "test_post_success(self): \"\"\"Snippet list POST must create a new snippet.\"\"\" response", "status.HTTP_400_BAD_REQUEST) def test_post_oversized_title(self): \"\"\"Snippet list POST must return a 400", "must return a 403 Forbidden response to anonymous users if", "using the proper content-type, and return the response. \"\"\" return", "from tests.mixins import SnippetListTestCaseMixin from tests.utils import constant, create_snippet, create_user", "self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_oversized_title(self): \"\"\"Snippet list POST must return a", "create_user class SnippetListTestCase(SnippetListTestCaseMixin, APITestCase): \"\"\"Tests for the snippet list view.\"\"\"", "Bad Request response if a value different than the available", "[0, 1, 2] def check(i): response = self.get() self.assertEqual(len(response.data), expected[i])", "title=title) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_invalid(self): \"\"\"Snippet list POST must return", "expected[i]) with constant('LIST_FOREIGN', False): self.check_for_users(check) def test_post_success(self): \"\"\"Snippet list POST", "'friendly') self.assertEqual( response.data['line_numbers'], constants.DEFAULT_LINE_NUMBERS) self.assertFalse(response.data['embed_title']) self.assertEqual(response.data['private'], constants.DEFAULT_PRIVATE) self.assertIsNone(response.data['owner']) def test_post_owner(self):", "def test_post_anonymous_private(self): \"\"\"Snippet list POST must return a 400 Bad", "set for a multiple choice field. \"\"\" for field in", "the given setting is True. \"\"\" expected = ( [status.HTTP_403_FORBIDDEN]", "return a 403 Forbidden response to anonymous users if the", "to anonymous users if the given setting is True. \"\"\"", "the LIST_FOREIGN setting is True, unless requested by a staff", "expected = [0, 1, 2] def check(i): response = self.get()", "SnippetListTestCase(SnippetListTestCaseMixin, APITestCase): \"\"\"Tests for the snippet list view.\"\"\" def url(self):", "status.HTTP_400_BAD_REQUEST) def check_post_forbid_anonymous(self, setting): \"\"\"Check that snippet list POST returns", "must return a 400 Bad Request response to anonymous users", "must return all the viewable snippets.\"\"\" create_snippet('foo') create_snippet('bar') response =", "self.assertEqual(response.data['style'], 'friendly') self.assertEqual( response.data['line_numbers'], constants.DEFAULT_LINE_NUMBERS) self.assertFalse(response.data['embed_title']) self.assertEqual(response.data['private'], constants.DEFAULT_PRIVATE) self.assertIsNone(response.data['owner']) def", "test_post_forbid_anonymous_create(self): \"\"\"Snippet list POST must return a 403 Forbidden response", "self.url(), data=json.dumps(kwargs), content_type='application/json') def test_get_success(self): \"\"\"Snippet list GET must return", "(constants.TITLE_MAX_LENGTH + 1) response = self.post(content='foo', title=title) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def", "self.assertIsNone(response.data['owner']) def test_post_owner(self): \"\"\"Snippet list POST must store currently authenticated", "indicated by given kwargs, as JSON, using the proper content-type,", "reverse('snippet-list') def post(self, **kwargs): \"\"\"Send a POST request to the", "Forbidden response to anonymous users if the given setting is", "self.post( **{'content': 'foo', field: '123-invalid-abc'}) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST) def check_post_forbid_anonymous(self,", "constants.DEFAULT_LINE_NUMBERS) self.assertFalse(response.data['embed_title']) self.assertEqual(response.data['private'], constants.DEFAULT_PRIVATE) self.assertIsNone(response.data['owner']) def test_post_owner(self): \"\"\"Snippet list POST", "\"\"\"Snippet list POST must create a new snippet.\"\"\" response =", "newly created snippet's owner. \"\"\" self.client.force_authenticate(self.user) response = self.post(content='foo') self.assertEqual(response.data['owner'],", "+ [status.HTTP_400_BAD_REQUEST] * 2) def check(i): response = self.post() self.assertEqual(response.status_code,", "view's URL with data indicated by given kwargs, as JSON,", "setting): \"\"\"Check that snippet list POST returns a 403 Forbidden", "setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS_CREATE') def test_post_anonymous_private(self): \"\"\"Snippet list POST", "viewable snippets.\"\"\" create_snippet('foo') create_snippet('bar') response = self.get() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data),", "\"\"\" create_snippet('foo') create_snippet('bar', owner=self.user) expected = [0, 1, 2] def", "to anonymous users who attempt to create a private snippet.", "anonymous users if the FORBID_ANONYMOUS setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS')", "title = 'a' * (constants.TITLE_MAX_LENGTH + 1) response = self.post(content='foo',", "private=True) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_pagination(self): \"\"\"Snippet list must be able", "'') self.assertEqual(response.data['language'], '') self.assertEqual(response.data['style'], 'friendly') self.assertEqual( response.data['line_numbers'], constants.DEFAULT_LINE_NUMBERS) self.assertFalse(response.data['embed_title']) self.assertEqual(response.data['private'],", "\"\"\" response = self.post(content='foo', private=True) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_pagination(self): \"\"\"Snippet", "the title field consists of more characters than the TITLE_MAX_LENGTH", "list POST must create a new snippet.\"\"\" response = self.post(", "return a 400 Bad Request response if a value different", "return all the viewable snippets.\"\"\" create_snippet('foo') create_snippet('bar') response = self.get()", "constants from tests.mixins import SnippetListTestCaseMixin from tests.utils import constant, create_snippet,", "def test_post_forbid_anonymous(self): \"\"\"Snippet list POST must return a 403 Forbidden", "self.assertEqual(response.data['title'], '') self.assertEqual(response.data['language'], '') self.assertEqual(response.data['style'], 'friendly') self.assertEqual( response.data['line_numbers'], constants.DEFAULT_LINE_NUMBERS) self.assertFalse(response.data['embed_title'])", "def test_post_oversized_title(self): \"\"\"Snippet list POST must return a 400 Bad", "snippets.\"\"\" create_snippet('foo') create_snippet('bar') response = self.get() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 2)", "import reverse from rest_framework import status from rest_framework.test import APITestCase", "Request response if no content field is set. \"\"\" response", "snippet.\"\"\" response = self.post( content='foo', style='friendly', embed_title=False) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['content'],", "True, unless requested by a staff user. \"\"\" create_snippet('foo') create_snippet('bar',", "response if a value different than the available choices is", "False): self.check_for_users(check) def test_post_success(self): \"\"\"Snippet list POST must create a", "authenticated user as the newly created snippet's owner. \"\"\" self.client.force_authenticate(self.user)", "\"\"\" expected = ( [status.HTTP_403_FORBIDDEN] + [status.HTTP_400_BAD_REQUEST] * 2) def", "title field consists of more characters than the TITLE_MAX_LENGTH setting", "is set for a multiple choice field. \"\"\" for field", "True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS_CREATE') def test_post_anonymous_private(self): \"\"\"Snippet list POST must return", "= self.get() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 2) self.assertEqual(response.data[0]['content'], 'foo') self.assertEqual(response.data[1]['content'], 'bar')", "a 400 Bad Request response if the title field consists", "= self.post(content='foo', title=title) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_invalid(self): \"\"\"Snippet list POST", "test_post_oversized_title(self): \"\"\"Snippet list POST must return a 400 Bad Request", "**{'content': 'foo', field: '123-invalid-abc'}) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST) def check_post_forbid_anonymous(self, setting):", "data indicated by given kwargs, as JSON, using the proper", "anonymous users if the given setting is True. \"\"\" expected", "expected[i]) self.check_for_users(check, owner) def test_get_list_foreign(self): \"\"\"Snippet list GET must not", "owner=self.user) expected = [0, 1, 2] def check(i): response =", "create_snippet('bar', owner=self.user) expected = [0, 1, 2] def check(i): response", "self.post(content='foo', private=True) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_pagination(self): \"\"\"Snippet list must be", "the FORBID_ANONYMOUS setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS') def test_post_forbid_anonymous_create(self): \"\"\"Snippet", "\"\"\" response = self.post(title='foo') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_oversized_title(self): \"\"\"Snippet list", "list GET must return all the viewable snippets.\"\"\" create_snippet('foo') create_snippet('bar')", "POST request to the view's URL with data indicated by", "def url(self): \"\"\"Return the snippet list URL.\"\"\" return reverse('snippet-list') def", "must not return snippets owned by other users if the", "by given kwargs, as JSON, using the proper content-type, and", "return the response. \"\"\" return self.client.post( self.url(), data=json.dumps(kwargs), content_type='application/json') def", "APITestCase from paste import constants from tests.mixins import SnippetListTestCaseMixin from", "\"\"\"Send a POST request to the view's URL with data", "response = self.get() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 2) self.assertEqual(response.data[0]['content'], 'foo') self.assertEqual(response.data[1]['content'],", "self.post(content='foo') self.assertEqual(response.data['owner'], self.user.pk) def test_post_no_content(self): \"\"\"Snippet list POST must return", "content_type='application/json') def test_get_success(self): \"\"\"Snippet list GET must return all the", "response = self.post(content='foo') self.assertEqual(response.data['owner'], self.user.pk) def test_post_no_content(self): \"\"\"Snippet list POST", "response. \"\"\" return self.client.post( self.url(), data=json.dumps(kwargs), content_type='application/json') def test_get_success(self): \"\"\"Snippet", "from paste import constants from tests.mixins import SnippetListTestCaseMixin from tests.utils", "'') self.assertEqual(response.data['style'], 'friendly') self.assertEqual( response.data['line_numbers'], constants.DEFAULT_LINE_NUMBERS) self.assertFalse(response.data['embed_title']) self.assertEqual(response.data['private'], constants.DEFAULT_PRIVATE) self.assertIsNone(response.data['owner'])", "self.check_for_users(check) def test_post_forbid_anonymous(self): \"\"\"Snippet list POST must return a 403", "with constant(setting): self.check_for_users(check) def test_post_forbid_anonymous(self): \"\"\"Snippet list POST must return", "'foo') self.assertEqual(response.data['title'], '') self.assertEqual(response.data['language'], '') self.assertEqual(response.data['style'], 'friendly') self.assertEqual( response.data['line_numbers'], constants.DEFAULT_LINE_NUMBERS)", "self.check_for_users(check) def test_post_success(self): \"\"\"Snippet list POST must create a new", "must return a 400 Bad Request response if no content", "return reverse('snippet-list') def post(self, **kwargs): \"\"\"Send a POST request to", "403 Forbidden response to anonymous users if the FORBID_ANONYMOUS setting", "to anonymous users if the FORBID_ANONYMOUS_CREATE setting is True. \"\"\"", "from rest_framework import status from rest_framework.test import APITestCase from paste", "True. \"\"\" expected = ( [status.HTTP_403_FORBIDDEN] + [status.HTTP_400_BAD_REQUEST] * 2)", "a POST request to the view's URL with data indicated", "self.assertEqual(response.data['owner'], self.user.pk) def test_post_no_content(self): \"\"\"Snippet list POST must return a", "self.client.force_authenticate(self.user) response = self.post(content='foo') self.assertEqual(response.data['owner'], self.user.pk) def test_post_no_content(self): \"\"\"Snippet list", "list GET must not return snippets owned by other users", "def test_post_owner(self): \"\"\"Snippet list POST must store currently authenticated user", "style='friendly', embed_title=False) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['content'], 'foo') self.assertEqual(response.data['title'], '') self.assertEqual(response.data['language'], '')", "403 Forbidden response to anonymous users if the FORBID_ANONYMOUS_CREATE setting", "['language', 'style']: response = self.post( **{'content': 'foo', field: '123-invalid-abc'}) self.assertEqual(", "response = self.post() self.assertEqual(response.status_code, expected[i]) with constant(setting): self.check_for_users(check) def test_post_forbid_anonymous(self):", "return a 400 Bad Request response if no content field", "def test_post_no_content(self): \"\"\"Snippet list POST must return a 400 Bad", "as JSON, using the proper content-type, and return the response.", "post(self, **kwargs): \"\"\"Send a POST request to the view's URL", "response to anonymous users if the FORBID_ANONYMOUS setting is True.", "test_get_list_foreign(self): \"\"\"Snippet list GET must not return snippets owned by", "a 400 Bad Request response if no content field is", "self.get() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 2) self.assertEqual(response.data[0]['content'], 'foo') self.assertEqual(response.data[1]['content'], 'bar') def", "* 2) def check(i): response = self.post() self.assertEqual(response.status_code, expected[i]) with", "constant('LIST_FOREIGN', False): self.check_for_users(check) def test_post_success(self): \"\"\"Snippet list POST must create", "self.post(title='foo') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_oversized_title(self): \"\"\"Snippet list POST must return", "to anonymous users if the FORBID_ANONYMOUS setting is True. \"\"\"", "store currently authenticated user as the newly created snippet's owner.", "\"\"\" return self.client.post( self.url(), data=json.dumps(kwargs), content_type='application/json') def test_get_success(self): \"\"\"Snippet list", "self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 2) self.assertEqual(response.data[0]['content'], 'foo') self.assertEqual(response.data[1]['content'], 'bar') def test_get_private(self):", "403 Forbidden response to anonymous users if the given setting", "400 Bad Request response if the title field consists of", "no content field is set. \"\"\" response = self.post(title='foo') self.assertEqual(response.status_code,", "snippet list POST returns a 403 Forbidden response to anonymous", "the response. \"\"\" return self.client.post( self.url(), data=json.dumps(kwargs), content_type='application/json') def test_get_success(self):", "snippet list view.\"\"\" def url(self): \"\"\"Return the snippet list URL.\"\"\"", "must create a new snippet.\"\"\" response = self.post( content='foo', style='friendly',", "constant(setting): self.check_for_users(check) def test_post_forbid_anonymous(self): \"\"\"Snippet list POST must return a", "self.check_for_users(check, owner) def test_get_list_foreign(self): \"\"\"Snippet list GET must not return", "= create_user('owner') create_snippet('foo', private=True, owner=owner) expected = [0, 0, 1,", "setting indicates. \"\"\" title = 'a' * (constants.TITLE_MAX_LENGTH + 1)", "a private snippet. \"\"\" response = self.post(content='foo', private=True) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)", "view them. \"\"\" owner = create_user('owner') create_snippet('foo', private=True, owner=owner) expected", "self.assertEqual( response.data['line_numbers'], constants.DEFAULT_LINE_NUMBERS) self.assertFalse(response.data['embed_title']) self.assertEqual(response.data['private'], constants.DEFAULT_PRIVATE) self.assertIsNone(response.data['owner']) def test_post_owner(self): \"\"\"Snippet", "\"\"\"Snippet list POST must store currently authenticated user as the", "for a multiple choice field. \"\"\" for field in ['language',", "return snippets owned by other users if the LIST_FOREIGN setting", "def test_pagination(self): \"\"\"Snippet list must be able to handle pagination.\"\"\"", "is True, unless requested by a staff user. \"\"\" create_snippet('foo')", "= self.post( **{'content': 'foo', field: '123-invalid-abc'}) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST) def", "1, 1] def check(i): response = self.get() self.assertEqual(len(response.data), expected[i]) self.check_for_users(check,", "field: '123-invalid-abc'}) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST) def check_post_forbid_anonymous(self, setting): \"\"\"Check that", "status.HTTP_400_BAD_REQUEST) def test_pagination(self): \"\"\"Snippet list must be able to handle", "a 400 Bad Request response if a value different than", "status from rest_framework.test import APITestCase from paste import constants from", "GET must return all the viewable snippets.\"\"\" create_snippet('foo') create_snippet('bar') response", "check(i): response = self.post() self.assertEqual(response.status_code, expected[i]) with constant(setting): self.check_for_users(check) def", "expected = [0, 0, 1, 1] def check(i): response =", "to those authorized to view them. \"\"\" owner = create_user('owner')", "self.check_post_forbid_anonymous('FORBID_ANONYMOUS_CREATE') def test_post_anonymous_private(self): \"\"\"Snippet list POST must return a 400", "all the viewable snippets.\"\"\" create_snippet('foo') create_snippet('bar') response = self.get() self.assertEqual(response.status_code,", "= [0, 0, 1, 1] def check(i): response = self.get()", "self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST) def check_post_forbid_anonymous(self, setting): \"\"\"Check that snippet list", "a 400 Bad Request response to anonymous users who attempt", "1] def check(i): response = self.get() self.assertEqual(len(response.data), expected[i]) self.check_for_users(check, owner)", "content field is set. \"\"\" response = self.post(title='foo') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)", "'123-invalid-abc'}) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST) def check_post_forbid_anonymous(self, setting): \"\"\"Check that snippet", "\"\"\"Snippet list GET must return private snippets only to those", "to create a private snippet. \"\"\" response = self.post(content='foo', private=True)", "than the available choices is set for a multiple choice", "self.user.pk) def test_post_no_content(self): \"\"\"Snippet list POST must return a 400", "( [status.HTTP_403_FORBIDDEN] + [status.HTTP_400_BAD_REQUEST] * 2) def check(i): response =", "URL with data indicated by given kwargs, as JSON, using", "by other users if the LIST_FOREIGN setting is True, unless", "= self.post() self.assertEqual(response.status_code, expected[i]) with constant(setting): self.check_for_users(check) def test_post_forbid_anonymous(self): \"\"\"Snippet", "= self.post(title='foo') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_oversized_title(self): \"\"\"Snippet list POST must", "django.urls import reverse from rest_framework import status from rest_framework.test import", "GET must not return snippets owned by other users if", "with constant('LIST_FOREIGN', False): self.check_for_users(check) def test_post_success(self): \"\"\"Snippet list POST must", "only to those authorized to view them. \"\"\" owner =", "= self.post(content='foo', private=True) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_pagination(self): \"\"\"Snippet list must", "setting is True, unless requested by a staff user. \"\"\"", "rest_framework import status from rest_framework.test import APITestCase from paste import", "reverse from rest_framework import status from rest_framework.test import APITestCase from", "def check(i): response = self.post() self.assertEqual(response.status_code, expected[i]) with constant(setting): self.check_for_users(check)", "self.assertFalse(response.data['embed_title']) self.assertEqual(response.data['private'], constants.DEFAULT_PRIVATE) self.assertIsNone(response.data['owner']) def test_post_owner(self): \"\"\"Snippet list POST must", "owner = create_user('owner') create_snippet('foo', private=True, owner=owner) expected = [0, 0,", "in ['language', 'style']: response = self.post( **{'content': 'foo', field: '123-invalid-abc'})", "users if the FORBID_ANONYMOUS_CREATE setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS_CREATE') def", "owner) def test_get_list_foreign(self): \"\"\"Snippet list GET must not return snippets", "users if the FORBID_ANONYMOUS setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS') def", "the TITLE_MAX_LENGTH setting indicates. \"\"\" title = 'a' * (constants.TITLE_MAX_LENGTH", "status.HTTP_400_BAD_REQUEST) def test_post_invalid(self): \"\"\"Snippet list POST must return a 400", "POST must return a 400 Bad Request response to anonymous", "Forbidden response to anonymous users if the FORBID_ANONYMOUS setting is", "the newly created snippet's owner. \"\"\" self.client.force_authenticate(self.user) response = self.post(content='foo')", "LIST_FOREIGN setting is True, unless requested by a staff user.", "the FORBID_ANONYMOUS_CREATE setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS_CREATE') def test_post_anonymous_private(self): \"\"\"Snippet", "list POST must return a 400 Bad Request response to", "self.get() self.assertEqual(len(response.data), expected[i]) with constant('LIST_FOREIGN', False): self.check_for_users(check) def test_post_success(self): \"\"\"Snippet", "return self.client.post( self.url(), data=json.dumps(kwargs), content_type='application/json') def test_get_success(self): \"\"\"Snippet list GET", "users if the given setting is True. \"\"\" expected =", "must return a 400 Bad Request response if the title", "self.assertEqual(response.data['language'], '') self.assertEqual(response.data['style'], 'friendly') self.assertEqual( response.data['line_numbers'], constants.DEFAULT_LINE_NUMBERS) self.assertFalse(response.data['embed_title']) self.assertEqual(response.data['private'], constants.DEFAULT_PRIVATE)", "0, 1, 1] def check(i): response = self.get() self.assertEqual(len(response.data), expected[i])", "tests.utils import constant, create_snippet, create_user class SnippetListTestCase(SnippetListTestCaseMixin, APITestCase): \"\"\"Tests for", "import status from rest_framework.test import APITestCase from paste import constants", "test_get_private(self): \"\"\"Snippet list GET must return private snippets only to", "def test_post_invalid(self): \"\"\"Snippet list POST must return a 400 Bad", "self.assertEqual(response.status_code, expected[i]) with constant(setting): self.check_for_users(check) def test_post_forbid_anonymous(self): \"\"\"Snippet list POST", "owned by other users if the LIST_FOREIGN setting is True,", "expected[i]) with constant(setting): self.check_for_users(check) def test_post_forbid_anonymous(self): \"\"\"Snippet list POST must", "def post(self, **kwargs): \"\"\"Send a POST request to the view's", "\"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS') def test_post_forbid_anonymous_create(self): \"\"\"Snippet list POST must return a", "'a' * (constants.TITLE_MAX_LENGTH + 1) response = self.post(content='foo', title=title) self.assertEqual(response.status_code,", "from django.urls import reverse from rest_framework import status from rest_framework.test", "test_post_anonymous_private(self): \"\"\"Snippet list POST must return a 400 Bad Request", "given kwargs, as JSON, using the proper content-type, and return", "if the given setting is True. \"\"\" expected = (", "rest_framework.test import APITestCase from paste import constants from tests.mixins import", "choice field. \"\"\" for field in ['language', 'style']: response =", "\"\"\" owner = create_user('owner') create_snippet('foo', private=True, owner=owner) expected = [0,", "view.\"\"\" def url(self): \"\"\"Return the snippet list URL.\"\"\" return reverse('snippet-list')", "self.post() self.assertEqual(response.status_code, expected[i]) with constant(setting): self.check_for_users(check) def test_post_forbid_anonymous(self): \"\"\"Snippet list", "proper content-type, and return the response. \"\"\" return self.client.post( self.url(),", "response = self.get() self.assertEqual(len(response.data), expected[i]) self.check_for_users(check, owner) def test_get_list_foreign(self): \"\"\"Snippet", "owner=owner) expected = [0, 0, 1, 1] def check(i): response", "for field in ['language', 'style']: response = self.post( **{'content': 'foo',", "FORBID_ANONYMOUS setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS') def test_post_forbid_anonymous_create(self): \"\"\"Snippet list", "list GET must return private snippets only to those authorized", "not return snippets owned by other users if the LIST_FOREIGN", "for the snippet list view.\"\"\" def url(self): \"\"\"Return the snippet", "Bad Request response if no content field is set. \"\"\"", "with data indicated by given kwargs, as JSON, using the", "test_post_invalid(self): \"\"\"Snippet list POST must return a 400 Bad Request", "content-type, and return the response. \"\"\" return self.client.post( self.url(), data=json.dumps(kwargs),", "response to anonymous users if the FORBID_ANONYMOUS_CREATE setting is True.", "that snippet list POST returns a 403 Forbidden response to", "a new snippet.\"\"\" response = self.post( content='foo', style='friendly', embed_title=False) self.assertEqual(response.status_code,", "* (constants.TITLE_MAX_LENGTH + 1) response = self.post(content='foo', title=title) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)", "'bar') def test_get_private(self): \"\"\"Snippet list GET must return private snippets", "and return the response. \"\"\" return self.client.post( self.url(), data=json.dumps(kwargs), content_type='application/json')", "a 403 Forbidden response to anonymous users if the given", "available choices is set for a multiple choice field. \"\"\"", "a staff user. \"\"\" create_snippet('foo') create_snippet('bar', owner=self.user) expected = [0,", "**kwargs): \"\"\"Send a POST request to the view's URL with", "import json from django.urls import reverse from rest_framework import status", "response = self.post( **{'content': 'foo', field: '123-invalid-abc'}) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST)", "to the view's URL with data indicated by given kwargs,", "\"\"\"Snippet list GET must return all the viewable snippets.\"\"\" create_snippet('foo')", "test_pagination(self): \"\"\"Snippet list must be able to handle pagination.\"\"\" self.check_pagination()", "list URL.\"\"\" return reverse('snippet-list') def post(self, **kwargs): \"\"\"Send a POST", "response if no content field is set. \"\"\" response =", "as the newly created snippet's owner. \"\"\" self.client.force_authenticate(self.user) response =", "list POST returns a 403 Forbidden response to anonymous users", "[status.HTTP_403_FORBIDDEN] + [status.HTTP_400_BAD_REQUEST] * 2) def check(i): response = self.post()", "self.assertEqual(len(response.data), expected[i]) self.check_for_users(check, owner) def test_get_list_foreign(self): \"\"\"Snippet list GET must", "1) response = self.post(content='foo', title=title) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_invalid(self): \"\"\"Snippet", "400 Bad Request response if no content field is set.", "staff user. \"\"\" create_snippet('foo') create_snippet('bar', owner=self.user) expected = [0, 1,", "FORBID_ANONYMOUS_CREATE setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS_CREATE') def test_post_anonymous_private(self): \"\"\"Snippet list", "APITestCase): \"\"\"Tests for the snippet list view.\"\"\" def url(self): \"\"\"Return", "snippets owned by other users if the LIST_FOREIGN setting is", "indicates. \"\"\" title = 'a' * (constants.TITLE_MAX_LENGTH + 1) response", "def check(i): response = self.get() self.assertEqual(len(response.data), expected[i]) self.check_for_users(check, owner) def", "snippet's owner. \"\"\" self.client.force_authenticate(self.user) response = self.post(content='foo') self.assertEqual(response.data['owner'], self.user.pk) def", "'style']: response = self.post( **{'content': 'foo', field: '123-invalid-abc'}) self.assertEqual( response.status_code,", "data=json.dumps(kwargs), content_type='application/json') def test_get_success(self): \"\"\"Snippet list GET must return all", "multiple choice field. \"\"\" for field in ['language', 'style']: response", "response to anonymous users if the given setting is True.", "Request response if the title field consists of more characters", "request to the view's URL with data indicated by given", "anonymous users if the FORBID_ANONYMOUS_CREATE setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS_CREATE')", "url(self): \"\"\"Return the snippet list URL.\"\"\" return reverse('snippet-list') def post(self,", "POST must return a 400 Bad Request response if a", "setting is True. \"\"\" expected = ( [status.HTTP_403_FORBIDDEN] + [status.HTTP_400_BAD_REQUEST]", "requested by a staff user. \"\"\" create_snippet('foo') create_snippet('bar', owner=self.user) expected", "\"\"\"Check that snippet list POST returns a 403 Forbidden response", "check(i): response = self.get() self.assertEqual(len(response.data), expected[i]) self.check_for_users(check, owner) def test_get_list_foreign(self):", "POST must return a 400 Bad Request response if no", "must return a 400 Bad Request response if a value", "\"\"\"Snippet list GET must not return snippets owned by other", "anonymous users who attempt to create a private snippet. \"\"\"", "= [0, 1, 2] def check(i): response = self.get() self.assertEqual(len(response.data),", "more characters than the TITLE_MAX_LENGTH setting indicates. \"\"\" title =", "Bad Request response to anonymous users who attempt to create", "is set. \"\"\" response = self.post(title='foo') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_oversized_title(self):", "create a new snippet.\"\"\" response = self.post( content='foo', style='friendly', embed_title=False)", "field in ['language', 'style']: response = self.post( **{'content': 'foo', field:", "attempt to create a private snippet. \"\"\" response = self.post(content='foo',", "return a 400 Bad Request response to anonymous users who", "snippets only to those authorized to view them. \"\"\" owner", "2) def check(i): response = self.post() self.assertEqual(response.status_code, expected[i]) with constant(setting):", "kwargs, as JSON, using the proper content-type, and return the", "setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS') def test_post_forbid_anonymous_create(self): \"\"\"Snippet list POST", "unless requested by a staff user. \"\"\" create_snippet('foo') create_snippet('bar', owner=self.user)", "test_post_owner(self): \"\"\"Snippet list POST must store currently authenticated user as", "'foo') self.assertEqual(response.data[1]['content'], 'bar') def test_get_private(self): \"\"\"Snippet list GET must return", "POST must return a 400 Bad Request response if the", "1, 2] def check(i): response = self.get() self.assertEqual(len(response.data), expected[i]) with", "authorized to view them. \"\"\" owner = create_user('owner') create_snippet('foo', private=True,", "response.data['line_numbers'], constants.DEFAULT_LINE_NUMBERS) self.assertFalse(response.data['embed_title']) self.assertEqual(response.data['private'], constants.DEFAULT_PRIVATE) self.assertIsNone(response.data['owner']) def test_post_owner(self): \"\"\"Snippet list", "Request response to anonymous users who attempt to create a", "check_post_forbid_anonymous(self, setting): \"\"\"Check that snippet list POST returns a 403", "self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_pagination(self): \"\"\"Snippet list must be able to", "is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS_CREATE') def test_post_anonymous_private(self): \"\"\"Snippet list POST must", "must store currently authenticated user as the newly created snippet's", "value different than the available choices is set for a", "than the TITLE_MAX_LENGTH setting indicates. \"\"\" title = 'a' *", "status.HTTP_200_OK) self.assertEqual(len(response.data), 2) self.assertEqual(response.data[0]['content'], 'foo') self.assertEqual(response.data[1]['content'], 'bar') def test_get_private(self): \"\"\"Snippet", "embed_title=False) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['content'], 'foo') self.assertEqual(response.data['title'], '') self.assertEqual(response.data['language'], '') self.assertEqual(response.data['style'],", "\"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS_CREATE') def test_post_anonymous_private(self): \"\"\"Snippet list POST must return a", "the snippet list URL.\"\"\" return reverse('snippet-list') def post(self, **kwargs): \"\"\"Send", "list POST must return a 403 Forbidden response to anonymous", "\"\"\"Snippet list POST must return a 403 Forbidden response to", "self.post( content='foo', style='friendly', embed_title=False) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['content'], 'foo') self.assertEqual(response.data['title'], '')", "a multiple choice field. \"\"\" for field in ['language', 'style']:", "user as the newly created snippet's owner. \"\"\" self.client.force_authenticate(self.user) response", "= self.post( content='foo', style='friendly', embed_title=False) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['content'], 'foo') self.assertEqual(response.data['title'],", "response = self.get() self.assertEqual(len(response.data), expected[i]) with constant('LIST_FOREIGN', False): self.check_for_users(check) def", "private=True, owner=owner) expected = [0, 0, 1, 1] def check(i):", "if the LIST_FOREIGN setting is True, unless requested by a", "created snippet's owner. \"\"\" self.client.force_authenticate(self.user) response = self.post(content='foo') self.assertEqual(response.data['owner'], self.user.pk)", "a value different than the available choices is set for", "list POST must return a 400 Bad Request response if", "tests.mixins import SnippetListTestCaseMixin from tests.utils import constant, create_snippet, create_user class", "by a staff user. \"\"\" create_snippet('foo') create_snippet('bar', owner=self.user) expected =", "if the title field consists of more characters than the", "self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_invalid(self): \"\"\"Snippet list POST must return a", "snippet. \"\"\" response = self.post(content='foo', private=True) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_pagination(self):", "import SnippetListTestCaseMixin from tests.utils import constant, create_snippet, create_user class SnippetListTestCase(SnippetListTestCaseMixin,", "private snippets only to those authorized to view them. \"\"\"", "\"\"\"Tests for the snippet list view.\"\"\" def url(self): \"\"\"Return the", "currently authenticated user as the newly created snippet's owner. \"\"\"", "returns a 403 Forbidden response to anonymous users if the", "field is set. \"\"\" response = self.post(title='foo') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def", "def test_get_list_foreign(self): \"\"\"Snippet list GET must not return snippets owned", "create_user('owner') create_snippet('foo', private=True, owner=owner) expected = [0, 0, 1, 1]", "Request response if a value different than the available choices", "SnippetListTestCaseMixin from tests.utils import constant, create_snippet, create_user class SnippetListTestCase(SnippetListTestCaseMixin, APITestCase):", "\"\"\" for field in ['language', 'style']: response = self.post( **{'content':", "= self.get() self.assertEqual(len(response.data), expected[i]) with constant('LIST_FOREIGN', False): self.check_for_users(check) def test_post_success(self):", "create_snippet('foo') create_snippet('bar', owner=self.user) expected = [0, 1, 2] def check(i):", "response to anonymous users who attempt to create a private", "GET must return private snippets only to those authorized to", "def test_get_private(self): \"\"\"Snippet list GET must return private snippets only", "URL.\"\"\" return reverse('snippet-list') def post(self, **kwargs): \"\"\"Send a POST request", "private snippet. \"\"\" response = self.post(content='foo', private=True) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def", "2) self.assertEqual(response.data[0]['content'], 'foo') self.assertEqual(response.data[1]['content'], 'bar') def test_get_private(self): \"\"\"Snippet list GET", "TITLE_MAX_LENGTH setting indicates. \"\"\" title = 'a' * (constants.TITLE_MAX_LENGTH +", "POST returns a 403 Forbidden response to anonymous users if", "constant, create_snippet, create_user class SnippetListTestCase(SnippetListTestCaseMixin, APITestCase): \"\"\"Tests for the snippet", "self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['content'], 'foo') self.assertEqual(response.data['title'], '') self.assertEqual(response.data['language'], '') self.assertEqual(response.data['style'], 'friendly')", "choices is set for a multiple choice field. \"\"\" for", "= 'a' * (constants.TITLE_MAX_LENGTH + 1) response = self.post(content='foo', title=title)", "400 Bad Request response to anonymous users who attempt to", "response if the title field consists of more characters than", "test_get_success(self): \"\"\"Snippet list GET must return all the viewable snippets.\"\"\"", "response.status_code, status.HTTP_400_BAD_REQUEST) def check_post_forbid_anonymous(self, setting): \"\"\"Check that snippet list POST", "json from django.urls import reverse from rest_framework import status from", "those authorized to view them. \"\"\" owner = create_user('owner') create_snippet('foo',", "if a value different than the available choices is set", "create_snippet('foo') create_snippet('bar') response = self.get() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 2) self.assertEqual(response.data[0]['content'],", "self.assertEqual(response.data['content'], 'foo') self.assertEqual(response.data['title'], '') self.assertEqual(response.data['language'], '') self.assertEqual(response.data['style'], 'friendly') self.assertEqual( response.data['line_numbers'],", "\"\"\" self.client.force_authenticate(self.user) response = self.post(content='foo') self.assertEqual(response.data['owner'], self.user.pk) def test_post_no_content(self): \"\"\"Snippet", "field consists of more characters than the TITLE_MAX_LENGTH setting indicates.", "is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS') def test_post_forbid_anonymous_create(self): \"\"\"Snippet list POST must", "given setting is True. \"\"\" expected = ( [status.HTTP_403_FORBIDDEN] +", "owner. \"\"\" self.client.force_authenticate(self.user) response = self.post(content='foo') self.assertEqual(response.data['owner'], self.user.pk) def test_post_no_content(self):", "content='foo', style='friendly', embed_title=False) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['content'], 'foo') self.assertEqual(response.data['title'], '') self.assertEqual(response.data['language'],", "self.assertEqual(response.data[0]['content'], 'foo') self.assertEqual(response.data[1]['content'], 'bar') def test_get_private(self): \"\"\"Snippet list GET must", "POST must return a 403 Forbidden response to anonymous users", "create_snippet('bar') response = self.get() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 2) self.assertEqual(response.data[0]['content'], 'foo')", "test_post_no_content(self): \"\"\"Snippet list POST must return a 400 Bad Request", "different than the available choices is set for a multiple", "2] def check(i): response = self.get() self.assertEqual(len(response.data), expected[i]) with constant('LIST_FOREIGN',", "response = self.post(content='foo', private=True) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_pagination(self): \"\"\"Snippet list", "is True. \"\"\" expected = ( [status.HTTP_403_FORBIDDEN] + [status.HTTP_400_BAD_REQUEST] *", "return a 400 Bad Request response if the title field", "characters than the TITLE_MAX_LENGTH setting indicates. \"\"\" title = 'a'", "a 403 Forbidden response to anonymous users if the FORBID_ANONYMOUS", "other users if the LIST_FOREIGN setting is True, unless requested", "paste import constants from tests.mixins import SnippetListTestCaseMixin from tests.utils import", "self.assertEqual(response.data['private'], constants.DEFAULT_PRIVATE) self.assertIsNone(response.data['owner']) def test_post_owner(self): \"\"\"Snippet list POST must store", "= ( [status.HTTP_403_FORBIDDEN] + [status.HTTP_400_BAD_REQUEST] * 2) def check(i): response", "list POST must store currently authenticated user as the newly", "from tests.utils import constant, create_snippet, create_user class SnippetListTestCase(SnippetListTestCaseMixin, APITestCase): \"\"\"Tests", "\"\"\"Return the snippet list URL.\"\"\" return reverse('snippet-list') def post(self, **kwargs):", "field. \"\"\" for field in ['language', 'style']: response = self.post(", "def test_get_success(self): \"\"\"Snippet list GET must return all the viewable", "response = self.post(title='foo') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_oversized_title(self): \"\"\"Snippet list POST", "= self.get() self.assertEqual(len(response.data), expected[i]) self.check_for_users(check, owner) def test_get_list_foreign(self): \"\"\"Snippet list", "self.get() self.assertEqual(len(response.data), expected[i]) self.check_for_users(check, owner) def test_get_list_foreign(self): \"\"\"Snippet list GET", "from rest_framework.test import APITestCase from paste import constants from tests.mixins", "POST must create a new snippet.\"\"\" response = self.post( content='foo',", "constants.DEFAULT_PRIVATE) self.assertIsNone(response.data['owner']) def test_post_owner(self): \"\"\"Snippet list POST must store currently", "of more characters than the TITLE_MAX_LENGTH setting indicates. \"\"\" title", "the snippet list view.\"\"\" def url(self): \"\"\"Return the snippet list", "JSON, using the proper content-type, and return the response. \"\"\"", "Forbidden response to anonymous users if the FORBID_ANONYMOUS_CREATE setting is", "class SnippetListTestCase(SnippetListTestCaseMixin, APITestCase): \"\"\"Tests for the snippet list view.\"\"\" def", "create_snippet('foo', private=True, owner=owner) expected = [0, 0, 1, 1] def", "self.assertEqual(len(response.data), expected[i]) with constant('LIST_FOREIGN', False): self.check_for_users(check) def test_post_success(self): \"\"\"Snippet list", "def test_post_forbid_anonymous_create(self): \"\"\"Snippet list POST must return a 403 Forbidden", "\"\"\" title = 'a' * (constants.TITLE_MAX_LENGTH + 1) response =", "them. \"\"\" owner = create_user('owner') create_snippet('foo', private=True, owner=owner) expected =", "400 Bad Request response if a value different than the", "[0, 0, 1, 1] def check(i): response = self.get() self.assertEqual(len(response.data),", "new snippet.\"\"\" response = self.post( content='foo', style='friendly', embed_title=False) self.assertEqual(response.status_code, status.HTTP_201_CREATED)", "response = self.post(content='foo', title=title) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_invalid(self): \"\"\"Snippet list", "+ 1) response = self.post(content='foo', title=title) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_post_invalid(self):", "create a private snippet. \"\"\" response = self.post(content='foo', private=True) self.assertEqual(response.status_code,", "def check_post_forbid_anonymous(self, setting): \"\"\"Check that snippet list POST returns a", "create_snippet, create_user class SnippetListTestCase(SnippetListTestCaseMixin, APITestCase): \"\"\"Tests for the snippet list", "= self.post(content='foo') self.assertEqual(response.data['owner'], self.user.pk) def test_post_no_content(self): \"\"\"Snippet list POST must", "must return private snippets only to those authorized to view", "if the FORBID_ANONYMOUS setting is True. \"\"\" self.check_post_forbid_anonymous('FORBID_ANONYMOUS') def test_post_forbid_anonymous_create(self):", "response = self.post( content='foo', style='friendly', embed_title=False) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['content'], 'foo')", "self.client.post( self.url(), data=json.dumps(kwargs), content_type='application/json') def test_get_success(self): \"\"\"Snippet list GET must", "the available choices is set for a multiple choice field.", "to view them. \"\"\" owner = create_user('owner') create_snippet('foo', private=True, owner=owner)", "snippet list URL.\"\"\" return reverse('snippet-list') def post(self, **kwargs): \"\"\"Send a", "\"\"\"Snippet list POST must return a 400 Bad Request response", "the viewable snippets.\"\"\" create_snippet('foo') create_snippet('bar') response = self.get() self.assertEqual(response.status_code, status.HTTP_200_OK)", "self.assertEqual(len(response.data), 2) self.assertEqual(response.data[0]['content'], 'foo') self.assertEqual(response.data[1]['content'], 'bar') def test_get_private(self): \"\"\"Snippet list" ]
[ "# python3 from itertools import permutations def max_dot_product_naive(first_sequence, second_sequence): assert", "** 3 assert all(0 <= f <= 10 ** 5", "for f in first_sequence) assert all(0 <= s <= 10", "prices = list(map(int, input().split())) clicks = list(map(int, input().split())) assert len(prices)", "3 assert all(0 <= f <= 10 ** 5 for", "5 for f in first_sequence) assert all(0 <= s <=", "in second_sequence) type here if __name__ == '__main__': n =", "assert all(0 <= s <= 10 ** 5 for s", "clicks = list(map(int, input().split())) assert len(prices) == len(clicks) == n", "<gh_stars>1-10 # python3 from itertools import permutations def max_dot_product_naive(first_sequence, second_sequence):", "input().split())) clicks = list(map(int, input().split())) assert len(prices) == len(clicks) ==", "s <= 10 ** 5 for s in second_sequence) max_product", "assert len(first_sequence) <= 10 ** 3 assert all(0 <= f", "<= 10 ** 3 assert all(0 <= f <= 10", "= list(map(int, input().split())) clicks = list(map(int, input().split())) assert len(prices) ==", "list(map(int, input().split())) assert len(prices) == len(clicks) == n print(max_dot_product(prices, clicks))", "s in second_sequence) type here if __name__ == '__main__': n", "all(0 <= f <= 10 ** 5 for f in", "permutation in permutations(second_sequence): dot_product = sum(first_sequence[i] * permutation[i] for i", "permutation[i] for i in range(len(first_sequence))) max_product = max(max_product, dot_product) return", "second_sequence) type here if __name__ == '__main__': n = int(input())", "range(len(first_sequence))) max_product = max(max_product, dot_product) return max_product def max_dot_product(first_sequence, second_sequence):", "dot_product) return max_product def max_dot_product(first_sequence, second_sequence): assert len(first_sequence) == len(second_sequence)", "5 for s in second_sequence) type here if __name__ ==", "10 ** 5 for s in second_sequence) type here if", "<= 10 ** 5 for s in second_sequence) max_product =", "in permutations(second_sequence): dot_product = sum(first_sequence[i] * permutation[i] for i in", "permutations def max_dot_product_naive(first_sequence, second_sequence): assert len(first_sequence) == len(second_sequence) assert len(first_sequence)", "= sum(first_sequence[i] * permutation[i] for i in range(len(first_sequence))) max_product =", "second_sequence) max_product = 0 for permutation in permutations(second_sequence): dot_product =", "** 5 for s in second_sequence) type here if __name__", "* permutation[i] for i in range(len(first_sequence))) max_product = max(max_product, dot_product)", "f in first_sequence) assert all(0 <= s <= 10 **", "for i in range(len(first_sequence))) max_product = max(max_product, dot_product) return max_product", "type here if __name__ == '__main__': n = int(input()) prices", "assert all(0 <= f <= 10 ** 5 for f", "== len(second_sequence) assert len(first_sequence) <= 10 ** 3 assert all(0", "__name__ == '__main__': n = int(input()) prices = list(map(int, input().split()))", "second_sequence): assert len(first_sequence) == len(second_sequence) assert len(first_sequence) <= 10 **", "<= f <= 10 ** 5 for f in first_sequence)", "permutations(second_sequence): dot_product = sum(first_sequence[i] * permutation[i] for i in range(len(first_sequence)))", "first_sequence) assert all(0 <= s <= 10 ** 5 for", "from itertools import permutations def max_dot_product_naive(first_sequence, second_sequence): assert len(first_sequence) ==", "sum(first_sequence[i] * permutation[i] for i in range(len(first_sequence))) max_product = max(max_product,", "max_dot_product(first_sequence, second_sequence): assert len(first_sequence) == len(second_sequence) assert len(first_sequence) <= 10", "max_product = 0 for permutation in permutations(second_sequence): dot_product = sum(first_sequence[i]", "i in range(len(first_sequence))) max_product = max(max_product, dot_product) return max_product def", "for s in second_sequence) max_product = 0 for permutation in", "list(map(int, input().split())) clicks = list(map(int, input().split())) assert len(prices) == len(clicks)", "len(second_sequence) assert len(first_sequence) <= 10 ** 3 assert all(0 <=", "<= s <= 10 ** 5 for s in second_sequence)", "assert len(first_sequence) == len(second_sequence) assert len(first_sequence) <= 10 ** 3", "== '__main__': n = int(input()) prices = list(map(int, input().split())) clicks", "n = int(input()) prices = list(map(int, input().split())) clicks = list(map(int,", "'__main__': n = int(input()) prices = list(map(int, input().split())) clicks =", "s in second_sequence) max_product = 0 for permutation in permutations(second_sequence):", "= max(max_product, dot_product) return max_product def max_dot_product(first_sequence, second_sequence): assert len(first_sequence)", "all(0 <= s <= 10 ** 5 for s in", "= 0 for permutation in permutations(second_sequence): dot_product = sum(first_sequence[i] *", "if __name__ == '__main__': n = int(input()) prices = list(map(int,", "<= 10 ** 5 for f in first_sequence) assert all(0", "int(input()) prices = list(map(int, input().split())) clicks = list(map(int, input().split())) assert", "in second_sequence) max_product = 0 for permutation in permutations(second_sequence): dot_product", "max_dot_product_naive(first_sequence, second_sequence): assert len(first_sequence) == len(second_sequence) assert len(first_sequence) <= 10", "for permutation in permutations(second_sequence): dot_product = sum(first_sequence[i] * permutation[i] for", "** 5 for f in first_sequence) assert all(0 <= s", "len(first_sequence) <= 10 ** 3 assert all(0 <= f <=", "return max_product def max_dot_product(first_sequence, second_sequence): assert len(first_sequence) == len(second_sequence) assert", "10 ** 3 assert all(0 <= f <= 10 **", "in range(len(first_sequence))) max_product = max(max_product, dot_product) return max_product def max_dot_product(first_sequence,", "= list(map(int, input().split())) assert len(prices) == len(clicks) == n print(max_dot_product(prices,", "= int(input()) prices = list(map(int, input().split())) clicks = list(map(int, input().split()))", "s <= 10 ** 5 for s in second_sequence) type", "max_product def max_dot_product(first_sequence, second_sequence): assert len(first_sequence) == len(second_sequence) assert len(first_sequence)", "in first_sequence) assert all(0 <= s <= 10 ** 5", "dot_product = sum(first_sequence[i] * permutation[i] for i in range(len(first_sequence))) max_product", "** 5 for s in second_sequence) max_product = 0 for", "f <= 10 ** 5 for f in first_sequence) assert", "import permutations def max_dot_product_naive(first_sequence, second_sequence): assert len(first_sequence) == len(second_sequence) assert", "<= 10 ** 5 for s in second_sequence) type here", "10 ** 5 for f in first_sequence) assert all(0 <=", "5 for s in second_sequence) max_product = 0 for permutation", "itertools import permutations def max_dot_product_naive(first_sequence, second_sequence): assert len(first_sequence) == len(second_sequence)", "10 ** 5 for s in second_sequence) max_product = 0", "for s in second_sequence) type here if __name__ == '__main__':", "max(max_product, dot_product) return max_product def max_dot_product(first_sequence, second_sequence): assert len(first_sequence) ==", "here if __name__ == '__main__': n = int(input()) prices =", "max_product = max(max_product, dot_product) return max_product def max_dot_product(first_sequence, second_sequence): assert", "0 for permutation in permutations(second_sequence): dot_product = sum(first_sequence[i] * permutation[i]", "def max_dot_product(first_sequence, second_sequence): assert len(first_sequence) == len(second_sequence) assert len(first_sequence) <=", "len(first_sequence) == len(second_sequence) assert len(first_sequence) <= 10 ** 3 assert", "python3 from itertools import permutations def max_dot_product_naive(first_sequence, second_sequence): assert len(first_sequence)", "def max_dot_product_naive(first_sequence, second_sequence): assert len(first_sequence) == len(second_sequence) assert len(first_sequence) <=" ]
[ "if hasGoodCredit: deposit = price/10 else: deposit = price/5 print(f\"Deposit", "True price = 1000000 deposit = 0 if hasGoodCredit: deposit", "= True price = 1000000 deposit = 0 if hasGoodCredit:", "0 if hasGoodCredit: deposit = price/10 else: deposit = price/5", "= 0 if hasGoodCredit: deposit = price/10 else: deposit =", "hasGoodCredit: deposit = price/10 else: deposit = price/5 print(f\"Deposit needed:", "= 1000000 deposit = 0 if hasGoodCredit: deposit = price/10", "deposit = price/10 else: deposit = price/5 print(f\"Deposit needed: £{deposit}\")", "price = 1000000 deposit = 0 if hasGoodCredit: deposit =", "1000000 deposit = 0 if hasGoodCredit: deposit = price/10 else:", "deposit = 0 if hasGoodCredit: deposit = price/10 else: deposit", "hasGoodCredit = True price = 1000000 deposit = 0 if", "<gh_stars>0 hasGoodCredit = True price = 1000000 deposit = 0" ]
[ "as props import sys import getopt from GitHubDataFetcher import GitHubDataFetcher", "\\ The output file') def main(argv): global OWNER, REPOSITORY, OUTPUTFILE", "create the fetcher data = GitHubDataFetcher(OWNER, REPOSITORY, TOKEN) # get", "remainder = getopt.getopt( argv, \"hr:o:f:\", [\"repo=\", \"owner=\", \"outputfile=\"]) except getopt.GetoptError:", "response is type ErrorFile or DependencyFile if(isinstance(res, DependencyFile)): if(OUTPUTFILE): output", "res.toJson(output) else: print(\"--repo and --owner arguments are mandatory\") if __name__", "DependencyFile import DependencyFile from ErrorFile import ErrorFile # Github Token", "\"\" REPOSITORY = \"\" OUTPUTFILE = \"\" def showHelp(): print('-r", "= OWNER+REPOSITORY+\"dependecies.json\" elif(isinstance(res, ErrorFile)): output = \"error.json\" # write file", "<reponame>vsundesha/documentation-hub-dependencies<gh_stars>0 import config as props import sys import getopt from", "owner are specified if(OWNER and REPOSITORY): # create the fetcher", "opts, remainder = getopt.getopt( argv, \"hr:o:f:\", [\"repo=\", \"owner=\", \"outputfile=\"]) except", "opts are the arguments and remainders are the arrguments that", "opt == '-h': showHelp() sys.exit() elif opt in (\"-r\", \"--repo\"):", "remainders are the arrguments that will not be complete if", "are the arrguments that will not be complete if something", "\"--outputfile\"): OUTPUTFILE = arg # check if repo and owner", "the response object res = data.getInfo() # response is type", "arg elif opt in (\"-o\", \"--owner\"): OWNER = arg elif", "# check if repo and owner are specified if(OWNER and", "\"\" def showHelp(): print('-r or --repo The name of the", "= getopt.getopt( argv, \"hr:o:f:\", [\"repo=\", \"owner=\", \"outputfile=\"]) except getopt.GetoptError: showHelp()", "elif opt in (\"-f\", \"--outputfile\"): OUTPUTFILE = arg # check", "elif opt in (\"-r\", \"--repo\"): REPOSITORY = arg elif opt", "opt, arg in opts: if opt == '-h': showHelp() sys.exit()", "REPOSITORY = arg elif opt in (\"-o\", \"--owner\"): OWNER =", "elif opt in (\"-o\", \"--owner\"): OWNER = arg elif opt", ": <OWNER+REPONAME>dependecies.json) \\ The output file') def main(argv): global OWNER,", "showHelp(): print('-r or --repo The name of the github repository')", "and remainders are the arrguments that will not be complete", "OWNER = \"\" REPOSITORY = \"\" OUTPUTFILE = \"\" def", "are the arguments and remainders are the arrguments that will", "props import sys import getopt from GitHubDataFetcher import GitHubDataFetcher from", "OWNER = arg elif opt in (\"-f\", \"--outputfile\"): OUTPUTFILE =", "are specified if(OWNER and REPOSITORY): # create the fetcher data", "The name of the github repository') print('-o or --owner The", "output file') def main(argv): global OWNER, REPOSITORY, OUTPUTFILE try: #", "sys.exit(2) for opt, arg in opts: if opt == '-h':", "response object res = data.getInfo() # response is type ErrorFile", "or DependencyFile if(isinstance(res, DependencyFile)): if(OUTPUTFILE): output = OUTPUTFILE+\"dependecies.json\" else: output", "GitHubDataFetcher from DependencyFile import DependencyFile from ErrorFile import ErrorFile #", "repository') print('-o or --owner The owner of the github repository')", "name of the github repository') print('-o or --owner The owner", "= arg # check if repo and owner are specified", "check if repo and owner are specified if(OWNER and REPOSITORY):", "in opts: if opt == '-h': showHelp() sys.exit() elif opt", "--repo The name of the github repository') print('-o or --owner", "opt in (\"-f\", \"--outputfile\"): OUTPUTFILE = arg # check if", "data.getInfo() # response is type ErrorFile or DependencyFile if(isinstance(res, DependencyFile)):", "or --repo The name of the github repository') print('-o or", "try: # opts are the arguments and remainders are the", "(\"-f\", \"--outputfile\"): OUTPUTFILE = arg # check if repo and", "OUTPUTFILE+\"dependecies.json\" else: output = OWNER+REPOSITORY+\"dependecies.json\" elif(isinstance(res, ErrorFile)): output = \"error.json\"", "\"error.json\" # write file res.toJson(output) else: print(\"--repo and --owner arguments", "import ErrorFile # Github Token TOKEN = props.token OWNER =", "argv, \"hr:o:f:\", [\"repo=\", \"owner=\", \"outputfile=\"]) except getopt.GetoptError: showHelp() sys.exit(2) for", "output = OUTPUTFILE+\"dependecies.json\" else: output = OWNER+REPOSITORY+\"dependecies.json\" elif(isinstance(res, ErrorFile)): output", "import sys import getopt from GitHubDataFetcher import GitHubDataFetcher from DependencyFile", "data = GitHubDataFetcher(OWNER, REPOSITORY, TOKEN) # get the response object", "and owner are specified if(OWNER and REPOSITORY): # create the", "the fetcher data = GitHubDataFetcher(OWNER, REPOSITORY, TOKEN) # get the", "print(\"--repo and --owner arguments are mandatory\") if __name__ == \"__main__\":", "the arrguments that will not be complete if something goes", "get the response object res = data.getInfo() # response is", "opt in (\"-o\", \"--owner\"): OWNER = arg elif opt in", "of the github repository') print('-f or --outputfile (Optional) (Default :", "import GitHubDataFetcher from DependencyFile import DependencyFile from ErrorFile import ErrorFile", "except getopt.GetoptError: showHelp() sys.exit(2) for opt, arg in opts: if", "type ErrorFile or DependencyFile if(isinstance(res, DependencyFile)): if(OUTPUTFILE): output = OUTPUTFILE+\"dependecies.json\"", "(\"-r\", \"--repo\"): REPOSITORY = arg elif opt in (\"-o\", \"--owner\"):", "write file res.toJson(output) else: print(\"--repo and --owner arguments are mandatory\")", "ErrorFile)): output = \"error.json\" # write file res.toJson(output) else: print(\"--repo", "# Github Token TOKEN = props.token OWNER = \"\" REPOSITORY", "ErrorFile # Github Token TOKEN = props.token OWNER = \"\"", "props.token OWNER = \"\" REPOSITORY = \"\" OUTPUTFILE = \"\"", "REPOSITORY, TOKEN) # get the response object res = data.getInfo()", "import getopt from GitHubDataFetcher import GitHubDataFetcher from DependencyFile import DependencyFile", "and REPOSITORY): # create the fetcher data = GitHubDataFetcher(OWNER, REPOSITORY,", "# get the response object res = data.getInfo() # response", "\"hr:o:f:\", [\"repo=\", \"owner=\", \"outputfile=\"]) except getopt.GetoptError: showHelp() sys.exit(2) for opt,", "\"outputfile=\"]) except getopt.GetoptError: showHelp() sys.exit(2) for opt, arg in opts:", "OUTPUTFILE try: # opts are the arguments and remainders are", "opt in (\"-r\", \"--repo\"): REPOSITORY = arg elif opt in", "\"owner=\", \"outputfile=\"]) except getopt.GetoptError: showHelp() sys.exit(2) for opt, arg in", "not be complete if something goes wrong opts, remainder =", "print('-r or --repo The name of the github repository') print('-o", "fetcher data = GitHubDataFetcher(OWNER, REPOSITORY, TOKEN) # get the response", "= arg elif opt in (\"-o\", \"--owner\"): OWNER = arg", "main(argv): global OWNER, REPOSITORY, OUTPUTFILE try: # opts are the", "sys.exit() elif opt in (\"-r\", \"--repo\"): REPOSITORY = arg elif", "TOKEN = props.token OWNER = \"\" REPOSITORY = \"\" OUTPUTFILE", "will not be complete if something goes wrong opts, remainder", "getopt.GetoptError: showHelp() sys.exit(2) for opt, arg in opts: if opt", "showHelp() sys.exit() elif opt in (\"-r\", \"--repo\"): REPOSITORY = arg", "OWNER+REPOSITORY+\"dependecies.json\" elif(isinstance(res, ErrorFile)): output = \"error.json\" # write file res.toJson(output)", "github repository') print('-o or --owner The owner of the github", "= \"\" def showHelp(): print('-r or --repo The name of", "the github repository') print('-f or --outputfile (Optional) (Default : <OWNER+REPONAME>dependecies.json)", "\"\" OUTPUTFILE = \"\" def showHelp(): print('-r or --repo The", "\"--owner\"): OWNER = arg elif opt in (\"-f\", \"--outputfile\"): OUTPUTFILE", "arg # check if repo and owner are specified if(OWNER", "Github Token TOKEN = props.token OWNER = \"\" REPOSITORY =", "# response is type ErrorFile or DependencyFile if(isinstance(res, DependencyFile)): if(OUTPUTFILE):", "ErrorFile or DependencyFile if(isinstance(res, DependencyFile)): if(OUTPUTFILE): output = OUTPUTFILE+\"dependecies.json\" else:", "import DependencyFile from ErrorFile import ErrorFile # Github Token TOKEN", "if something goes wrong opts, remainder = getopt.getopt( argv, \"hr:o:f:\",", "if(OWNER and REPOSITORY): # create the fetcher data = GitHubDataFetcher(OWNER,", "file') def main(argv): global OWNER, REPOSITORY, OUTPUTFILE try: # opts", "# opts are the arguments and remainders are the arrguments", "arg elif opt in (\"-f\", \"--outputfile\"): OUTPUTFILE = arg #", "DependencyFile)): if(OUTPUTFILE): output = OUTPUTFILE+\"dependecies.json\" else: output = OWNER+REPOSITORY+\"dependecies.json\" elif(isinstance(res,", "= \"\" REPOSITORY = \"\" OUTPUTFILE = \"\" def showHelp():", "getopt.getopt( argv, \"hr:o:f:\", [\"repo=\", \"owner=\", \"outputfile=\"]) except getopt.GetoptError: showHelp() sys.exit(2)", "else: print(\"--repo and --owner arguments are mandatory\") if __name__ ==", "from DependencyFile import DependencyFile from ErrorFile import ErrorFile # Github", "TOKEN) # get the response object res = data.getInfo() #", "be complete if something goes wrong opts, remainder = getopt.getopt(", "Token TOKEN = props.token OWNER = \"\" REPOSITORY = \"\"", "sys import getopt from GitHubDataFetcher import GitHubDataFetcher from DependencyFile import", "The output file') def main(argv): global OWNER, REPOSITORY, OUTPUTFILE try:", "the arguments and remainders are the arrguments that will not", "that will not be complete if something goes wrong opts,", "= OUTPUTFILE+\"dependecies.json\" else: output = OWNER+REPOSITORY+\"dependecies.json\" elif(isinstance(res, ErrorFile)): output =", "= props.token OWNER = \"\" REPOSITORY = \"\" OUTPUTFILE =", "DependencyFile from ErrorFile import ErrorFile # Github Token TOKEN =", "GitHubDataFetcher(OWNER, REPOSITORY, TOKEN) # get the response object res =", "for opt, arg in opts: if opt == '-h': showHelp()", "is type ErrorFile or DependencyFile if(isinstance(res, DependencyFile)): if(OUTPUTFILE): output =", "getopt from GitHubDataFetcher import GitHubDataFetcher from DependencyFile import DependencyFile from", "REPOSITORY = \"\" OUTPUTFILE = \"\" def showHelp(): print('-r or", "wrong opts, remainder = getopt.getopt( argv, \"hr:o:f:\", [\"repo=\", \"owner=\", \"outputfile=\"])", "== '-h': showHelp() sys.exit() elif opt in (\"-r\", \"--repo\"): REPOSITORY", "= arg elif opt in (\"-f\", \"--outputfile\"): OUTPUTFILE = arg", "(Optional) (Default : <OWNER+REPONAME>dependecies.json) \\ The output file') def main(argv):", "elif(isinstance(res, ErrorFile)): output = \"error.json\" # write file res.toJson(output) else:", "of the github repository') print('-o or --owner The owner of", "def main(argv): global OWNER, REPOSITORY, OUTPUTFILE try: # opts are", "from ErrorFile import ErrorFile # Github Token TOKEN = props.token", "or --outputfile (Optional) (Default : <OWNER+REPONAME>dependecies.json) \\ The output file')", "if(OUTPUTFILE): output = OUTPUTFILE+\"dependecies.json\" else: output = OWNER+REPOSITORY+\"dependecies.json\" elif(isinstance(res, ErrorFile)):", "arguments and remainders are the arrguments that will not be", "complete if something goes wrong opts, remainder = getopt.getopt( argv,", "\"--repo\"): REPOSITORY = arg elif opt in (\"-o\", \"--owner\"): OWNER", "[\"repo=\", \"owner=\", \"outputfile=\"]) except getopt.GetoptError: showHelp() sys.exit(2) for opt, arg", "(Default : <OWNER+REPONAME>dependecies.json) \\ The output file') def main(argv): global", "def showHelp(): print('-r or --repo The name of the github", "REPOSITORY): # create the fetcher data = GitHubDataFetcher(OWNER, REPOSITORY, TOKEN)", "object res = data.getInfo() # response is type ErrorFile or", "'-h': showHelp() sys.exit() elif opt in (\"-r\", \"--repo\"): REPOSITORY =", "specified if(OWNER and REPOSITORY): # create the fetcher data =", "(\"-o\", \"--owner\"): OWNER = arg elif opt in (\"-f\", \"--outputfile\"):", "res = data.getInfo() # response is type ErrorFile or DependencyFile", "global OWNER, REPOSITORY, OUTPUTFILE try: # opts are the arguments", "print('-f or --outputfile (Optional) (Default : <OWNER+REPONAME>dependecies.json) \\ The output", "DependencyFile if(isinstance(res, DependencyFile)): if(OUTPUTFILE): output = OUTPUTFILE+\"dependecies.json\" else: output =", "repo and owner are specified if(OWNER and REPOSITORY): # create", "config as props import sys import getopt from GitHubDataFetcher import", "else: output = OWNER+REPOSITORY+\"dependecies.json\" elif(isinstance(res, ErrorFile)): output = \"error.json\" #", "GitHubDataFetcher import GitHubDataFetcher from DependencyFile import DependencyFile from ErrorFile import", "OUTPUTFILE = \"\" def showHelp(): print('-r or --repo The name", "file res.toJson(output) else: print(\"--repo and --owner arguments are mandatory\") if", "--outputfile (Optional) (Default : <OWNER+REPONAME>dependecies.json) \\ The output file') def", "the github repository') print('-o or --owner The owner of the", "goes wrong opts, remainder = getopt.getopt( argv, \"hr:o:f:\", [\"repo=\", \"owner=\",", "if(isinstance(res, DependencyFile)): if(OUTPUTFILE): output = OUTPUTFILE+\"dependecies.json\" else: output = OWNER+REPOSITORY+\"dependecies.json\"", "in (\"-f\", \"--outputfile\"): OUTPUTFILE = arg # check if repo", "import config as props import sys import getopt from GitHubDataFetcher", "opts: if opt == '-h': showHelp() sys.exit() elif opt in", "# create the fetcher data = GitHubDataFetcher(OWNER, REPOSITORY, TOKEN) #", "repository') print('-f or --outputfile (Optional) (Default : <OWNER+REPONAME>dependecies.json) \\ The", "if repo and owner are specified if(OWNER and REPOSITORY): #", "arrguments that will not be complete if something goes wrong", "<OWNER+REPONAME>dependecies.json) \\ The output file') def main(argv): global OWNER, REPOSITORY,", "in (\"-r\", \"--repo\"): REPOSITORY = arg elif opt in (\"-o\",", "from GitHubDataFetcher import GitHubDataFetcher from DependencyFile import DependencyFile from ErrorFile", "= \"error.json\" # write file res.toJson(output) else: print(\"--repo and --owner", "= GitHubDataFetcher(OWNER, REPOSITORY, TOKEN) # get the response object res", "REPOSITORY, OUTPUTFILE try: # opts are the arguments and remainders", "= \"\" OUTPUTFILE = \"\" def showHelp(): print('-r or --repo", "in (\"-o\", \"--owner\"): OWNER = arg elif opt in (\"-f\",", "The owner of the github repository') print('-f or --outputfile (Optional)", "output = OWNER+REPOSITORY+\"dependecies.json\" elif(isinstance(res, ErrorFile)): output = \"error.json\" # write", "output = \"error.json\" # write file res.toJson(output) else: print(\"--repo and", "# write file res.toJson(output) else: print(\"--repo and --owner arguments are", "showHelp() sys.exit(2) for opt, arg in opts: if opt ==", "OUTPUTFILE = arg # check if repo and owner are", "owner of the github repository') print('-f or --outputfile (Optional) (Default", "arg in opts: if opt == '-h': showHelp() sys.exit() elif", "= data.getInfo() # response is type ErrorFile or DependencyFile if(isinstance(res,", "github repository') print('-f or --outputfile (Optional) (Default : <OWNER+REPONAME>dependecies.json) \\", "and --owner arguments are mandatory\") if __name__ == \"__main__\": main(sys.argv[1:])", "OWNER, REPOSITORY, OUTPUTFILE try: # opts are the arguments and", "print('-o or --owner The owner of the github repository') print('-f", "something goes wrong opts, remainder = getopt.getopt( argv, \"hr:o:f:\", [\"repo=\",", "or --owner The owner of the github repository') print('-f or", "ErrorFile import ErrorFile # Github Token TOKEN = props.token OWNER", "if opt == '-h': showHelp() sys.exit() elif opt in (\"-r\",", "--owner The owner of the github repository') print('-f or --outputfile" ]
[ "default=4, help='The final upsampling scale of the image') parser.add_argument('--suffix', type=str,", "_ = upsampler.enhance(img, outscale=args.outscale) except RuntimeError as error: print('Error', error)", "4: img_mode = 'RGBA' else: img_mode = None if args.ext", "final upsampling scale of the image') parser.add_argument('--suffix', type=str, default='Realesrgan-4x', help='Suffix", "the image') parser.add_argument('--suffix', type=str, default='Realesrgan-4x', help='Suffix of the restored image')", "for no tile during testing') parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding')", "channels. Options: realesrgan | bicubic') parser.add_argument( '--ext', type=str, default='auto', help='Image", "extension = args.ext if img_mode == 'RGBA': # RGBA images", "argparse import cv2 import glob import os from basicsr.archs.rrdbnet_arch import", "model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu') netscale =", "upsampler = RealESRGANer( scale=netscale, model_path=model_path, model=model, tile=args.tile, tile_pad=args.tile_pad, pre_pad=args.pre_pad, half=args.half)", "model_path = os.path.join('realesrgan/weights', args.model_name + '.pth') if not os.path.isfile(model_path): raise", "x4 VGG-style model (XS size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64,", "not os.path.isfile(model_path): model_path = os.path.join('realesrgan/weights', args.model_name + '.pth') if not", "else: paths = sorted(glob.glob(os.path.join(args.input, '*'))) for idx, path in enumerate(paths):", "'--tile', type=int, default=0, help='Tile size, 0 for no tile during", "def main(): \"\"\"Inference demo for Real-ESRGAN. \"\"\" parser = argparse.ArgumentParser()", "border') parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to enhance face') parser.add_argument('--half', action='store_true',", "num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu') netscale = 4 else: model", "'--alpha_upsampler', type=str, default='realesrgan', help='The upsampler for the alpha channels. Options:", "format extension = 'png' save_path = os.path.join(args.output, f'{imgname}-{args.suffix}.{extension}') if os.path.exists(save_path):", "netscale = 4 else: model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6,", "does not exist.') # restorer upsampler = RealESRGANer( scale=netscale, model_path=model_path,", "0 for no tile during testing') parser.add_argument('--tile_pad', type=int, default=10, help='Tile", "elif args.model_name in [ 'RealESRGANv2-anime-xsx4', 'RealESRGANv2-animevideo-xsx4-nousm', 'RealESRGANv2-animevideo-xsx4' ]: # x4", "type=str, default='RealESRGAN_x4plus', help=('Model names: RealESRGAN_x4plus | RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B |", "# x4 RRDBNet model with 6 blocks model = RRDBNet(num_in_ch=3,", "f'{imgname}-{args.suffix}.{extension}') if os.path.exists(save_path): continue try: if args.face_enhance: _, _, output", "image or folder') parser.add_argument( '-n', '--model_name', type=str, default='RealESRGAN_x4plus', help=('Model names:", "model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) netscale =", "else: extension = args.ext if img_mode == 'RGBA': # RGBA", "determine model paths model_path = os.path.join('experiments/pretrained_models', args.model_name + '.pth') if", "each border') parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to enhance face') parser.add_argument('--half',", "os.path.exists(save_path): continue try: if args.face_enhance: _, _, output = face_enhancer.enhance(img,", "type=int, default=0, help='Tile size, 0 for no tile during testing')", "upsampling scale of the image') parser.add_argument('--suffix', type=str, default='Realesrgan-4x', help='Suffix of", "RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) netscale = 4 #", "except RuntimeError as error: print('Error', error) print('If you encounter CUDA", "to set --tile with a smaller number.') else: cv2.imwrite(save_path, output)", "default=10, help='Tile padding') parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding size at", "--tile with a smaller number.') else: cv2.imwrite(save_path, output) print(f'NO.{idx}, {imgname}", "type=str, default='auto', help='Image extension. Options: auto | jpg | png,", "for Real-ESRGAN. \"\"\" parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, default='inputs',", "inference') parser.add_argument( '--alpha_upsampler', type=str, default='realesrgan', help='The upsampler for the alpha", "]: # x4 VGG-style model (XS size) model = SRVGGNetCompact(num_in_ch=3,", "netscale = 2 elif args.model_name in [ 'RealESRGANv2-anime-xsx4', 'RealESRGANv2-animevideo-xsx4-nousm', 'RealESRGANv2-animevideo-xsx4'", "try: if args.face_enhance: _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False,", "parser.add_argument( '--alpha_upsampler', type=str, default='realesrgan', help='The upsampler for the alpha channels.", "= 'RGBA' else: img_mode = None if args.ext == 'auto':", "= \"png\" else: extension = args.ext if img_mode == 'RGBA':", "tile_pad=args.tile_pad, pre_pad=args.pre_pad, half=args.half) if args.face_enhance: # Use GFPGAN for face", "== 4: img_mode = 'RGBA' else: img_mode = None if", "the alpha channels. Options: realesrgan | bicubic') parser.add_argument( '--ext', type=str,", "of the restored image') parser.add_argument('-t', '--tile', type=int, default=0, help='Tile size,", "| png, auto means using the same extension as inputs')", "'RealESRGANv2-animevideo-xsx2' ]: # x2 VGG-style model (XS size) model =", "extension = os.path.splitext(os.path.basename(path)) img = cv2.imread(path, cv2.IMREAD_UNCHANGED) if len(img.shape) ==", "face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True) else: output, _ = upsampler.enhance(img, outscale=args.outscale)", "outscale=args.outscale) except RuntimeError as error: print('Error', error) print('If you encounter", "if os.path.isfile(args.input): paths = [args.input] else: paths = sorted(glob.glob(os.path.join(args.input, '*')))", "'RealESRGANv2-animevideo-xsx2-nousm', 'RealESRGANv2-animevideo-xsx2' ]: # x2 VGG-style model (XS size) model", "'png' save_path = os.path.join(args.output, f'{imgname}-{args.suffix}.{extension}') if os.path.exists(save_path): continue try: if", "save_path = os.path.join(args.output, f'{imgname}-{args.suffix}.{extension}') if os.path.exists(save_path): continue try: if args.face_enhance:", "help='The final upsampling scale of the image') parser.add_argument('--suffix', type=str, default='Realesrgan-4x',", "model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2) netscale =", "help='The upsampler for the alpha channels. Options: realesrgan | bicubic')", "num_block=6, num_grow_ch=32, scale=4) netscale = 4 elif args.model_name in ['RealESRGAN_x2plus']:", "= args.model_name.split('.')[0] if args.model_name in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']: # x4 RRDBNet", "for face enhancement from gfpgan import GFPGANer face_enhancer = GFPGANer(", "= time.perf_counter() imgname, extension = os.path.splitext(os.path.basename(path)) img = cv2.imread(path, cv2.IMREAD_UNCHANGED)", "SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=2, act_type='prelu') netscale = 2 elif", "model_path=model_path, model=model, tile=args.tile, tile_pad=args.tile_pad, pre_pad=args.pre_pad, half=args.half) if args.face_enhance: # Use", "default='realesrgan', help='The upsampler for the alpha channels. Options: realesrgan |", "| jpg | png, auto means using the same extension", "model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth', upscale=args.outscale, arch='clean', channel_multiplier=2, bg_upsampler=upsampler) os.makedirs(args.output, exist_ok=True) if os.path.isfile(args.input): paths", "['RealESRGAN_x4plus_anime_6B']: # x4 RRDBNet model with 6 blocks model =", "]: # x2 VGG-style model (XS size) model = SRVGGNetCompact(num_in_ch=3,", "model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=2, act_type='prelu') netscale =", "| RealESRGANv2-animevideo-xsx4')) parser.add_argument('-o', '--output', type=str, default='results', help='Output folder') parser.add_argument('-s', '--outscale',", "in ['RealESRGAN_x4plus_anime_6B']: # x4 RRDBNet model with 6 blocks model", "help='Image extension. Options: auto | jpg | png, auto means", "help='Pre padding size at each border') parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN", "not exist.') # restorer upsampler = RealESRGANer( scale=netscale, model_path=model_path, model=model,", "folder') parser.add_argument('-s', '--outscale', type=float, default=4, help='The final upsampling scale of", "argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, default='inputs', help='Input image or folder') parser.add_argument(", "scale=4) netscale = 4 elif args.model_name in ['RealESRGAN_x4plus_anime_6B']: # x4", "tile during testing') parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding') parser.add_argument('--pre_pad', type=int,", "in enumerate(paths): startTime = time.perf_counter() imgname, extension = os.path.splitext(os.path.basename(path)) img", "memory, try to set --tile with a smaller number.') else:", "for idx, path in enumerate(paths): startTime = time.perf_counter() imgname, extension", "import argparse import cv2 import glob import os from basicsr.archs.rrdbnet_arch", "SRVGGNetCompact def main(): \"\"\"Inference demo for Real-ESRGAN. \"\"\" parser =", "type=str, default='realesrgan', help='The upsampler for the alpha channels. Options: realesrgan", "scale=4) netscale = 4 elif args.model_name in ['RealESRGAN_x2plus']: # x2", "'RealESRGANv2-anime-xsx2', 'RealESRGANv2-animevideo-xsx2-nousm', 'RealESRGANv2-animevideo-xsx2' ]: # x2 VGG-style model (XS size)", "RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) netscale = 4 elif", "parser.add_argument('--suffix', type=str, default='Realesrgan-4x', help='Suffix of the restored image') parser.add_argument('-t', '--tile',", "3 and img.shape[2] == 4: img_mode = 'RGBA' else: img_mode", "paste_back=True) else: output, _ = upsampler.enhance(img, outscale=args.outscale) except RuntimeError as", "png, auto means using the same extension as inputs') args", "not os.path.isfile(model_path): raise ValueError(f'Model {args.model_name} does not exist.') # restorer", "= face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True) else: output, _ = upsampler.enhance(img,", "try to set --tile with a smaller number.') else: cv2.imwrite(save_path,", "or folder') parser.add_argument( '-n', '--model_name', type=str, default='RealESRGAN_x4plus', help=('Model names: RealESRGAN_x4plus", "VGG-style model (XS size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16,", "num_feat=64, num_block=6, num_grow_ch=32, scale=4) netscale = 4 elif args.model_name in", "in [ 'RealESRGANv2-anime-xsx2', 'RealESRGANv2-animevideo-xsx2-nousm', 'RealESRGANv2-animevideo-xsx2' ]: # x2 VGG-style model", "img.shape[2] == 4: img_mode = 'RGBA' else: img_mode = None", "num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2) netscale = 2 elif args.model_name", "'RealESRGANv2-animevideo-xsx4' ]: # x4 VGG-style model (XS size) model =", "RuntimeError as error: print('Error', error) print('If you encounter CUDA out", "bg_upsampler=upsampler) os.makedirs(args.output, exist_ok=True) if os.path.isfile(args.input): paths = [args.input] else: paths", "_, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True) else: output, _", "num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) netscale = 4 # determine", "= sorted(glob.glob(os.path.join(args.input, '*'))) for idx, path in enumerate(paths): startTime =", "if not os.path.isfile(model_path): model_path = os.path.join('realesrgan/weights', args.model_name + '.pth') if", "exist_ok=True) if os.path.isfile(args.input): paths = [args.input] else: paths = sorted(glob.glob(os.path.join(args.input,", "pre_pad=args.pre_pad, half=args.half) if args.face_enhance: # Use GFPGAN for face enhancement", "glob import os from basicsr.archs.rrdbnet_arch import RRDBNet import time from", "num_out_ch=3, num_feat=64, num_conv=16, upscale=2, act_type='prelu') netscale = 2 elif args.model_name", "img_mode = None if args.ext == 'auto': extension = \"png\"", "4 # determine model paths model_path = os.path.join('experiments/pretrained_models', args.model_name +", "bicubic') parser.add_argument( '--ext', type=str, default='auto', help='Image extension. Options: auto |", "upscale=args.outscale, arch='clean', channel_multiplier=2, bg_upsampler=upsampler) os.makedirs(args.output, exist_ok=True) if os.path.isfile(args.input): paths =", "\"png\" else: extension = args.ext if img_mode == 'RGBA': #", "{round((time.perf_counter() - startTime), 4)} seconds') if __name__ == '__main__': main()", "help='Output folder') parser.add_argument('-s', '--outscale', type=float, default=4, help='The final upsampling scale", "during inference') parser.add_argument( '--alpha_upsampler', type=str, default='realesrgan', help='The upsampler for the", "parser.add_argument('--half', action='store_true', help='Use half precision during inference') parser.add_argument( '--alpha_upsampler', type=str,", "num_grow_ch=32, scale=4) netscale = 4 elif args.model_name in ['RealESRGAN_x2plus']: #", "image') parser.add_argument('--suffix', type=str, default='Realesrgan-4x', help='Suffix of the restored image') parser.add_argument('-t',", "model paths model_path = os.path.join('experiments/pretrained_models', args.model_name + '.pth') if not", "tile=args.tile, tile_pad=args.tile_pad, pre_pad=args.pre_pad, half=args.half) if args.face_enhance: # Use GFPGAN for", "default=0, help='Pre padding size at each border') parser.add_argument('--face_enhance', action='store_true', help='Use", "= RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) netscale = 4", "of the image') parser.add_argument('--suffix', type=str, default='Realesrgan-4x', help='Suffix of the restored", "6 blocks model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)", "time from realesrgan import RealESRGANer from realesrgan.archs.srvgg_arch import SRVGGNetCompact def", "scale of the image') parser.add_argument('--suffix', type=str, default='Realesrgan-4x', help='Suffix of the", "args.model_name in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']: # x4 RRDBNet model model =", "num_feat=64, num_block=23, num_grow_ch=32, scale=2) netscale = 2 elif args.model_name in", "and img.shape[2] == 4: img_mode = 'RGBA' else: img_mode =", "'.pth') if not os.path.isfile(model_path): raise ValueError(f'Model {args.model_name} does not exist.')", "enhancement from gfpgan import GFPGANer face_enhancer = GFPGANer( model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth', upscale=args.outscale,", "= 4 elif args.model_name in ['RealESRGAN_x4plus_anime_6B']: # x4 RRDBNet model", "extension = \"png\" else: extension = args.ext if img_mode ==", "= SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=2, act_type='prelu') netscale = 2", "args.face_enhance: _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True) else:", "Use GFPGAN for face enhancement from gfpgan import GFPGANer face_enhancer", "RRDBNet import time from realesrgan import RealESRGANer from realesrgan.archs.srvgg_arch import", "demo for Real-ESRGAN. \"\"\" parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str,", "scale=netscale, model_path=model_path, model=model, tile=args.tile, tile_pad=args.tile_pad, pre_pad=args.pre_pad, half=args.half) if args.face_enhance: #", "args.model_name in [ 'RealESRGANv2-anime-xsx2', 'RealESRGANv2-animevideo-xsx2-nousm', 'RealESRGANv2-animevideo-xsx2' ]: # x2 VGG-style", "RGBA images should be saved in png format extension =", "smaller number.') else: cv2.imwrite(save_path, output) print(f'NO.{idx}, {imgname} is done, used", "else: cv2.imwrite(save_path, output) print(f'NO.{idx}, {imgname} is done, used {round((time.perf_counter() -", "args.model_name.split('.')[0] if args.model_name in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']: # x4 RRDBNet model", "in png format extension = 'png' save_path = os.path.join(args.output, f'{imgname}-{args.suffix}.{extension}')", "size, 0 for no tile during testing') parser.add_argument('--tile_pad', type=int, default=10,", "[ 'RealESRGANv2-anime-xsx2', 'RealESRGANv2-animevideo-xsx2-nousm', 'RealESRGANv2-animevideo-xsx2' ]: # x2 VGG-style model (XS", "cv2.IMREAD_UNCHANGED) if len(img.shape) == 3 and img.shape[2] == 4: img_mode", "_, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True) else: output,", "type=str, default='results', help='Output folder') parser.add_argument('-s', '--outscale', type=float, default=4, help='The final", "os.path.join('experiments/pretrained_models', args.model_name + '.pth') if not os.path.isfile(model_path): model_path = os.path.join('realesrgan/weights',", "'RealESRGANv2-anime-xsx4', 'RealESRGANv2-animevideo-xsx4-nousm', 'RealESRGANv2-animevideo-xsx4' ]: # x4 VGG-style model (XS size)", "# x4 RRDBNet model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23,", "paths = [args.input] else: paths = sorted(glob.glob(os.path.join(args.input, '*'))) for idx,", "parser.add_argument('-t', '--tile', type=int, default=0, help='Tile size, 0 for no tile", "model with 6 blocks model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6,", "['RealESRGAN_x2plus']: # x2 RRDBNet model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64,", "inputs') args = parser.parse_args() # determine models according to model", "os from basicsr.archs.rrdbnet_arch import RRDBNet import time from realesrgan import", "print(f'NO.{idx}, {imgname} is done, used {round((time.perf_counter() - startTime), 4)} seconds')", "parser.add_argument( '-n', '--model_name', type=str, default='RealESRGAN_x4plus', help=('Model names: RealESRGAN_x4plus | RealESRNet_x4plus", "the same extension as inputs') args = parser.parse_args() # determine", "alpha channels. Options: realesrgan | bicubic') parser.add_argument( '--ext', type=str, default='auto',", "face enhancement from gfpgan import GFPGANer face_enhancer = GFPGANer( model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth',", "= RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2) netscale = 2", "# determine models according to model names args.model_name = args.model_name.split('.')[0]", "parser.add_argument( '--ext', type=str, default='auto', help='Image extension. Options: auto | jpg", "elif args.model_name in [ 'RealESRGANv2-anime-xsx2', 'RealESRGANv2-animevideo-xsx2-nousm', 'RealESRGANv2-animevideo-xsx2' ]: # x2", "num_conv=16, upscale=4, act_type='prelu') netscale = 4 else: model = RRDBNet(num_in_ch=3,", "output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True) else: output, _ =", "RealESRGANv2-animevideo-xsx4')) parser.add_argument('-o', '--output', type=str, default='results', help='Output folder') parser.add_argument('-s', '--outscale', type=float,", "'RGBA': # RGBA images should be saved in png format", "RealESRGANer from realesrgan.archs.srvgg_arch import SRVGGNetCompact def main(): \"\"\"Inference demo for", "has_aligned=False, only_center_face=False, paste_back=True) else: output, _ = upsampler.enhance(img, outscale=args.outscale) except", "import GFPGANer face_enhancer = GFPGANer( model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth', upscale=args.outscale, arch='clean', channel_multiplier=2, bg_upsampler=upsampler)", "you encounter CUDA out of memory, try to set --tile", "if args.ext == 'auto': extension = \"png\" else: extension =", "extension. Options: auto | jpg | png, auto means using", "{imgname} is done, used {round((time.perf_counter() - startTime), 4)} seconds') if", "# x2 VGG-style model (XS size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3,", "Options: auto | jpg | png, auto means using the", "args.model_name in ['RealESRGAN_x2plus']: # x2 RRDBNet model model = RRDBNet(num_in_ch=3,", "set --tile with a smaller number.') else: cv2.imwrite(save_path, output) print(f'NO.{idx},", "args.model_name in ['RealESRGAN_x4plus_anime_6B']: # x4 RRDBNet model with 6 blocks", "if len(img.shape) == 3 and img.shape[2] == 4: img_mode =", "restored image') parser.add_argument('-t', '--tile', type=int, default=0, help='Tile size, 0 for", "'-n', '--model_name', type=str, default='RealESRGAN_x4plus', help=('Model names: RealESRGAN_x4plus | RealESRNet_x4plus |", "RealESRGANv2-animevideo-xsx2-nousm | RealESRGANv2-animevideo-xsx2' 'RealESRGANv2-anime-xsx4 | RealESRGANv2-animevideo-xsx4-nousm | RealESRGANv2-animevideo-xsx4')) parser.add_argument('-o', '--output',", "cv2 import glob import os from basicsr.archs.rrdbnet_arch import RRDBNet import", "else: img_mode = None if args.ext == 'auto': extension =", "'.pth') if not os.path.isfile(model_path): model_path = os.path.join('realesrgan/weights', args.model_name + '.pth')", "imgname, extension = os.path.splitext(os.path.basename(path)) img = cv2.imread(path, cv2.IMREAD_UNCHANGED) if len(img.shape)", "extension = 'png' save_path = os.path.join(args.output, f'{imgname}-{args.suffix}.{extension}') if os.path.exists(save_path): continue", "args.face_enhance: # Use GFPGAN for face enhancement from gfpgan import", "args.model_name = args.model_name.split('.')[0] if args.model_name in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']: # x4", "(XS size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')", "args = parser.parse_args() # determine models according to model names", "help='Use GFPGAN to enhance face') parser.add_argument('--half', action='store_true', help='Use half precision", "encounter CUDA out of memory, try to set --tile with", "upscale=2, act_type='prelu') netscale = 2 elif args.model_name in [ 'RealESRGANv2-anime-xsx4',", "img_mode = 'RGBA' else: img_mode = None if args.ext ==", "num_block=6, num_grow_ch=32, scale=4) netscale = 4 # determine model paths", "cv2.imread(path, cv2.IMREAD_UNCHANGED) if len(img.shape) == 3 and img.shape[2] == 4:", "names: RealESRGAN_x4plus | RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus' 'RealESRGANv2-anime-xsx2 |", "help='Tile padding') parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding size at each", "ValueError(f'Model {args.model_name} does not exist.') # restorer upsampler = RealESRGANer(", "'RealESRNet_x4plus']: # x4 RRDBNet model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64,", "default=0, help='Tile size, 0 for no tile during testing') parser.add_argument('--tile_pad',", "'auto': extension = \"png\" else: extension = args.ext if img_mode", "SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu') netscale = 4 else:", "netscale = 2 elif args.model_name in [ 'RealESRGANv2-anime-xsx2', 'RealESRGANv2-animevideo-xsx2-nousm', 'RealESRGANv2-animevideo-xsx2'", "of memory, try to set --tile with a smaller number.')", "action='store_true', help='Use GFPGAN to enhance face') parser.add_argument('--half', action='store_true', help='Use half", "realesrgan import RealESRGANer from realesrgan.archs.srvgg_arch import SRVGGNetCompact def main(): \"\"\"Inference", "face') parser.add_argument('--half', action='store_true', help='Use half precision during inference') parser.add_argument( '--alpha_upsampler',", "in ['RealESRGAN_x2plus']: # x2 RRDBNet model model = RRDBNet(num_in_ch=3, num_out_ch=3,", "= os.path.join('realesrgan/weights', args.model_name + '.pth') if not os.path.isfile(model_path): raise ValueError(f'Model", "RRDBNet model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)", "precision during inference') parser.add_argument( '--alpha_upsampler', type=str, default='realesrgan', help='The upsampler for", "= parser.parse_args() # determine models according to model names args.model_name", "num_feat=64, num_block=23, num_grow_ch=32, scale=4) netscale = 4 elif args.model_name in", "num_conv=16, upscale=2, act_type='prelu') netscale = 2 elif args.model_name in [", "model (XS size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=2,", "RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus' 'RealESRGANv2-anime-xsx2 | RealESRGANv2-animevideo-xsx2-nousm | RealESRGANv2-animevideo-xsx2'", "determine models according to model names args.model_name = args.model_name.split('.')[0] if", "output) print(f'NO.{idx}, {imgname} is done, used {round((time.perf_counter() - startTime), 4)}", "help='Input image or folder') parser.add_argument( '-n', '--model_name', type=str, default='RealESRGAN_x4plus', help=('Model", "parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to enhance face') parser.add_argument('--half', action='store_true', help='Use", "cv2.imwrite(save_path, output) print(f'NO.{idx}, {imgname} is done, used {round((time.perf_counter() - startTime),", "parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding') parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding", "args.model_name + '.pth') if not os.path.isfile(model_path): model_path = os.path.join('realesrgan/weights', args.model_name", "num_feat=64, num_conv=16, upscale=2, act_type='prelu') netscale = 2 elif args.model_name in", "startTime = time.perf_counter() imgname, extension = os.path.splitext(os.path.basename(path)) img = cv2.imread(path,", "x4 RRDBNet model with 6 blocks model = RRDBNet(num_in_ch=3, num_out_ch=3,", "png format extension = 'png' save_path = os.path.join(args.output, f'{imgname}-{args.suffix}.{extension}') if", "to model names args.model_name = args.model_name.split('.')[0] if args.model_name in ['RealESRGAN_x4plus',", "folder') parser.add_argument( '-n', '--model_name', type=str, default='RealESRGAN_x4plus', help=('Model names: RealESRGAN_x4plus |", "padding size at each border') parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to", "None if args.ext == 'auto': extension = \"png\" else: extension", "model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4) netscale =", "netscale = 4 elif args.model_name in ['RealESRGAN_x4plus_anime_6B']: # x4 RRDBNet", "enumerate(paths): startTime = time.perf_counter() imgname, extension = os.path.splitext(os.path.basename(path)) img =", "args.model_name + '.pth') if not os.path.isfile(model_path): raise ValueError(f'Model {args.model_name} does", "= None if args.ext == 'auto': extension = \"png\" else:", "names args.model_name = args.model_name.split('.')[0] if args.model_name in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']: #", "= 'png' save_path = os.path.join(args.output, f'{imgname}-{args.suffix}.{extension}') if os.path.exists(save_path): continue try:", "'--outscale', type=float, default=4, help='The final upsampling scale of the image')", "import cv2 import glob import os from basicsr.archs.rrdbnet_arch import RRDBNet", "parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding size at each border') parser.add_argument('--face_enhance',", "type=int, default=0, help='Pre padding size at each border') parser.add_argument('--face_enhance', action='store_true',", "'RGBA' else: img_mode = None if args.ext == 'auto': extension", "help='Tile size, 0 for no tile during testing') parser.add_argument('--tile_pad', type=int,", "print('Error', error) print('If you encounter CUDA out of memory, try", "| RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus' 'RealESRGANv2-anime-xsx2 | RealESRGANv2-animevideo-xsx2-nousm |", "image') parser.add_argument('-t', '--tile', type=int, default=0, help='Tile size, 0 for no", "model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2) netscale", "+ '.pth') if not os.path.isfile(model_path): raise ValueError(f'Model {args.model_name} does not", "4 else: model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)", "testing') parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding') parser.add_argument('--pre_pad', type=int, default=0, help='Pre", "in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']: # x4 RRDBNet model model = RRDBNet(num_in_ch=3,", "os.path.isfile(args.input): paths = [args.input] else: paths = sorted(glob.glob(os.path.join(args.input, '*'))) for", "sorted(glob.glob(os.path.join(args.input, '*'))) for idx, path in enumerate(paths): startTime = time.perf_counter()", "| bicubic') parser.add_argument( '--ext', type=str, default='auto', help='Image extension. Options: auto", "| RealESRGANv2-animevideo-xsx2' 'RealESRGANv2-anime-xsx4 | RealESRGANv2-animevideo-xsx4-nousm | RealESRGANv2-animevideo-xsx4')) parser.add_argument('-o', '--output', type=str,", "help='Suffix of the restored image') parser.add_argument('-t', '--tile', type=int, default=0, help='Tile", "num_block=23, num_grow_ch=32, scale=4) netscale = 4 elif args.model_name in ['RealESRGAN_x4plus_anime_6B']:", "according to model names args.model_name = args.model_name.split('.')[0] if args.model_name in", "from realesrgan.archs.srvgg_arch import SRVGGNetCompact def main(): \"\"\"Inference demo for Real-ESRGAN.", "os.path.isfile(model_path): model_path = os.path.join('realesrgan/weights', args.model_name + '.pth') if not os.path.isfile(model_path):", "if img_mode == 'RGBA': # RGBA images should be saved", "with 6 blocks model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32,", "as error: print('Error', error) print('If you encounter CUDA out of", "continue try: if args.face_enhance: _, _, output = face_enhancer.enhance(img, has_aligned=False,", "parser.add_argument('-i', '--input', type=str, default='inputs', help='Input image or folder') parser.add_argument( '-n',", "if args.model_name in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']: # x4 RRDBNet model model", "['RealESRGAN_x4plus', 'RealESRNet_x4plus']: # x4 RRDBNet model model = RRDBNet(num_in_ch=3, num_out_ch=3,", "'--ext', type=str, default='auto', help='Image extension. Options: auto | jpg |", "help=('Model names: RealESRGAN_x4plus | RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus' 'RealESRGANv2-anime-xsx2", "parser.add_argument('-o', '--output', type=str, default='results', help='Output folder') parser.add_argument('-s', '--outscale', type=float, default=4,", "elif args.model_name in ['RealESRGAN_x2plus']: # x2 RRDBNet model model =", "== 3 and img.shape[2] == 4: img_mode = 'RGBA' else:", "else: output, _ = upsampler.enhance(img, outscale=args.outscale) except RuntimeError as error:", "RealESRGANv2-animevideo-xsx4-nousm | RealESRGANv2-animevideo-xsx4')) parser.add_argument('-o', '--output', type=str, default='results', help='Output folder') parser.add_argument('-s',", "RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4) netscale = 4 elif", "default='inputs', help='Input image or folder') parser.add_argument( '-n', '--model_name', type=str, default='RealESRGAN_x4plus',", "os.path.splitext(os.path.basename(path)) img = cv2.imread(path, cv2.IMREAD_UNCHANGED) if len(img.shape) == 3 and", "images should be saved in png format extension = 'png'", "default='auto', help='Image extension. Options: auto | jpg | png, auto", "= 4 else: model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32,", "model (XS size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4,", "from realesrgan import RealESRGANer from realesrgan.archs.srvgg_arch import SRVGGNetCompact def main():", "in [ 'RealESRGANv2-anime-xsx4', 'RealESRGANv2-animevideo-xsx4-nousm', 'RealESRGANv2-animevideo-xsx4' ]: # x4 VGG-style model", "upsampler for the alpha channels. Options: realesrgan | bicubic') parser.add_argument(", "img = cv2.imread(path, cv2.IMREAD_UNCHANGED) if len(img.shape) == 3 and img.shape[2]", "as inputs') args = parser.parse_args() # determine models according to", "os.makedirs(args.output, exist_ok=True) if os.path.isfile(args.input): paths = [args.input] else: paths =", "for the alpha channels. Options: realesrgan | bicubic') parser.add_argument( '--ext',", "RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus' 'RealESRGANv2-anime-xsx2 | RealESRGANv2-animevideo-xsx2-nousm | RealESRGANv2-animevideo-xsx2' 'RealESRGANv2-anime-xsx4 |", "type=float, default=4, help='The final upsampling scale of the image') parser.add_argument('--suffix',", "auto means using the same extension as inputs') args =", "Real-ESRGAN. \"\"\" parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, default='inputs', help='Input", "models according to model names args.model_name = args.model_name.split('.')[0] if args.model_name", "= RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4) netscale = 4", "half precision during inference') parser.add_argument( '--alpha_upsampler', type=str, default='realesrgan', help='The upsampler", "blocks model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) netscale", "# Use GFPGAN for face enhancement from gfpgan import GFPGANer", "RRDBNet model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)", "import glob import os from basicsr.archs.rrdbnet_arch import RRDBNet import time", "| RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus' 'RealESRGANv2-anime-xsx2 | RealESRGANv2-animevideo-xsx2-nousm | RealESRGANv2-animevideo-xsx2' 'RealESRGANv2-anime-xsx4", "== 'RGBA': # RGBA images should be saved in png", "# x4 VGG-style model (XS size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3,", "+ '.pth') if not os.path.isfile(model_path): model_path = os.path.join('realesrgan/weights', args.model_name +", "args.ext == 'auto': extension = \"png\" else: extension = args.ext", "the restored image') parser.add_argument('-t', '--tile', type=int, default=0, help='Tile size, 0", "4 elif args.model_name in ['RealESRGAN_x4plus_anime_6B']: # x4 RRDBNet model with", "num_feat=64, num_block=6, num_grow_ch=32, scale=4) netscale = 4 # determine model", "= RealESRGANer( scale=netscale, model_path=model_path, model=model, tile=args.tile, tile_pad=args.tile_pad, pre_pad=args.pre_pad, half=args.half) if", "GFPGANer( model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth', upscale=args.outscale, arch='clean', channel_multiplier=2, bg_upsampler=upsampler) os.makedirs(args.output, exist_ok=True) if os.path.isfile(args.input):", "parser.parse_args() # determine models according to model names args.model_name =", "realesrgan.archs.srvgg_arch import SRVGGNetCompact def main(): \"\"\"Inference demo for Real-ESRGAN. \"\"\"", "face_enhancer = GFPGANer( model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth', upscale=args.outscale, arch='clean', channel_multiplier=2, bg_upsampler=upsampler) os.makedirs(args.output, exist_ok=True)", "# x2 RRDBNet model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23,", "model=model, tile=args.tile, tile_pad=args.tile_pad, pre_pad=args.pre_pad, half=args.half) if args.face_enhance: # Use GFPGAN", "Options: realesrgan | bicubic') parser.add_argument( '--ext', type=str, default='auto', help='Image extension.", "size at each border') parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to enhance", "model names args.model_name = args.model_name.split('.')[0] if args.model_name in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']:", "idx, path in enumerate(paths): startTime = time.perf_counter() imgname, extension =", "x4 RRDBNet model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32,", "error: print('Error', error) print('If you encounter CUDA out of memory,", "num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4) netscale = 4 elif args.model_name", "(XS size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=2, act_type='prelu')", "default='RealESRGAN_x4plus', help=('Model names: RealESRGAN_x4plus | RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus'", "[ 'RealESRGANv2-anime-xsx4', 'RealESRGANv2-animevideo-xsx4-nousm', 'RealESRGANv2-animevideo-xsx4' ]: # x4 VGG-style model (XS", "is done, used {round((time.perf_counter() - startTime), 4)} seconds') if __name__", "RealESRGANer( scale=netscale, model_path=model_path, model=model, tile=args.tile, tile_pad=args.tile_pad, pre_pad=args.pre_pad, half=args.half) if args.face_enhance:", "2 elif args.model_name in [ 'RealESRGANv2-anime-xsx4', 'RealESRGANv2-animevideo-xsx4-nousm', 'RealESRGANv2-animevideo-xsx4' ]: #", "num_grow_ch=32, scale=4) netscale = 4 # determine model paths model_path", "len(img.shape) == 3 and img.shape[2] == 4: img_mode = 'RGBA'", "= 2 elif args.model_name in [ 'RealESRGANv2-anime-xsx4', 'RealESRGANv2-animevideo-xsx4-nousm', 'RealESRGANv2-animevideo-xsx4' ]:", "means using the same extension as inputs') args = parser.parse_args()", "# determine model paths model_path = os.path.join('experiments/pretrained_models', args.model_name + '.pth')", "= GFPGANer( model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth', upscale=args.outscale, arch='clean', channel_multiplier=2, bg_upsampler=upsampler) os.makedirs(args.output, exist_ok=True) if", "during testing') parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding') parser.add_argument('--pre_pad', type=int, default=0,", "num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) netscale = 4 elif args.model_name", "'--output', type=str, default='results', help='Output folder') parser.add_argument('-s', '--outscale', type=float, default=4, help='The", "output, _ = upsampler.enhance(img, outscale=args.outscale) except RuntimeError as error: print('Error',", "| RealESRGANv2-animevideo-xsx2-nousm | RealESRGANv2-animevideo-xsx2' 'RealESRGANv2-anime-xsx4 | RealESRGANv2-animevideo-xsx4-nousm | RealESRGANv2-animevideo-xsx4')) parser.add_argument('-o',", "gfpgan import GFPGANer face_enhancer = GFPGANer( model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth', upscale=args.outscale, arch='clean', channel_multiplier=2,", "help='Use half precision during inference') parser.add_argument( '--alpha_upsampler', type=str, default='realesrgan', help='The", "num_grow_ch=32, scale=4) netscale = 4 elif args.model_name in ['RealESRGAN_x4plus_anime_6B']: #", "type=str, default='Realesrgan-4x', help='Suffix of the restored image') parser.add_argument('-t', '--tile', type=int,", "= args.ext if img_mode == 'RGBA': # RGBA images should", "args.ext if img_mode == 'RGBA': # RGBA images should be", "enhance face') parser.add_argument('--half', action='store_true', help='Use half precision during inference') parser.add_argument(", "with a smaller number.') else: cv2.imwrite(save_path, output) print(f'NO.{idx}, {imgname} is", "no tile during testing') parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding') parser.add_argument('--pre_pad',", "GFPGAN to enhance face') parser.add_argument('--half', action='store_true', help='Use half precision during", "RealESRGANv2-animevideo-xsx2' 'RealESRGANv2-anime-xsx4 | RealESRGANv2-animevideo-xsx4-nousm | RealESRGANv2-animevideo-xsx4')) parser.add_argument('-o', '--output', type=str, default='results',", "action='store_true', help='Use half precision during inference') parser.add_argument( '--alpha_upsampler', type=str, default='realesrgan',", "saved in png format extension = 'png' save_path = os.path.join(args.output,", "\"\"\" parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, default='inputs', help='Input image", "type=str, default='inputs', help='Input image or folder') parser.add_argument( '-n', '--model_name', type=str,", "x2 VGG-style model (XS size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64,", "model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4) netscale", "RealESRGAN_x4plus | RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus' 'RealESRGANv2-anime-xsx2 | RealESRGANv2-animevideo-xsx2-nousm", "4 elif args.model_name in ['RealESRGAN_x2plus']: # x2 RRDBNet model model", "extension as inputs') args = parser.parse_args() # determine models according", "upscale=4, act_type='prelu') netscale = 4 else: model = RRDBNet(num_in_ch=3, num_out_ch=3,", "default='Realesrgan-4x', help='Suffix of the restored image') parser.add_argument('-t', '--tile', type=int, default=0,", "'--model_name', type=str, default='RealESRGAN_x4plus', help=('Model names: RealESRGAN_x4plus | RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B", "act_type='prelu') netscale = 2 elif args.model_name in [ 'RealESRGANv2-anime-xsx4', 'RealESRGANv2-animevideo-xsx4-nousm',", "os.path.join('realesrgan/weights', args.model_name + '.pth') if not os.path.isfile(model_path): raise ValueError(f'Model {args.model_name}", "at each border') parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to enhance face')", "jpg | png, auto means using the same extension as", "half=args.half) if args.face_enhance: # Use GFPGAN for face enhancement from", "GFPGANer face_enhancer = GFPGANer( model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth', upscale=args.outscale, arch='clean', channel_multiplier=2, bg_upsampler=upsampler) os.makedirs(args.output,", "= 2 elif args.model_name in [ 'RealESRGANv2-anime-xsx2', 'RealESRGANv2-animevideo-xsx2-nousm', 'RealESRGANv2-animevideo-xsx2' ]:", "\"\"\"Inference demo for Real-ESRGAN. \"\"\" parser = argparse.ArgumentParser() parser.add_argument('-i', '--input',", "GFPGAN for face enhancement from gfpgan import GFPGANer face_enhancer =", "channel_multiplier=2, bg_upsampler=upsampler) os.makedirs(args.output, exist_ok=True) if os.path.isfile(args.input): paths = [args.input] else:", "= 4 elif args.model_name in ['RealESRGAN_x2plus']: # x2 RRDBNet model", "arch='clean', channel_multiplier=2, bg_upsampler=upsampler) os.makedirs(args.output, exist_ok=True) if os.path.isfile(args.input): paths = [args.input]", "done, used {round((time.perf_counter() - startTime), 4)} seconds') if __name__ ==", "'RealESRGANv2-anime-xsx2 | RealESRGANv2-animevideo-xsx2-nousm | RealESRGANv2-animevideo-xsx2' 'RealESRGANv2-anime-xsx4 | RealESRGANv2-animevideo-xsx4-nousm | RealESRGANv2-animevideo-xsx4'))", "= os.path.join('experiments/pretrained_models', args.model_name + '.pth') if not os.path.isfile(model_path): model_path =", "paths = sorted(glob.glob(os.path.join(args.input, '*'))) for idx, path in enumerate(paths): startTime", "num_feat=64, num_conv=16, upscale=4, act_type='prelu') netscale = 4 else: model =", "if args.face_enhance: # Use GFPGAN for face enhancement from gfpgan", "exist.') # restorer upsampler = RealESRGANer( scale=netscale, model_path=model_path, model=model, tile=args.tile,", "using the same extension as inputs') args = parser.parse_args() #", "netscale = 4 # determine model paths model_path = os.path.join('experiments/pretrained_models',", "main(): \"\"\"Inference demo for Real-ESRGAN. \"\"\" parser = argparse.ArgumentParser() parser.add_argument('-i',", "parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, default='inputs', help='Input image or", "auto | jpg | png, auto means using the same", "size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu') netscale", "only_center_face=False, paste_back=True) else: output, _ = upsampler.enhance(img, outscale=args.outscale) except RuntimeError", "# RGBA images should be saved in png format extension", "RRDBNet model with 6 blocks model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64,", "out of memory, try to set --tile with a smaller", "= os.path.join(args.output, f'{imgname}-{args.suffix}.{extension}') if os.path.exists(save_path): continue try: if args.face_enhance: _,", "padding') parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding size at each border')", "[args.input] else: paths = sorted(glob.glob(os.path.join(args.input, '*'))) for idx, path in", "default='results', help='Output folder') parser.add_argument('-s', '--outscale', type=float, default=4, help='The final upsampling", "= cv2.imread(path, cv2.IMREAD_UNCHANGED) if len(img.shape) == 3 and img.shape[2] ==", "= upsampler.enhance(img, outscale=args.outscale) except RuntimeError as error: print('Error', error) print('If", "type=int, default=10, help='Tile padding') parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding size", "= SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu') netscale = 4", "realesrgan | bicubic') parser.add_argument( '--ext', type=str, default='auto', help='Image extension. Options:", "act_type='prelu') netscale = 4 else: model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64,", "restorer upsampler = RealESRGANer( scale=netscale, model_path=model_path, model=model, tile=args.tile, tile_pad=args.tile_pad, pre_pad=args.pre_pad,", "size) model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=2, act_type='prelu') netscale", "import SRVGGNetCompact def main(): \"\"\"Inference demo for Real-ESRGAN. \"\"\" parser", "| RealESRGAN_x2plus' 'RealESRGANv2-anime-xsx2 | RealESRGANv2-animevideo-xsx2-nousm | RealESRGANv2-animevideo-xsx2' 'RealESRGANv2-anime-xsx4 | RealESRGANv2-animevideo-xsx4-nousm", "from basicsr.archs.rrdbnet_arch import RRDBNet import time from realesrgan import RealESRGANer", "{args.model_name} does not exist.') # restorer upsampler = RealESRGANer( scale=netscale,", "netscale = 4 elif args.model_name in ['RealESRGAN_x2plus']: # x2 RRDBNet", "from gfpgan import GFPGANer face_enhancer = GFPGANer( model_path='https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth', upscale=args.outscale, arch='clean',", "else: model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4) netscale", "used {round((time.perf_counter() - startTime), 4)} seconds') if __name__ == '__main__':", "raise ValueError(f'Model {args.model_name} does not exist.') # restorer upsampler =", "should be saved in png format extension = 'png' save_path", "os.path.isfile(model_path): raise ValueError(f'Model {args.model_name} does not exist.') # restorer upsampler", "path in enumerate(paths): startTime = time.perf_counter() imgname, extension = os.path.splitext(os.path.basename(path))", "parser.add_argument('-s', '--outscale', type=float, default=4, help='The final upsampling scale of the", "= 4 # determine model paths model_path = os.path.join('experiments/pretrained_models', args.model_name", "scale=2) netscale = 2 elif args.model_name in [ 'RealESRGANv2-anime-xsx2', 'RealESRGANv2-animevideo-xsx2-nousm',", "'RealESRGANv2-anime-xsx4 | RealESRGANv2-animevideo-xsx4-nousm | RealESRGANv2-animevideo-xsx4')) parser.add_argument('-o', '--output', type=str, default='results', help='Output", "| RealESRGANv2-animevideo-xsx4-nousm | RealESRGANv2-animevideo-xsx4')) parser.add_argument('-o', '--output', type=str, default='results', help='Output folder')", "num_block=23, num_grow_ch=32, scale=2) netscale = 2 elif args.model_name in [", "2 elif args.model_name in [ 'RealESRGANv2-anime-xsx2', 'RealESRGANv2-animevideo-xsx2-nousm', 'RealESRGANv2-animevideo-xsx2' ]: #", "== 'auto': extension = \"png\" else: extension = args.ext if", "scale=4) netscale = 4 # determine model paths model_path =", "args.model_name in [ 'RealESRGANv2-anime-xsx4', 'RealESRGANv2-animevideo-xsx4-nousm', 'RealESRGANv2-animevideo-xsx4' ]: # x4 VGG-style", "a smaller number.') else: cv2.imwrite(save_path, output) print(f'NO.{idx}, {imgname} is done,", "import RealESRGANer from realesrgan.archs.srvgg_arch import SRVGGNetCompact def main(): \"\"\"Inference demo", "os.path.join(args.output, f'{imgname}-{args.suffix}.{extension}') if os.path.exists(save_path): continue try: if args.face_enhance: _, _,", "RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2) netscale = 2 elif", "elif args.model_name in ['RealESRGAN_x4plus_anime_6B']: # x4 RRDBNet model with 6", "if os.path.exists(save_path): continue try: if args.face_enhance: _, _, output =", "= [args.input] else: paths = sorted(glob.glob(os.path.join(args.input, '*'))) for idx, path", "num_grow_ch=32, scale=2) netscale = 2 elif args.model_name in [ 'RealESRGANv2-anime-xsx2',", "# restorer upsampler = RealESRGANer( scale=netscale, model_path=model_path, model=model, tile=args.tile, tile_pad=args.tile_pad,", "model_path = os.path.join('experiments/pretrained_models', args.model_name + '.pth') if not os.path.isfile(model_path): model_path", "paths model_path = os.path.join('experiments/pretrained_models', args.model_name + '.pth') if not os.path.isfile(model_path):", "= argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, default='inputs', help='Input image or folder')", "'RealESRGANv2-animevideo-xsx4-nousm', 'RealESRGANv2-animevideo-xsx4' ]: # x4 VGG-style model (XS size) model", "= os.path.splitext(os.path.basename(path)) img = cv2.imread(path, cv2.IMREAD_UNCHANGED) if len(img.shape) == 3", "if args.face_enhance: _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)", "'*'))) for idx, path in enumerate(paths): startTime = time.perf_counter() imgname,", "to enhance face') parser.add_argument('--half', action='store_true', help='Use half precision during inference')", "same extension as inputs') args = parser.parse_args() # determine models", "time.perf_counter() imgname, extension = os.path.splitext(os.path.basename(path)) img = cv2.imread(path, cv2.IMREAD_UNCHANGED) if", "RealESRGAN_x2plus' 'RealESRGANv2-anime-xsx2 | RealESRGANv2-animevideo-xsx2-nousm | RealESRGANv2-animevideo-xsx2' 'RealESRGANv2-anime-xsx4 | RealESRGANv2-animevideo-xsx4-nousm |", "import RRDBNet import time from realesrgan import RealESRGANer from realesrgan.archs.srvgg_arch", "CUDA out of memory, try to set --tile with a", "if not os.path.isfile(model_path): raise ValueError(f'Model {args.model_name} does not exist.') #", "'--input', type=str, default='inputs', help='Input image or folder') parser.add_argument( '-n', '--model_name',", "be saved in png format extension = 'png' save_path =", "print('If you encounter CUDA out of memory, try to set", "import os from basicsr.archs.rrdbnet_arch import RRDBNet import time from realesrgan", "import time from realesrgan import RealESRGANer from realesrgan.archs.srvgg_arch import SRVGGNetCompact", "upsampler.enhance(img, outscale=args.outscale) except RuntimeError as error: print('Error', error) print('If you", "img_mode == 'RGBA': # RGBA images should be saved in", "x2 RRDBNet model model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32,", "basicsr.archs.rrdbnet_arch import RRDBNet import time from realesrgan import RealESRGANer from", "error) print('If you encounter CUDA out of memory, try to", "number.') else: cv2.imwrite(save_path, output) print(f'NO.{idx}, {imgname} is done, used {round((time.perf_counter()" ]
[ "try: os.remove(filename) msg = \"{} removed.\".format(filename) except FileNotFoundError as e:", "'REPORT', 'vasp.log', 'vasprun.xml', 'WAVECAR', 'XDATCAR' ] for filename in filenames_delete:", "= [ 'CHG', 'CHGCAR', 'CONTCAR', 'DOSCAR', 'EIGENVAL', 'IBZKPT', 'job.err', 'job.out',", "'DOSCAR', 'EIGENVAL', 'IBZKPT', 'job.err', 'job.out', 'OSZICAR', 'PCDAT', 'REPORT', 'vasp.log', 'vasprun.xml',", "for filename in filenames_delete: try: os.remove(filename) msg = \"{} removed.\".format(filename)", "FileNotFoundError as e: msg = \"{} does not exist.\".format(filename) except:", "os filenames_delete = [ 'CHG', 'CHGCAR', 'CONTCAR', 'DOSCAR', 'EIGENVAL', 'IBZKPT',", "\"{} removed.\".format(filename) except FileNotFoundError as e: msg = \"{} does", "filenames_delete: try: os.remove(filename) msg = \"{} removed.\".format(filename) except FileNotFoundError as", "'job.out', 'OSZICAR', 'PCDAT', 'REPORT', 'vasp.log', 'vasprun.xml', 'WAVECAR', 'XDATCAR' ] for", "'EIGENVAL', 'IBZKPT', 'job.err', 'job.out', 'OSZICAR', 'PCDAT', 'REPORT', 'vasp.log', 'vasprun.xml', 'WAVECAR',", "= \"{} removed.\".format(filename) except FileNotFoundError as e: msg = \"{}", "filenames_delete = [ 'CHG', 'CHGCAR', 'CONTCAR', 'DOSCAR', 'EIGENVAL', 'IBZKPT', 'job.err',", "'PCDAT', 'REPORT', 'vasp.log', 'vasprun.xml', 'WAVECAR', 'XDATCAR' ] for filename in", "import os filenames_delete = [ 'CHG', 'CHGCAR', 'CONTCAR', 'DOSCAR', 'EIGENVAL',", "'WAVECAR', 'XDATCAR' ] for filename in filenames_delete: try: os.remove(filename) msg", "removed.\".format(filename) except FileNotFoundError as e: msg = \"{} does not", "'OSZICAR', 'PCDAT', 'REPORT', 'vasp.log', 'vasprun.xml', 'WAVECAR', 'XDATCAR' ] for filename", "os.remove(filename) msg = \"{} removed.\".format(filename) except FileNotFoundError as e: msg", "<reponame>eragasa/pypospack import os filenames_delete = [ 'CHG', 'CHGCAR', 'CONTCAR', 'DOSCAR',", "'vasprun.xml', 'WAVECAR', 'XDATCAR' ] for filename in filenames_delete: try: os.remove(filename)", "'XDATCAR' ] for filename in filenames_delete: try: os.remove(filename) msg =", "] for filename in filenames_delete: try: os.remove(filename) msg = \"{}", "'CHG', 'CHGCAR', 'CONTCAR', 'DOSCAR', 'EIGENVAL', 'IBZKPT', 'job.err', 'job.out', 'OSZICAR', 'PCDAT',", "'CONTCAR', 'DOSCAR', 'EIGENVAL', 'IBZKPT', 'job.err', 'job.out', 'OSZICAR', 'PCDAT', 'REPORT', 'vasp.log',", "filename in filenames_delete: try: os.remove(filename) msg = \"{} removed.\".format(filename) except", "'job.err', 'job.out', 'OSZICAR', 'PCDAT', 'REPORT', 'vasp.log', 'vasprun.xml', 'WAVECAR', 'XDATCAR' ]", "'vasp.log', 'vasprun.xml', 'WAVECAR', 'XDATCAR' ] for filename in filenames_delete: try:", "'CHGCAR', 'CONTCAR', 'DOSCAR', 'EIGENVAL', 'IBZKPT', 'job.err', 'job.out', 'OSZICAR', 'PCDAT', 'REPORT',", "msg = \"{} removed.\".format(filename) except FileNotFoundError as e: msg =", "as e: msg = \"{} does not exist.\".format(filename) except: raise", "in filenames_delete: try: os.remove(filename) msg = \"{} removed.\".format(filename) except FileNotFoundError", "[ 'CHG', 'CHGCAR', 'CONTCAR', 'DOSCAR', 'EIGENVAL', 'IBZKPT', 'job.err', 'job.out', 'OSZICAR',", "e: msg = \"{} does not exist.\".format(filename) except: raise print(msg)", "'IBZKPT', 'job.err', 'job.out', 'OSZICAR', 'PCDAT', 'REPORT', 'vasp.log', 'vasprun.xml', 'WAVECAR', 'XDATCAR'", "except FileNotFoundError as e: msg = \"{} does not exist.\".format(filename)" ]
[ "deque() # add the root node to the queue at", "collection import deque def largest_values_in_tree_rows(t): rv = [] if t", "# otherwise, we update `current_max` if we need to else:", "from collection import deque def largest_values_in_tree_rows(t): rv = [] if", "return rv current_depth = 0 current_max = t.value q =", "solution. See mine in largest_values_in_each_row.py ''' from collection import deque", "while len(q) > 0: node, depth = q.popleft() # if", "depth # otherwise, we update `current_max` if we need to", "node # to the queue, along with their depths if", "# don't forget to append the last `current_max` rv.append(current_max) return", "`rv` and then # reset `current_max` and `current_depth` if depth", "and then # reset `current_max` and `current_depth` if depth !=", "largest_values_in_tree_rows(t): rv = [] if t is None: return rv", "current_max = max(node.value, current_max) # add the left and right", "def largest_values_in_tree_rows(t): rv = [] if t is None: return", "to else: current_max = max(node.value, current_max) # add the left", "is None: return rv current_depth = 0 current_max = t.value", "<gh_stars>0 ''' <NAME>'s solution. See mine in largest_values_in_each_row.py ''' from", "0: node, depth = q.popleft() # if the depth of", "+ 1)) # don't forget to append the last `current_max`", "the queue at a depth of 0 q.append((t, current_depth)) while", "# `current_node`, add `current_max` to `rv` and then # reset", "to `rv` and then # reset `current_max` and `current_depth` if", "different from # `current_node`, add `current_max` to `rv` and then", "current_depth = 0 current_max = t.value q = deque() #", "the left and right children of the current node #", "depth of 0 q.append((t, current_depth)) while len(q) > 0: node,", "max(node.value, current_max) # add the left and right children of", "left and right children of the current node # to", "= depth # otherwise, we update `current_max` if we need", "otherwise, we update `current_max` if we need to else: current_max", "= node.value current_depth = depth # otherwise, we update `current_max`", "# reset `current_max` and `current_depth` if depth != current_depth: rv.append(current_max)", "mine in largest_values_in_each_row.py ''' from collection import deque def largest_values_in_tree_rows(t):", "q.popleft() # if the depth of the current node is", "current_depth: rv.append(current_max) current_max = node.value current_depth = depth # otherwise,", "q.append((node.right, depth + 1)) # don't forget to append the", "node to the queue at a depth of 0 q.append((t,", "= q.popleft() # if the depth of the current node", "= 0 current_max = t.value q = deque() # add", "we need to else: current_max = max(node.value, current_max) # add", "# add the left and right children of the current", "See mine in largest_values_in_each_row.py ''' from collection import deque def", "deque def largest_values_in_tree_rows(t): rv = [] if t is None:", "`current_max` and `current_depth` if depth != current_depth: rv.append(current_max) current_max =", "add the left and right children of the current node", "the depth of the current node is different from #", "+ 1)) if node.right: q.append((node.right, depth + 1)) # don't", "add the root node to the queue at a depth", "[] if t is None: return rv current_depth = 0", "right children of the current node # to the queue,", "# if the depth of the current node is different", "rv.append(current_max) current_max = node.value current_depth = depth # otherwise, we", "a depth of 0 q.append((t, current_depth)) while len(q) > 0:", "current_max = node.value current_depth = depth # otherwise, we update", "current node is different from # `current_node`, add `current_max` to", "the current node is different from # `current_node`, add `current_max`", "q.append((node.left, depth + 1)) if node.right: q.append((node.right, depth + 1))", "= [] if t is None: return rv current_depth =", "the queue, along with their depths if node.left: q.append((node.left, depth", "import deque def largest_values_in_tree_rows(t): rv = [] if t is", "None: return rv current_depth = 0 current_max = t.value q", "at a depth of 0 q.append((t, current_depth)) while len(q) >", "q.append((t, current_depth)) while len(q) > 0: node, depth = q.popleft()", "if node.right: q.append((node.right, depth + 1)) # don't forget to", "if t is None: return rv current_depth = 0 current_max", "queue, along with their depths if node.left: q.append((node.left, depth +", "= t.value q = deque() # add the root node", "1)) # don't forget to append the last `current_max` rv.append(current_max)", "to the queue, along with their depths if node.left: q.append((node.left,", "rv current_depth = 0 current_max = t.value q = deque()", "we update `current_max` if we need to else: current_max =", "queue at a depth of 0 q.append((t, current_depth)) while len(q)", "# to the queue, along with their depths if node.left:", "else: current_max = max(node.value, current_max) # add the left and", "don't forget to append the last `current_max` rv.append(current_max) return rv", "root node to the queue at a depth of 0", "need to else: current_max = max(node.value, current_max) # add the", "and right children of the current node # to the", "with their depths if node.left: q.append((node.left, depth + 1)) if", "to the queue at a depth of 0 q.append((t, current_depth))", "current_depth = depth # otherwise, we update `current_max` if we", "in largest_values_in_each_row.py ''' from collection import deque def largest_values_in_tree_rows(t): rv", "t is None: return rv current_depth = 0 current_max =", "> 0: node, depth = q.popleft() # if the depth", "# add the root node to the queue at a", "depth + 1)) if node.right: q.append((node.right, depth + 1)) #", "= max(node.value, current_max) # add the left and right children", "and `current_depth` if depth != current_depth: rv.append(current_max) current_max = node.value", "update `current_max` if we need to else: current_max = max(node.value,", "depth != current_depth: rv.append(current_max) current_max = node.value current_depth = depth", "add `current_max` to `rv` and then # reset `current_max` and", "of the current node # to the queue, along with", "from # `current_node`, add `current_max` to `rv` and then #", "node.right: q.append((node.right, depth + 1)) # don't forget to append", "then # reset `current_max` and `current_depth` if depth != current_depth:", "= deque() # add the root node to the queue", "if the depth of the current node is different from", "t.value q = deque() # add the root node to", "0 current_max = t.value q = deque() # add the", "1)) if node.right: q.append((node.right, depth + 1)) # don't forget", "current_max = t.value q = deque() # add the root", "`current_depth` if depth != current_depth: rv.append(current_max) current_max = node.value current_depth", "if node.left: q.append((node.left, depth + 1)) if node.right: q.append((node.right, depth", "depth + 1)) # don't forget to append the last", "`current_max` if we need to else: current_max = max(node.value, current_max)", "children of the current node # to the queue, along", "node, depth = q.popleft() # if the depth of the", "if depth != current_depth: rv.append(current_max) current_max = node.value current_depth =", "current node # to the queue, along with their depths", "reset `current_max` and `current_depth` if depth != current_depth: rv.append(current_max) current_max", "''' from collection import deque def largest_values_in_tree_rows(t): rv = []", "of 0 q.append((t, current_depth)) while len(q) > 0: node, depth", "''' <NAME>'s solution. See mine in largest_values_in_each_row.py ''' from collection", "len(q) > 0: node, depth = q.popleft() # if the", "current_depth)) while len(q) > 0: node, depth = q.popleft() #", "rv = [] if t is None: return rv current_depth", "0 q.append((t, current_depth)) while len(q) > 0: node, depth =", "!= current_depth: rv.append(current_max) current_max = node.value current_depth = depth #", "depths if node.left: q.append((node.left, depth + 1)) if node.right: q.append((node.right,", "current_max) # add the left and right children of the", "along with their depths if node.left: q.append((node.left, depth + 1))", "`current_max` to `rv` and then # reset `current_max` and `current_depth`", "node is different from # `current_node`, add `current_max` to `rv`", "of the current node is different from # `current_node`, add", "if we need to else: current_max = max(node.value, current_max) #", "node.left: q.append((node.left, depth + 1)) if node.right: q.append((node.right, depth +", "the current node # to the queue, along with their", "the root node to the queue at a depth of", "q = deque() # add the root node to the", "is different from # `current_node`, add `current_max` to `rv` and", "<NAME>'s solution. See mine in largest_values_in_each_row.py ''' from collection import", "node.value current_depth = depth # otherwise, we update `current_max` if", "`current_node`, add `current_max` to `rv` and then # reset `current_max`", "largest_values_in_each_row.py ''' from collection import deque def largest_values_in_tree_rows(t): rv =", "their depths if node.left: q.append((node.left, depth + 1)) if node.right:", "depth = q.popleft() # if the depth of the current", "depth of the current node is different from # `current_node`," ]
[ "[box[-1] for box in list_of_bboxes], \"bbox\": list_of_bboxes}) if adjust_score: ensemble_bbox_df[\"score\"]", "run_ensemble(get_TTA_results(\"fold1_256\", test_image_set, RCNN0_DETS_DIR.format(fold1_nom)), metadata) fold3RCNN0 = run_ensemble(get_TTA_results(\"fold3_320\", test_image_set, RCNN0_DETS_DIR.format(fold3_nom)), metadata)", "results_df[results_df.score >= threshold] results_df = results_df.merge(metadata, on=\"patientId\", how=\"left\") return results_df[[\"patientId\",", "\"x\", \"y\", \"w\", \"h\", \"bbox\", \"view\"]] with open(MAPPINGS_PATH) as f:", "box[1] w = box[2] h = box[3] topRight = (x1", "\"fold{}_{}\".format(7, imsizes[7]) fold8_nom = \"fold{}_{}\".format(8, imsizes[8]) fold9_nom = \"fold{}_{}\".format(9, imsizes[9])", "convert_dict_to_df(tmp_results, mapping, metadata, test_set=test_set, flip=False, threshold=0.01) TTAs.append(tmp_df) return TTAs execfile(os.path.join(WDIR,", "RCNN0_DETS_DIR.format(fold3_nom)), metadata) fold5RCNN0 = run_ensemble(get_TTA_results(\"fold5_384\", test_image_set, RCNN0_DETS_DIR.format(fold5_nom)), metadata) fold7RCNN0 =", "[] list_of_bboxes = [] for res in results: coco_image_id =", "final_TTA_ensemble[\"adjustedScore\"] = final_TTA_ensemble.score * final_TTA_ensemble.votes final_TTA_ensemble = final_TTA_ensemble[[\"patientId\", \"x\", \"y\",", "final_TTA_ensemble.votes final_TTA_ensemble = final_TTA_ensemble[[\"patientId\", \"x\", \"y\", \"w\", \"h\", \"score\", \"votes\",", "ensemble_bbox_df.votes return ensemble_bbox_df imsizes = [224, 256, 288, 320, 352,", "list_of_new_pids = [] list_of_bboxes = [] for i, ensemble_bboxes in", "- topRight[0], topRight[1]) return [newTopLeft[0], newTopLeft[1], w, h] def convert_dict_to_df(results,", "run_ensemble(get_TTA_results(\"fold7_448\", test_image_set, RCNN0_DETS_DIR.format(fold7_nom)), metadata) fold9RCNN0 = run_ensemble(get_TTA_results(\"fold9_512\", test_image_set, RCNN0_DETS_DIR.format(fold9_nom)), metadata)", "results_df = results_df[results_df.score >= threshold] results_df = results_df.merge(metadata, on=\"patientId\", how=\"left\")", "= [] list_of_ensemble_bboxes = [] for pid in np.unique(metadata.patientId): list_of_tmp_dfs", "convert_dict_to_df(tmp_results, flip_mapping, metadata, test_set=test_set, flip=True, threshold=0.01) else: tmp_df = convert_dict_to_df(tmp_results,", "= metadata[metadata.patientId == pid][\"view\"].iloc[0] for df_index, each_df in enumerate(list_of_dfs): tmp_df", "list_of_scores, \"x\": [box[0] for box in list_of_bboxes], \"y\": [box[1] for", "final_TTA_ensemble = run_ensemble(list_of_dfs, metadata, adjust_score=False) final_TTA_ensemble[\"adjustedScore\"] = final_TTA_ensemble.score * final_TTA_ensemble.votes", "convert_dict_to_df(results, mapping, metadata, test_set, flip=False, threshold=0.): list_of_image_ids = [] list_of_scores", "tmp_df.iterrows(): bbox = row.bbox bbox.append(1) bbox.append(row.score) list_of_bboxes.append(bbox) list_of_detections.append(list_of_bboxes) from src.infer.DetectionEnsemble", "\"fold{}_{}\".format(1, imsizes[1]) fold2_nom = \"fold{}_{}\".format(2, imsizes[2]) fold3_nom = \"fold{}_{}\".format(3, imsizes[3])", "with open(MAPPINGS_PATH) as f: mapping = json.load(f) with open(MAPPINGS_PATH.replace(test_image_set, \"{}_flip\".format(test_image_set)))", "4): [x1, y1, w, h] \"\"\" # Get top right", "in enumerate(list_of_ensemble_bboxes): for bbox in ensemble_bboxes: list_of_new_pids.append(list_of_pids[i]) list_of_bboxes.append(bbox) ensemble_bbox_df =", "[box[3] for box in list_of_bboxes], \"bbox\": list_of_bboxes}) results_df = results_df.sort_values([\"patientId\",", "fold4_nom = \"fold{}_{}\".format(4, imsizes[4]) fold5_nom = \"fold{}_{}\".format(5, imsizes[5]) fold6_nom =", "as f: flip_mapping = json.load(f) metadata = pd.read_csv(METADATA_PATH) def get_TTA_results(fold_imsize,", "coco_img_file = \"COCO_{}_{}.png\".format(test_set, str(coco_image_id).zfill(12)) list_of_image_ids.append(mapping[coco_img_file]) list_of_scores.append(res[\"score\"]) list_of_bboxes.append(res[\"bbox\"]) if flip: list_of_bboxes", "\"w\", \"h\", \"bbox\", \"view\"]] with open(MAPPINGS_PATH) as f: mapping =", "with open(filepath) as f: return json.load(f) def flip_box(box): \"\"\" box", "enumerate(list_of_ensemble_bboxes): for bbox in ensemble_bboxes: list_of_new_pids.append(list_of_pids[i]) list_of_bboxes.append(bbox) ensemble_bbox_df = pd.DataFrame({\"patientId\":", "= [] view = metadata[metadata.patientId == pid][\"view\"].iloc[0] for df_index, each_df", "fold3RCNN0, fold5RCNN0, fold7RCNN0, fold9RCNN0] final_TTA_ensemble = run_ensemble(list_of_dfs, metadata, adjust_score=False) final_TTA_ensemble[\"adjustedScore\"]", "def run_ensemble(list_of_dfs, metadata, adjust_score=True): list_of_pids = [] list_of_ensemble_bboxes = []", "fold2_nom = \"fold{}_{}\".format(2, imsizes[2]) fold3_nom = \"fold{}_{}\".format(3, imsizes[3]) fold4_nom =", "= ensemble_bbox_df.score * ensemble_bbox_df.votes return ensemble_bbox_df imsizes = [224, 256,", "def flip_box(box): \"\"\" box (list, length 4): [x1, y1, w,", "\"x\", \"y\", \"w\", \"h\", \"score\", \"votes\", \"adjustedScore\"]] final_TTA_ensemble.to_csv(os.path.join(WDIR, \"../../SimpleDCNPredictions.csv\"), index=False)", "results_df[[\"patientId\", \"score\", \"x\", \"y\", \"w\", \"h\", \"bbox\", \"view\"]] with open(MAPPINGS_PATH)", "test_set, suffix): filepath = os.path.join(det_folder, test_set, \"results/detections_{}_results_{}.json\".format(test_set, suffix)) with open(filepath)", "get_results(det_folder, test_set, suffix): filepath = os.path.join(det_folder, test_set, \"results/detections_{}_results_{}.json\".format(test_set, suffix)) with", "list_of_image_ids.append(mapping[coco_img_file]) list_of_scores.append(res[\"score\"]) list_of_bboxes.append(res[\"bbox\"]) if flip: list_of_bboxes = [flip_box(_) for _", "RCNN0_DETS_DIR WDIR = os.path.dirname(os.path.abspath(__file__)) def get_results(det_folder, test_set, suffix): filepath =", "# Top left corner of flipped box is: newTopLeft =", "= convert_dict_to_df(tmp_results, flip_mapping, metadata, test_set=test_set, flip=True, threshold=0.01) else: tmp_df =", "test_image_set, RCNN0_DETS_DIR.format(fold7_nom)), metadata) fold9RCNN0 = run_ensemble(get_TTA_results(\"fold9_512\", test_image_set, RCNN0_DETS_DIR.format(fold9_nom)), metadata) list_of_dfs", "def convert_dict_to_df(results, mapping, metadata, test_set, flip=False, threshold=0.): list_of_image_ids = []", "results_df = results_df.sort_values([\"patientId\", \"score\"], ascending=False) results_df = results_df[results_df.score >= threshold]", "metadata, test_set=test_set, flip=True, threshold=0.01) else: tmp_df = convert_dict_to_df(tmp_results, mapping, metadata,", "list_of_new_pids.append(list_of_pids[i]) list_of_bboxes.append(bbox) ensemble_bbox_df = pd.DataFrame({\"patientId\": list_of_new_pids, \"x\": [box[0] for box", "list_of_bboxes], \"bbox\": list_of_bboxes}) results_df = results_df.sort_values([\"patientId\", \"score\"], ascending=False) results_df =", "test_image_set, MAIN_DIR): TTAs = [] for test_set in [test_image_set, \"{}_flip\".format(test_image_set)]:", "= json.load(f) metadata = pd.read_csv(METADATA_PATH) def get_TTA_results(fold_imsize, test_image_set, MAIN_DIR): TTAs", "= run_ensemble(get_TTA_results(\"fold7_448\", test_image_set, RCNN0_DETS_DIR.format(fold7_nom)), metadata) fold9RCNN0 = run_ensemble(get_TTA_results(\"fold9_512\", test_image_set, RCNN0_DETS_DIR.format(fold9_nom)),", "suffix=suffix) if re.search(\"_flip\", test_set): tmp_df = convert_dict_to_df(tmp_results, flip_mapping, metadata, test_set=test_set,", "in list_of_bboxes], \"score\": [box[5] for box in list_of_bboxes], \"votes\": [box[-1]", "= os.path.dirname(os.path.abspath(__file__)) def get_results(det_folder, test_set, suffix): filepath = os.path.join(det_folder, test_set,", "ensemble_bbox_df imsizes = [224, 256, 288, 320, 352, 384, 416,", "open(filepath) as f: return json.load(f) def flip_box(box): \"\"\" box (list,", "y1) # Top left corner of flipped box is: newTopLeft", "\"DetectionEnsemble.py\")) def run_ensemble(list_of_dfs, metadata, adjust_score=True): list_of_pids = [] list_of_ensemble_bboxes =", "[] for pid in np.unique(metadata.patientId): list_of_tmp_dfs = [] list_of_detections =", "box in list_of_bboxes], \"votes\": [box[-1] for box in list_of_bboxes], \"bbox\":", "run_ensemble(get_TTA_results(\"fold3_320\", test_image_set, RCNN0_DETS_DIR.format(fold3_nom)), metadata) fold5RCNN0 = run_ensemble(get_TTA_results(\"fold5_384\", test_image_set, RCNN0_DETS_DIR.format(fold5_nom)), metadata)", "right corner of prediction x1 = box[0] y1 = box[1]", "for box in list_of_bboxes], \"bbox\": list_of_bboxes}) results_df = results_df.sort_values([\"patientId\", \"score\"],", "for i, ensemble_bboxes in enumerate(list_of_ensemble_bboxes): for bbox in ensemble_bboxes: list_of_new_pids.append(list_of_pids[i])", "fold7RCNN0, fold9RCNN0] final_TTA_ensemble = run_ensemble(list_of_dfs, metadata, adjust_score=False) final_TTA_ensemble[\"adjustedScore\"] = final_TTA_ensemble.score", "as f: return json.load(f) def flip_box(box): \"\"\" box (list, length", "fold3_nom = \"fold{}_{}\".format(3, imsizes[3]) fold4_nom = \"fold{}_{}\".format(4, imsizes[4]) fold5_nom =", "test_image_set, RCNN0_DETS_DIR.format(fold5_nom)), metadata) fold7RCNN0 = run_ensemble(get_TTA_results(\"fold7_448\", test_image_set, RCNN0_DETS_DIR.format(fold7_nom)), metadata) fold9RCNN0", "\"y\": [box[1] for box in list_of_bboxes], \"w\": [box[2] for box", "return results_df[[\"patientId\", \"score\", \"x\", \"y\", \"w\", \"h\", \"bbox\", \"view\"]] with", "448, 480, 512] fold0_nom = \"fold{}_{}\".format(0, imsizes[0]) fold1_nom = \"fold{}_{}\".format(1,", "[box[0] for box in list_of_bboxes], \"y\": [box[1] for box in", "pd.DataFrame({\"patientId\": list_of_new_pids, \"x\": [box[0] for box in list_of_bboxes], \"y\": [box[1]", "for res in results: coco_image_id = res[\"image_id\"] coco_img_file = \"COCO_{}_{}.png\".format(test_set,", "[x1, y1, w, h] \"\"\" # Get top right corner", "for box in list_of_bboxes], \"score\": [box[5] for box in list_of_bboxes],", "list_of_scores = [] list_of_bboxes = [] for res in results:", "open(MAPPINGS_PATH.replace(test_image_set, \"{}_flip\".format(test_image_set))) as f: flip_mapping = json.load(f) metadata = pd.read_csv(METADATA_PATH)", "def get_TTA_results(fold_imsize, test_image_set, MAIN_DIR): TTAs = [] for test_set in", "\"scale120\"]: tmp_results = get_results(os.path.join(MAIN_DIR, \"peepin_{}\".format(fold_imsize, fold_imsize)), test_set=test_set, suffix=suffix) if re.search(\"_flip\",", "in list_of_bboxes], \"votes\": [box[-1] for box in list_of_bboxes], \"bbox\": list_of_bboxes})", "i, ensemble_bboxes in enumerate(list_of_ensemble_bboxes): for bbox in ensemble_bboxes: list_of_new_pids.append(list_of_pids[i]) list_of_bboxes.append(bbox)", "list_of_ensemble_bboxes = [] for pid in np.unique(metadata.patientId): list_of_tmp_dfs = []", "fold5_nom = \"fold{}_{}\".format(5, imsizes[5]) fold6_nom = \"fold{}_{}\".format(6, imsizes[6]) fold7_nom =", "adjust_score: ensemble_bbox_df[\"score\"] = ensemble_bbox_df.score * ensemble_bbox_df.votes return ensemble_bbox_df imsizes =", "= [] for i, ensemble_bboxes in enumerate(list_of_ensemble_bboxes): for bbox in", "for df_index, each_df in enumerate(list_of_dfs): tmp_df = each_df[each_df.patientId == pid]", "list_of_image_ids], \"score\": list_of_scores, \"x\": [box[0] for box in list_of_bboxes], \"y\":", "bbox.append(row.score) list_of_bboxes.append(bbox) list_of_detections.append(list_of_bboxes) from src.infer.DetectionEnsemble import GeneralEnsemble list_of_ensemble_bboxes.append(GeneralEnsemble(list_of_detections, iou_thresh=0.4)) list_of_pids.append(pid)", "= run_ensemble(get_TTA_results(\"fold5_384\", test_image_set, RCNN0_DETS_DIR.format(fold5_nom)), metadata) fold7RCNN0 = run_ensemble(get_TTA_results(\"fold7_448\", test_image_set, RCNN0_DETS_DIR.format(fold7_nom)),", "length 4): [x1, y1, w, h] \"\"\" # Get top", "in tmp_df.iterrows(): bbox = row.bbox bbox.append(1) bbox.append(row.score) list_of_bboxes.append(bbox) list_of_detections.append(list_of_bboxes) from", "src.infer.DetectionEnsemble import GeneralEnsemble list_of_ensemble_bboxes.append(GeneralEnsemble(list_of_detections, iou_thresh=0.4)) list_of_pids.append(pid) # Create new DataFrame", "416, 448, 480, 512] fold0_nom = \"fold{}_{}\".format(0, imsizes[0]) fold1_nom =", "metadata, adjust_score=True): list_of_pids = [] list_of_ensemble_bboxes = [] for pid", "= [] for rownum, row in tmp_df.iterrows(): bbox = row.bbox", "list_of_bboxes], \"h\": [box[3] for box in list_of_bboxes], \"bbox\": list_of_bboxes}) results_df", "newTopLeft[1], w, h] def convert_dict_to_df(results, mapping, metadata, test_set, flip=False, threshold=0.):", "list_of_bboxes = [flip_box(_) for _ in list_of_bboxes] results_df = pd.DataFrame({\"patientId\":", "box in list_of_bboxes], \"h\": [box[3] for box in list_of_bboxes], \"score\":", "for box in list_of_bboxes], \"votes\": [box[-1] for box in list_of_bboxes],", "test_set=test_set, flip=False, threshold=0.01) TTAs.append(tmp_df) return TTAs execfile(os.path.join(WDIR, \"DetectionEnsemble.py\")) def run_ensemble(list_of_dfs,", "(list, length 4): [x1, y1, w, h] \"\"\" # Get", "pd.read_csv(METADATA_PATH) def get_TTA_results(fold_imsize, test_image_set, MAIN_DIR): TTAs = [] for test_set", "new DataFrame list_of_new_pids = [] list_of_bboxes = [] for i,", "threshold=0.01) TTAs.append(tmp_df) return TTAs execfile(os.path.join(WDIR, \"DetectionEnsemble.py\")) def run_ensemble(list_of_dfs, metadata, adjust_score=True):", "\"fold{}_{}\".format(3, imsizes[3]) fold4_nom = \"fold{}_{}\".format(4, imsizes[4]) fold5_nom = \"fold{}_{}\".format(5, imsizes[5])", "\"y\", \"w\", \"h\", \"bbox\", \"view\"]] with open(MAPPINGS_PATH) as f: mapping", "w, h] \"\"\" # Get top right corner of prediction", "import os import re import numpy as np import pandas", "# Get top right corner of prediction x1 = box[0]", "import GeneralEnsemble list_of_ensemble_bboxes.append(GeneralEnsemble(list_of_detections, iou_thresh=0.4)) list_of_pids.append(pid) # Create new DataFrame list_of_new_pids", "return ensemble_bbox_df imsizes = [224, 256, 288, 320, 352, 384,", "ensemble_bbox_df[\"score\"] = ensemble_bbox_df.score * ensemble_bbox_df.votes return ensemble_bbox_df imsizes = [224,", "= box[3] topRight = (x1 + w, y1) # Top", "\"scale080\", \"scale120\"]: tmp_results = get_results(os.path.join(MAIN_DIR, \"peepin_{}\".format(fold_imsize, fold_imsize)), test_set=test_set, suffix=suffix) if", "h] \"\"\" # Get top right corner of prediction x1", "[box[3] for box in list_of_bboxes], \"score\": [box[5] for box in", "[224, 256, 288, 320, 352, 384, 416, 448, 480, 512]", "if flip: list_of_bboxes = [flip_box(_) for _ in list_of_bboxes] results_df", "in list_of_bboxes], \"bbox\": list_of_bboxes}) results_df = results_df.sort_values([\"patientId\", \"score\"], ascending=False) results_df", "imsizes[1]) fold2_nom = \"fold{}_{}\".format(2, imsizes[2]) fold3_nom = \"fold{}_{}\".format(3, imsizes[3]) fold4_nom", "in list_of_bboxes], \"h\": [box[3] for box in list_of_bboxes], \"bbox\": list_of_bboxes})", "bbox = row.bbox bbox.append(1) bbox.append(row.score) list_of_bboxes.append(bbox) list_of_detections.append(list_of_bboxes) from src.infer.DetectionEnsemble import", "ensemble_bbox_df.score * ensemble_bbox_df.votes return ensemble_bbox_df imsizes = [224, 256, 288,", "\"fold{}_{}\".format(5, imsizes[5]) fold6_nom = \"fold{}_{}\".format(6, imsizes[6]) fold7_nom = \"fold{}_{}\".format(7, imsizes[7])", "Create new DataFrame list_of_new_pids = [] list_of_bboxes = [] for", "list_of_bboxes}) results_df = results_df.sort_values([\"patientId\", \"score\"], ascending=False) results_df = results_df[results_df.score >=", "threshold] results_df = results_df.merge(metadata, on=\"patientId\", how=\"left\") return results_df[[\"patientId\", \"score\", \"x\",", "np.unique(metadata.patientId): list_of_tmp_dfs = [] list_of_detections = [] view = metadata[metadata.patientId", "np import pandas as pd from src.infer.ExtractDeformableTTA import MAPPINGS_PATH, test_image_set,", "= [] list_of_bboxes = [] for i, ensemble_bboxes in enumerate(list_of_ensemble_bboxes):", "imsizes[9]) fold1RCNN0 = run_ensemble(get_TTA_results(\"fold1_256\", test_image_set, RCNN0_DETS_DIR.format(fold1_nom)), metadata) fold3RCNN0 = run_ensemble(get_TTA_results(\"fold3_320\",", "= [] list_of_bboxes = [] for res in results: coco_image_id", "os.path.dirname(os.path.abspath(__file__)) def get_results(det_folder, test_set, suffix): filepath = os.path.join(det_folder, test_set, \"results/detections_{}_results_{}.json\".format(test_set,", "= (x1 + w, y1) # Top left corner of", "bbox in ensemble_bboxes: list_of_new_pids.append(list_of_pids[i]) list_of_bboxes.append(bbox) ensemble_bbox_df = pd.DataFrame({\"patientId\": list_of_new_pids, \"x\":", "list_of_bboxes] results_df = pd.DataFrame({\"patientId\": [pid.split(\".\")[0] for pid in list_of_image_ids], \"score\":", "\"bbox\", \"view\"]] with open(MAPPINGS_PATH) as f: mapping = json.load(f) with", "re.search(\"_flip\", test_set): tmp_df = convert_dict_to_df(tmp_results, flip_mapping, metadata, test_set=test_set, flip=True, threshold=0.01)", "filepath = os.path.join(det_folder, test_set, \"results/detections_{}_results_{}.json\".format(test_set, suffix)) with open(filepath) as f:", "flipped box is: newTopLeft = (1024. - topRight[0], topRight[1]) return", "RCNN0_DETS_DIR.format(fold5_nom)), metadata) fold7RCNN0 = run_ensemble(get_TTA_results(\"fold7_448\", test_image_set, RCNN0_DETS_DIR.format(fold7_nom)), metadata) fold9RCNN0 =", "box (list, length 4): [x1, y1, w, h] \"\"\" #", "json import os import re import numpy as np import", "for box in list_of_bboxes], \"bbox\": list_of_bboxes}) if adjust_score: ensemble_bbox_df[\"score\"] =", "if adjust_score: ensemble_bbox_df[\"score\"] = ensemble_bbox_df.score * ensemble_bbox_df.votes return ensemble_bbox_df imsizes", "metadata) fold5RCNN0 = run_ensemble(get_TTA_results(\"fold5_384\", test_image_set, RCNN0_DETS_DIR.format(fold5_nom)), metadata) fold7RCNN0 = run_ensemble(get_TTA_results(\"fold7_448\",", "test_image_set, RCNN0_DETS_DIR.format(fold9_nom)), metadata) list_of_dfs = [fold1RCNN0, fold3RCNN0, fold5RCNN0, fold7RCNN0, fold9RCNN0]", "as f: mapping = json.load(f) with open(MAPPINGS_PATH.replace(test_image_set, \"{}_flip\".format(test_image_set))) as f:", "each_df in enumerate(list_of_dfs): tmp_df = each_df[each_df.patientId == pid] list_of_bboxes =", "list_of_pids = [] list_of_ensemble_bboxes = [] for pid in np.unique(metadata.patientId):", "list_of_image_ids = [] list_of_scores = [] list_of_bboxes = [] for", "run_ensemble(list_of_dfs, metadata, adjust_score=False) final_TTA_ensemble[\"adjustedScore\"] = final_TTA_ensemble.score * final_TTA_ensemble.votes final_TTA_ensemble =", "res in results: coco_image_id = res[\"image_id\"] coco_img_file = \"COCO_{}_{}.png\".format(test_set, str(coco_image_id).zfill(12))", "json.load(f) def flip_box(box): \"\"\" box (list, length 4): [x1, y1,", "= \"fold{}_{}\".format(9, imsizes[9]) fold1RCNN0 = run_ensemble(get_TTA_results(\"fold1_256\", test_image_set, RCNN0_DETS_DIR.format(fold1_nom)), metadata) fold3RCNN0", "final_TTA_ensemble.score * final_TTA_ensemble.votes final_TTA_ensemble = final_TTA_ensemble[[\"patientId\", \"x\", \"y\", \"w\", \"h\",", "fold_imsize)), test_set=test_set, suffix=suffix) if re.search(\"_flip\", test_set): tmp_df = convert_dict_to_df(tmp_results, flip_mapping,", "in list_of_bboxes], \"y\": [box[1] for box in list_of_bboxes], \"w\": [box[2]", "== pid] list_of_bboxes = [] for rownum, row in tmp_df.iterrows():", "imsizes[5]) fold6_nom = \"fold{}_{}\".format(6, imsizes[6]) fold7_nom = \"fold{}_{}\".format(7, imsizes[7]) fold8_nom", "= \"COCO_{}_{}.png\".format(test_set, str(coco_image_id).zfill(12)) list_of_image_ids.append(mapping[coco_img_file]) list_of_scores.append(res[\"score\"]) list_of_bboxes.append(res[\"bbox\"]) if flip: list_of_bboxes =", "[] list_of_ensemble_bboxes = [] for pid in np.unique(metadata.patientId): list_of_tmp_dfs =", "= [flip_box(_) for _ in list_of_bboxes] results_df = pd.DataFrame({\"patientId\": [pid.split(\".\")[0]", "in list_of_bboxes], \"bbox\": list_of_bboxes}) if adjust_score: ensemble_bbox_df[\"score\"] = ensemble_bbox_df.score *", "Top left corner of flipped box is: newTopLeft = (1024.", "\"fold{}_{}\".format(2, imsizes[2]) fold3_nom = \"fold{}_{}\".format(3, imsizes[3]) fold4_nom = \"fold{}_{}\".format(4, imsizes[4])", "top right corner of prediction x1 = box[0] y1 =", "\"COCO_{}_{}.png\".format(test_set, str(coco_image_id).zfill(12)) list_of_image_ids.append(mapping[coco_img_file]) list_of_scores.append(res[\"score\"]) list_of_bboxes.append(res[\"bbox\"]) if flip: list_of_bboxes = [flip_box(_)", "list_of_bboxes], \"w\": [box[2] for box in list_of_bboxes], \"h\": [box[3] for", "imsizes[8]) fold9_nom = \"fold{}_{}\".format(9, imsizes[9]) fold1RCNN0 = run_ensemble(get_TTA_results(\"fold1_256\", test_image_set, RCNN0_DETS_DIR.format(fold1_nom)),", "test_set): tmp_df = convert_dict_to_df(tmp_results, flip_mapping, metadata, test_set=test_set, flip=True, threshold=0.01) else:", "RCNN0_DETS_DIR.format(fold1_nom)), metadata) fold3RCNN0 = run_ensemble(get_TTA_results(\"fold3_320\", test_image_set, RCNN0_DETS_DIR.format(fold3_nom)), metadata) fold5RCNN0 =", "= [] for res in results: coco_image_id = res[\"image_id\"] coco_img_file", "from src.infer.DetectionEnsemble import GeneralEnsemble list_of_ensemble_bboxes.append(GeneralEnsemble(list_of_detections, iou_thresh=0.4)) list_of_pids.append(pid) # Create new", "x1 = box[0] y1 = box[1] w = box[2] h", "w = box[2] h = box[3] topRight = (x1 +", "list_of_new_pids, \"x\": [box[0] for box in list_of_bboxes], \"y\": [box[1] for", "\"\"\" # Get top right corner of prediction x1 =", "w, h] def convert_dict_to_df(results, mapping, metadata, test_set, flip=False, threshold=0.): list_of_image_ids", "test_set, flip=False, threshold=0.): list_of_image_ids = [] list_of_scores = [] list_of_bboxes", "mapping, metadata, test_set, flip=False, threshold=0.): list_of_image_ids = [] list_of_scores =", "how=\"left\") return results_df[[\"patientId\", \"score\", \"x\", \"y\", \"w\", \"h\", \"bbox\", \"view\"]]", "\"score\": list_of_scores, \"x\": [box[0] for box in list_of_bboxes], \"y\": [box[1]", "imsizes = [224, 256, 288, 320, 352, 384, 416, 448,", "\"{}_flip\".format(test_image_set))) as f: flip_mapping = json.load(f) metadata = pd.read_csv(METADATA_PATH) def", "TTAs = [] for test_set in [test_image_set, \"{}_flip\".format(test_image_set)]: for suffix", "\"peepin_{}\".format(fold_imsize, fold_imsize)), test_set=test_set, suffix=suffix) if re.search(\"_flip\", test_set): tmp_df = convert_dict_to_df(tmp_results,", "pid in np.unique(metadata.patientId): list_of_tmp_dfs = [] list_of_detections = [] view", "\"h\": [box[3] for box in list_of_bboxes], \"score\": [box[5] for box", "fold9RCNN0 = run_ensemble(get_TTA_results(\"fold9_512\", test_image_set, RCNN0_DETS_DIR.format(fold9_nom)), metadata) list_of_dfs = [fold1RCNN0, fold3RCNN0,", "for pid in list_of_image_ids], \"score\": list_of_scores, \"x\": [box[0] for box", "in list_of_bboxes], \"w\": [box[2] for box in list_of_bboxes], \"h\": [box[3]", "box[2] h = box[3] topRight = (x1 + w, y1)", "iou_thresh=0.4)) list_of_pids.append(pid) # Create new DataFrame list_of_new_pids = [] list_of_bboxes", "box in list_of_bboxes], \"bbox\": list_of_bboxes}) if adjust_score: ensemble_bbox_df[\"score\"] = ensemble_bbox_df.score", "df_index, each_df in enumerate(list_of_dfs): tmp_df = each_df[each_df.patientId == pid] list_of_bboxes", "= \"fold{}_{}\".format(0, imsizes[0]) fold1_nom = \"fold{}_{}\".format(1, imsizes[1]) fold2_nom = \"fold{}_{}\".format(2,", "= (1024. - topRight[0], topRight[1]) return [newTopLeft[0], newTopLeft[1], w, h]", "on=\"patientId\", how=\"left\") return results_df[[\"patientId\", \"score\", \"x\", \"y\", \"w\", \"h\", \"bbox\",", "for box in list_of_bboxes], \"h\": [box[3] for box in list_of_bboxes],", "box[3] topRight = (x1 + w, y1) # Top left", "coco_image_id = res[\"image_id\"] coco_img_file = \"COCO_{}_{}.png\".format(test_set, str(coco_image_id).zfill(12)) list_of_image_ids.append(mapping[coco_img_file]) list_of_scores.append(res[\"score\"]) list_of_bboxes.append(res[\"bbox\"])", "= row.bbox bbox.append(1) bbox.append(row.score) list_of_bboxes.append(bbox) list_of_detections.append(list_of_bboxes) from src.infer.DetectionEnsemble import GeneralEnsemble", "metadata) fold7RCNN0 = run_ensemble(get_TTA_results(\"fold7_448\", test_image_set, RCNN0_DETS_DIR.format(fold7_nom)), metadata) fold9RCNN0 = run_ensemble(get_TTA_results(\"fold9_512\",", "is: newTopLeft = (1024. - topRight[0], topRight[1]) return [newTopLeft[0], newTopLeft[1],", "fold8_nom = \"fold{}_{}\".format(8, imsizes[8]) fold9_nom = \"fold{}_{}\".format(9, imsizes[9]) fold1RCNN0 =", "from src.infer.ExtractDeformableTTA import MAPPINGS_PATH, test_image_set, METADATA_PATH, RCNN0_DETS_DIR WDIR = os.path.dirname(os.path.abspath(__file__))", "for bbox in ensemble_bboxes: list_of_new_pids.append(list_of_pids[i]) list_of_bboxes.append(bbox) ensemble_bbox_df = pd.DataFrame({\"patientId\": list_of_new_pids,", "TTAs execfile(os.path.join(WDIR, \"DetectionEnsemble.py\")) def run_ensemble(list_of_dfs, metadata, adjust_score=True): list_of_pids = []", "fold0_nom = \"fold{}_{}\".format(0, imsizes[0]) fold1_nom = \"fold{}_{}\".format(1, imsizes[1]) fold2_nom =", "\"w\": [box[2] for box in list_of_bboxes], \"h\": [box[3] for box", "list_of_scores.append(res[\"score\"]) list_of_bboxes.append(res[\"bbox\"]) if flip: list_of_bboxes = [flip_box(_) for _ in", "384, 416, 448, 480, 512] fold0_nom = \"fold{}_{}\".format(0, imsizes[0]) fold1_nom", "\"fold{}_{}\".format(4, imsizes[4]) fold5_nom = \"fold{}_{}\".format(5, imsizes[5]) fold6_nom = \"fold{}_{}\".format(6, imsizes[6])", "newTopLeft = (1024. - topRight[0], topRight[1]) return [newTopLeft[0], newTopLeft[1], w,", "tmp_df = convert_dict_to_df(tmp_results, flip_mapping, metadata, test_set=test_set, flip=True, threshold=0.01) else: tmp_df", "return TTAs execfile(os.path.join(WDIR, \"DetectionEnsemble.py\")) def run_ensemble(list_of_dfs, metadata, adjust_score=True): list_of_pids =", "execfile(os.path.join(WDIR, \"DetectionEnsemble.py\")) def run_ensemble(list_of_dfs, metadata, adjust_score=True): list_of_pids = [] list_of_ensemble_bboxes", "= \"fold{}_{}\".format(6, imsizes[6]) fold7_nom = \"fold{}_{}\".format(7, imsizes[7]) fold8_nom = \"fold{}_{}\".format(8,", "[] for i, ensemble_bboxes in enumerate(list_of_ensemble_bboxes): for bbox in ensemble_bboxes:", "flip=True, threshold=0.01) else: tmp_df = convert_dict_to_df(tmp_results, mapping, metadata, test_set=test_set, flip=False,", "= pd.read_csv(METADATA_PATH) def get_TTA_results(fold_imsize, test_image_set, MAIN_DIR): TTAs = [] for", "ensemble_bboxes: list_of_new_pids.append(list_of_pids[i]) list_of_bboxes.append(bbox) ensemble_bbox_df = pd.DataFrame({\"patientId\": list_of_new_pids, \"x\": [box[0] for", "288, 320, 352, 384, 416, 448, 480, 512] fold0_nom =", "= get_results(os.path.join(MAIN_DIR, \"peepin_{}\".format(fold_imsize, fold_imsize)), test_set=test_set, suffix=suffix) if re.search(\"_flip\", test_set): tmp_df", "results_df = results_df.merge(metadata, on=\"patientId\", how=\"left\") return results_df[[\"patientId\", \"score\", \"x\", \"y\",", "= final_TTA_ensemble[[\"patientId\", \"x\", \"y\", \"w\", \"h\", \"score\", \"votes\", \"adjustedScore\"]] final_TTA_ensemble.to_csv(os.path.join(WDIR,", "flip=False, threshold=0.): list_of_image_ids = [] list_of_scores = [] list_of_bboxes =", "(x1 + w, y1) # Top left corner of flipped", "rownum, row in tmp_df.iterrows(): bbox = row.bbox bbox.append(1) bbox.append(row.score) list_of_bboxes.append(bbox)", "list_of_bboxes}) if adjust_score: ensemble_bbox_df[\"score\"] = ensemble_bbox_df.score * ensemble_bbox_df.votes return ensemble_bbox_df", "test_set=test_set, flip=True, threshold=0.01) else: tmp_df = convert_dict_to_df(tmp_results, mapping, metadata, test_set=test_set,", "fold5RCNN0 = run_ensemble(get_TTA_results(\"fold5_384\", test_image_set, RCNN0_DETS_DIR.format(fold5_nom)), metadata) fold7RCNN0 = run_ensemble(get_TTA_results(\"fold7_448\", test_image_set,", "results_df.sort_values([\"patientId\", \"score\"], ascending=False) results_df = results_df[results_df.score >= threshold] results_df =", "= box[2] h = box[3] topRight = (x1 + w,", "of prediction x1 = box[0] y1 = box[1] w =", "for box in list_of_bboxes], \"w\": [box[2] for box in list_of_bboxes],", "WDIR = os.path.dirname(os.path.abspath(__file__)) def get_results(det_folder, test_set, suffix): filepath = os.path.join(det_folder,", "y1 = box[1] w = box[2] h = box[3] topRight", "= [] list_of_detections = [] view = metadata[metadata.patientId == pid][\"view\"].iloc[0]", "ascending=False) results_df = results_df[results_df.score >= threshold] results_df = results_df.merge(metadata, on=\"patientId\",", "bbox.append(1) bbox.append(row.score) list_of_bboxes.append(bbox) list_of_detections.append(list_of_bboxes) from src.infer.DetectionEnsemble import GeneralEnsemble list_of_ensemble_bboxes.append(GeneralEnsemble(list_of_detections, iou_thresh=0.4))", "metadata[metadata.patientId == pid][\"view\"].iloc[0] for df_index, each_df in enumerate(list_of_dfs): tmp_df =", "= [224, 256, 288, 320, 352, 384, 416, 448, 480,", "[] for rownum, row in tmp_df.iterrows(): bbox = row.bbox bbox.append(1)", "tmp_df = convert_dict_to_df(tmp_results, mapping, metadata, test_set=test_set, flip=False, threshold=0.01) TTAs.append(tmp_df) return", "MAPPINGS_PATH, test_image_set, METADATA_PATH, RCNN0_DETS_DIR WDIR = os.path.dirname(os.path.abspath(__file__)) def get_results(det_folder, test_set,", "MAIN_DIR): TTAs = [] for test_set in [test_image_set, \"{}_flip\".format(test_image_set)]: for", "fold5RCNN0, fold7RCNN0, fold9RCNN0] final_TTA_ensemble = run_ensemble(list_of_dfs, metadata, adjust_score=False) final_TTA_ensemble[\"adjustedScore\"] =", "\"\"\" box (list, length 4): [x1, y1, w, h] \"\"\"", "open(MAPPINGS_PATH) as f: mapping = json.load(f) with open(MAPPINGS_PATH.replace(test_image_set, \"{}_flip\".format(test_image_set))) as", "box in list_of_bboxes], \"w\": [box[2] for box in list_of_bboxes], \"h\":", "in list_of_bboxes], \"h\": [box[3] for box in list_of_bboxes], \"score\": [box[5]", "f: mapping = json.load(f) with open(MAPPINGS_PATH.replace(test_image_set, \"{}_flip\".format(test_image_set))) as f: flip_mapping", "= \"fold{}_{}\".format(2, imsizes[2]) fold3_nom = \"fold{}_{}\".format(3, imsizes[3]) fold4_nom = \"fold{}_{}\".format(4,", "as pd from src.infer.ExtractDeformableTTA import MAPPINGS_PATH, test_image_set, METADATA_PATH, RCNN0_DETS_DIR WDIR", "[] for res in results: coco_image_id = res[\"image_id\"] coco_img_file =", "pid in list_of_image_ids], \"score\": list_of_scores, \"x\": [box[0] for box in", ">= threshold] results_df = results_df.merge(metadata, on=\"patientId\", how=\"left\") return results_df[[\"patientId\", \"score\",", "for _ in list_of_bboxes] results_df = pd.DataFrame({\"patientId\": [pid.split(\".\")[0] for pid", "pid] list_of_bboxes = [] for rownum, row in tmp_df.iterrows(): bbox", "as np import pandas as pd from src.infer.ExtractDeformableTTA import MAPPINGS_PATH,", "tmp_results = get_results(os.path.join(MAIN_DIR, \"peepin_{}\".format(fold_imsize, fold_imsize)), test_set=test_set, suffix=suffix) if re.search(\"_flip\", test_set):", "\"fold{}_{}\".format(0, imsizes[0]) fold1_nom = \"fold{}_{}\".format(1, imsizes[1]) fold2_nom = \"fold{}_{}\".format(2, imsizes[2])", "box is: newTopLeft = (1024. - topRight[0], topRight[1]) return [newTopLeft[0],", "def get_results(det_folder, test_set, suffix): filepath = os.path.join(det_folder, test_set, \"results/detections_{}_results_{}.json\".format(test_set, suffix))", "list_of_tmp_dfs = [] list_of_detections = [] view = metadata[metadata.patientId ==", "<reponame>RamsteinWR/PneumoniaRSNA1 import json import os import re import numpy as", "metadata) list_of_dfs = [fold1RCNN0, fold3RCNN0, fold5RCNN0, fold7RCNN0, fold9RCNN0] final_TTA_ensemble =", "256, 288, 320, 352, 384, 416, 448, 480, 512] fold0_nom", "box in list_of_bboxes], \"h\": [box[3] for box in list_of_bboxes], \"bbox\":", "* final_TTA_ensemble.votes final_TTA_ensemble = final_TTA_ensemble[[\"patientId\", \"x\", \"y\", \"w\", \"h\", \"score\",", "in [test_image_set, \"{}_flip\".format(test_image_set)]: for suffix in [\"original\", \"scale080\", \"scale120\"]: tmp_results", "else: tmp_df = convert_dict_to_df(tmp_results, mapping, metadata, test_set=test_set, flip=False, threshold=0.01) TTAs.append(tmp_df)", "320, 352, 384, 416, 448, 480, 512] fold0_nom = \"fold{}_{}\".format(0,", "= results_df[results_df.score >= threshold] results_df = results_df.merge(metadata, on=\"patientId\", how=\"left\") return", "y1, w, h] \"\"\" # Get top right corner of", "= json.load(f) with open(MAPPINGS_PATH.replace(test_image_set, \"{}_flip\".format(test_image_set))) as f: flip_mapping = json.load(f)", "pd.DataFrame({\"patientId\": [pid.split(\".\")[0] for pid in list_of_image_ids], \"score\": list_of_scores, \"x\": [box[0]", "h = box[3] topRight = (x1 + w, y1) #", "res[\"image_id\"] coco_img_file = \"COCO_{}_{}.png\".format(test_set, str(coco_image_id).zfill(12)) list_of_image_ids.append(mapping[coco_img_file]) list_of_scores.append(res[\"score\"]) list_of_bboxes.append(res[\"bbox\"]) if flip:", "in np.unique(metadata.patientId): list_of_tmp_dfs = [] list_of_detections = [] view =", "import numpy as np import pandas as pd from src.infer.ExtractDeformableTTA", "re import numpy as np import pandas as pd from", "[box[5] for box in list_of_bboxes], \"votes\": [box[-1] for box in", "mapping, metadata, test_set=test_set, flip=False, threshold=0.01) TTAs.append(tmp_df) return TTAs execfile(os.path.join(WDIR, \"DetectionEnsemble.py\"))", "flip: list_of_bboxes = [flip_box(_) for _ in list_of_bboxes] results_df =", "list_of_bboxes.append(bbox) ensemble_bbox_df = pd.DataFrame({\"patientId\": list_of_new_pids, \"x\": [box[0] for box in", "imsizes[3]) fold4_nom = \"fold{}_{}\".format(4, imsizes[4]) fold5_nom = \"fold{}_{}\".format(5, imsizes[5]) fold6_nom", "TTAs.append(tmp_df) return TTAs execfile(os.path.join(WDIR, \"DetectionEnsemble.py\")) def run_ensemble(list_of_dfs, metadata, adjust_score=True): list_of_pids", "# Create new DataFrame list_of_new_pids = [] list_of_bboxes = []", "pid][\"view\"].iloc[0] for df_index, each_df in enumerate(list_of_dfs): tmp_df = each_df[each_df.patientId ==", "h] def convert_dict_to_df(results, mapping, metadata, test_set, flip=False, threshold=0.): list_of_image_ids =", "= final_TTA_ensemble.score * final_TTA_ensemble.votes final_TTA_ensemble = final_TTA_ensemble[[\"patientId\", \"x\", \"y\", \"w\",", "final_TTA_ensemble[[\"patientId\", \"x\", \"y\", \"w\", \"h\", \"score\", \"votes\", \"adjustedScore\"]] final_TTA_ensemble.to_csv(os.path.join(WDIR, \"../../SimpleDCNPredictions.csv\"),", "get_results(os.path.join(MAIN_DIR, \"peepin_{}\".format(fold_imsize, fold_imsize)), test_set=test_set, suffix=suffix) if re.search(\"_flip\", test_set): tmp_df =", "json.load(f) with open(MAPPINGS_PATH.replace(test_image_set, \"{}_flip\".format(test_image_set))) as f: flip_mapping = json.load(f) metadata", "\"bbox\": list_of_bboxes}) if adjust_score: ensemble_bbox_df[\"score\"] = ensemble_bbox_df.score * ensemble_bbox_df.votes return", "import MAPPINGS_PATH, test_image_set, METADATA_PATH, RCNN0_DETS_DIR WDIR = os.path.dirname(os.path.abspath(__file__)) def get_results(det_folder,", "\"h\": [box[3] for box in list_of_bboxes], \"bbox\": list_of_bboxes}) results_df =", "= convert_dict_to_df(tmp_results, mapping, metadata, test_set=test_set, flip=False, threshold=0.01) TTAs.append(tmp_df) return TTAs", "flip=False, threshold=0.01) TTAs.append(tmp_df) return TTAs execfile(os.path.join(WDIR, \"DetectionEnsemble.py\")) def run_ensemble(list_of_dfs, metadata,", "adjust_score=False) final_TTA_ensemble[\"adjustedScore\"] = final_TTA_ensemble.score * final_TTA_ensemble.votes final_TTA_ensemble = final_TTA_ensemble[[\"patientId\", \"x\",", "fold7_nom = \"fold{}_{}\".format(7, imsizes[7]) fold8_nom = \"fold{}_{}\".format(8, imsizes[8]) fold9_nom =", "= each_df[each_df.patientId == pid] list_of_bboxes = [] for rownum, row", "[flip_box(_) for _ in list_of_bboxes] results_df = pd.DataFrame({\"patientId\": [pid.split(\".\")[0] for", "GeneralEnsemble list_of_ensemble_bboxes.append(GeneralEnsemble(list_of_detections, iou_thresh=0.4)) list_of_pids.append(pid) # Create new DataFrame list_of_new_pids =", "[] list_of_detections = [] view = metadata[metadata.patientId == pid][\"view\"].iloc[0] for", "for rownum, row in tmp_df.iterrows(): bbox = row.bbox bbox.append(1) bbox.append(row.score)", "topRight[1]) return [newTopLeft[0], newTopLeft[1], w, h] def convert_dict_to_df(results, mapping, metadata,", "* ensemble_bbox_df.votes return ensemble_bbox_df imsizes = [224, 256, 288, 320,", "= [fold1RCNN0, fold3RCNN0, fold5RCNN0, fold7RCNN0, fold9RCNN0] final_TTA_ensemble = run_ensemble(list_of_dfs, metadata,", "= run_ensemble(get_TTA_results(\"fold9_512\", test_image_set, RCNN0_DETS_DIR.format(fold9_nom)), metadata) list_of_dfs = [fold1RCNN0, fold3RCNN0, fold5RCNN0,", "\"view\"]] with open(MAPPINGS_PATH) as f: mapping = json.load(f) with open(MAPPINGS_PATH.replace(test_image_set,", "\"fold{}_{}\".format(8, imsizes[8]) fold9_nom = \"fold{}_{}\".format(9, imsizes[9]) fold1RCNN0 = run_ensemble(get_TTA_results(\"fold1_256\", test_image_set,", "\"results/detections_{}_results_{}.json\".format(test_set, suffix)) with open(filepath) as f: return json.load(f) def flip_box(box):", "box in list_of_bboxes], \"bbox\": list_of_bboxes}) results_df = results_df.sort_values([\"patientId\", \"score\"], ascending=False)", "[newTopLeft[0], newTopLeft[1], w, h] def convert_dict_to_df(results, mapping, metadata, test_set, flip=False,", "json.load(f) metadata = pd.read_csv(METADATA_PATH) def get_TTA_results(fold_imsize, test_image_set, MAIN_DIR): TTAs =", "metadata) fold3RCNN0 = run_ensemble(get_TTA_results(\"fold3_320\", test_image_set, RCNN0_DETS_DIR.format(fold3_nom)), metadata) fold5RCNN0 = run_ensemble(get_TTA_results(\"fold5_384\",", "\"h\", \"bbox\", \"view\"]] with open(MAPPINGS_PATH) as f: mapping = json.load(f)", "= run_ensemble(get_TTA_results(\"fold1_256\", test_image_set, RCNN0_DETS_DIR.format(fold1_nom)), metadata) fold3RCNN0 = run_ensemble(get_TTA_results(\"fold3_320\", test_image_set, RCNN0_DETS_DIR.format(fold3_nom)),", "fold6_nom = \"fold{}_{}\".format(6, imsizes[6]) fold7_nom = \"fold{}_{}\".format(7, imsizes[7]) fold8_nom =", "of flipped box is: newTopLeft = (1024. - topRight[0], topRight[1])", "= results_df.sort_values([\"patientId\", \"score\"], ascending=False) results_df = results_df[results_df.score >= threshold] results_df", "test_set, \"results/detections_{}_results_{}.json\".format(test_set, suffix)) with open(filepath) as f: return json.load(f) def", "test_image_set, RCNN0_DETS_DIR.format(fold1_nom)), metadata) fold3RCNN0 = run_ensemble(get_TTA_results(\"fold3_320\", test_image_set, RCNN0_DETS_DIR.format(fold3_nom)), metadata) fold5RCNN0", "run_ensemble(list_of_dfs, metadata, adjust_score=True): list_of_pids = [] list_of_ensemble_bboxes = [] for", "list_of_pids.append(pid) # Create new DataFrame list_of_new_pids = [] list_of_bboxes =", "\"score\": [box[5] for box in list_of_bboxes], \"votes\": [box[-1] for box", "for box in list_of_bboxes], \"y\": [box[1] for box in list_of_bboxes],", "suffix)) with open(filepath) as f: return json.load(f) def flip_box(box): \"\"\"", "fold9_nom = \"fold{}_{}\".format(9, imsizes[9]) fold1RCNN0 = run_ensemble(get_TTA_results(\"fold1_256\", test_image_set, RCNN0_DETS_DIR.format(fold1_nom)), metadata)", "enumerate(list_of_dfs): tmp_df = each_df[each_df.patientId == pid] list_of_bboxes = [] for", "for suffix in [\"original\", \"scale080\", \"scale120\"]: tmp_results = get_results(os.path.join(MAIN_DIR, \"peepin_{}\".format(fold_imsize,", "imsizes[2]) fold3_nom = \"fold{}_{}\".format(3, imsizes[3]) fold4_nom = \"fold{}_{}\".format(4, imsizes[4]) fold5_nom", "results: coco_image_id = res[\"image_id\"] coco_img_file = \"COCO_{}_{}.png\".format(test_set, str(coco_image_id).zfill(12)) list_of_image_ids.append(mapping[coco_img_file]) list_of_scores.append(res[\"score\"])", "in list_of_bboxes] results_df = pd.DataFrame({\"patientId\": [pid.split(\".\")[0] for pid in list_of_image_ids],", "str(coco_image_id).zfill(12)) list_of_image_ids.append(mapping[coco_img_file]) list_of_scores.append(res[\"score\"]) list_of_bboxes.append(res[\"bbox\"]) if flip: list_of_bboxes = [flip_box(_) for", "for test_set in [test_image_set, \"{}_flip\".format(test_image_set)]: for suffix in [\"original\", \"scale080\",", "list_of_bboxes = [] for res in results: coco_image_id = res[\"image_id\"]", "f: flip_mapping = json.load(f) metadata = pd.read_csv(METADATA_PATH) def get_TTA_results(fold_imsize, test_image_set,", "= results_df.merge(metadata, on=\"patientId\", how=\"left\") return results_df[[\"patientId\", \"score\", \"x\", \"y\", \"w\",", "import re import numpy as np import pandas as pd", "Get top right corner of prediction x1 = box[0] y1", "box in list_of_bboxes], \"y\": [box[1] for box in list_of_bboxes], \"w\":", "adjust_score=True): list_of_pids = [] list_of_ensemble_bboxes = [] for pid in", "in list_of_image_ids], \"score\": list_of_scores, \"x\": [box[0] for box in list_of_bboxes],", "list_of_ensemble_bboxes.append(GeneralEnsemble(list_of_detections, iou_thresh=0.4)) list_of_pids.append(pid) # Create new DataFrame list_of_new_pids = []", "mapping = json.load(f) with open(MAPPINGS_PATH.replace(test_image_set, \"{}_flip\".format(test_image_set))) as f: flip_mapping =", "in ensemble_bboxes: list_of_new_pids.append(list_of_pids[i]) list_of_bboxes.append(bbox) ensemble_bbox_df = pd.DataFrame({\"patientId\": list_of_new_pids, \"x\": [box[0]", "w, y1) # Top left corner of flipped box is:", "= \"fold{}_{}\".format(3, imsizes[3]) fold4_nom = \"fold{}_{}\".format(4, imsizes[4]) fold5_nom = \"fold{}_{}\".format(5,", "= [] for pid in np.unique(metadata.patientId): list_of_tmp_dfs = [] list_of_detections", "each_df[each_df.patientId == pid] list_of_bboxes = [] for rownum, row in", "metadata, test_set, flip=False, threshold=0.): list_of_image_ids = [] list_of_scores = []", "flip_box(box): \"\"\" box (list, length 4): [x1, y1, w, h]", "[] list_of_bboxes = [] for i, ensemble_bboxes in enumerate(list_of_ensemble_bboxes): for", "os.path.join(det_folder, test_set, \"results/detections_{}_results_{}.json\".format(test_set, suffix)) with open(filepath) as f: return json.load(f)", "[\"original\", \"scale080\", \"scale120\"]: tmp_results = get_results(os.path.join(MAIN_DIR, \"peepin_{}\".format(fold_imsize, fold_imsize)), test_set=test_set, suffix=suffix)", "corner of flipped box is: newTopLeft = (1024. - topRight[0],", "corner of prediction x1 = box[0] y1 = box[1] w", "return json.load(f) def flip_box(box): \"\"\" box (list, length 4): [x1,", "\"{}_flip\".format(test_image_set)]: for suffix in [\"original\", \"scale080\", \"scale120\"]: tmp_results = get_results(os.path.join(MAIN_DIR,", "import json import os import re import numpy as np", "run_ensemble(get_TTA_results(\"fold9_512\", test_image_set, RCNN0_DETS_DIR.format(fold9_nom)), metadata) list_of_dfs = [fold1RCNN0, fold3RCNN0, fold5RCNN0, fold7RCNN0,", "_ in list_of_bboxes] results_df = pd.DataFrame({\"patientId\": [pid.split(\".\")[0] for pid in", "results_df.merge(metadata, on=\"patientId\", how=\"left\") return results_df[[\"patientId\", \"score\", \"x\", \"y\", \"w\", \"h\",", "[box[1] for box in list_of_bboxes], \"w\": [box[2] for box in", "512] fold0_nom = \"fold{}_{}\".format(0, imsizes[0]) fold1_nom = \"fold{}_{}\".format(1, imsizes[1]) fold2_nom", "list_of_bboxes], \"h\": [box[3] for box in list_of_bboxes], \"score\": [box[5] for", "topRight = (x1 + w, y1) # Top left corner", "fold7RCNN0 = run_ensemble(get_TTA_results(\"fold7_448\", test_image_set, RCNN0_DETS_DIR.format(fold7_nom)), metadata) fold9RCNN0 = run_ensemble(get_TTA_results(\"fold9_512\", test_image_set,", "metadata, adjust_score=False) final_TTA_ensemble[\"adjustedScore\"] = final_TTA_ensemble.score * final_TTA_ensemble.votes final_TTA_ensemble = final_TTA_ensemble[[\"patientId\",", "METADATA_PATH, RCNN0_DETS_DIR WDIR = os.path.dirname(os.path.abspath(__file__)) def get_results(det_folder, test_set, suffix): filepath", "\"score\"], ascending=False) results_df = results_df[results_df.score >= threshold] results_df = results_df.merge(metadata,", "[box[2] for box in list_of_bboxes], \"h\": [box[3] for box in", "\"votes\": [box[-1] for box in list_of_bboxes], \"bbox\": list_of_bboxes}) if adjust_score:", "results_df = pd.DataFrame({\"patientId\": [pid.split(\".\")[0] for pid in list_of_image_ids], \"score\": list_of_scores,", "imsizes[6]) fold7_nom = \"fold{}_{}\".format(7, imsizes[7]) fold8_nom = \"fold{}_{}\".format(8, imsizes[8]) fold9_nom", "test_set in [test_image_set, \"{}_flip\".format(test_image_set)]: for suffix in [\"original\", \"scale080\", \"scale120\"]:", "metadata) fold9RCNN0 = run_ensemble(get_TTA_results(\"fold9_512\", test_image_set, RCNN0_DETS_DIR.format(fold9_nom)), metadata) list_of_dfs = [fold1RCNN0,", "480, 512] fold0_nom = \"fold{}_{}\".format(0, imsizes[0]) fold1_nom = \"fold{}_{}\".format(1, imsizes[1])", "fold1_nom = \"fold{}_{}\".format(1, imsizes[1]) fold2_nom = \"fold{}_{}\".format(2, imsizes[2]) fold3_nom =", "= run_ensemble(get_TTA_results(\"fold3_320\", test_image_set, RCNN0_DETS_DIR.format(fold3_nom)), metadata) fold5RCNN0 = run_ensemble(get_TTA_results(\"fold5_384\", test_image_set, RCNN0_DETS_DIR.format(fold5_nom)),", "DataFrame list_of_new_pids = [] list_of_bboxes = [] for i, ensemble_bboxes", "list_of_bboxes = [] for i, ensemble_bboxes in enumerate(list_of_ensemble_bboxes): for bbox", "[fold1RCNN0, fold3RCNN0, fold5RCNN0, fold7RCNN0, fold9RCNN0] final_TTA_ensemble = run_ensemble(list_of_dfs, metadata, adjust_score=False)", "suffix in [\"original\", \"scale080\", \"scale120\"]: tmp_results = get_results(os.path.join(MAIN_DIR, \"peepin_{}\".format(fold_imsize, fold_imsize)),", "RCNN0_DETS_DIR.format(fold9_nom)), metadata) list_of_dfs = [fold1RCNN0, fold3RCNN0, fold5RCNN0, fold7RCNN0, fold9RCNN0] final_TTA_ensemble", "= \"fold{}_{}\".format(7, imsizes[7]) fold8_nom = \"fold{}_{}\".format(8, imsizes[8]) fold9_nom = \"fold{}_{}\".format(9,", "= \"fold{}_{}\".format(8, imsizes[8]) fold9_nom = \"fold{}_{}\".format(9, imsizes[9]) fold1RCNN0 = run_ensemble(get_TTA_results(\"fold1_256\",", "list_of_detections.append(list_of_bboxes) from src.infer.DetectionEnsemble import GeneralEnsemble list_of_ensemble_bboxes.append(GeneralEnsemble(list_of_detections, iou_thresh=0.4)) list_of_pids.append(pid) # Create", "metadata, test_set=test_set, flip=False, threshold=0.01) TTAs.append(tmp_df) return TTAs execfile(os.path.join(WDIR, \"DetectionEnsemble.py\")) def", "src.infer.ExtractDeformableTTA import MAPPINGS_PATH, test_image_set, METADATA_PATH, RCNN0_DETS_DIR WDIR = os.path.dirname(os.path.abspath(__file__)) def", "== pid][\"view\"].iloc[0] for df_index, each_df in enumerate(list_of_dfs): tmp_df = each_df[each_df.patientId", "pd from src.infer.ExtractDeformableTTA import MAPPINGS_PATH, test_image_set, METADATA_PATH, RCNN0_DETS_DIR WDIR =", "[] list_of_scores = [] list_of_bboxes = [] for res in", "list_of_bboxes.append(bbox) list_of_detections.append(list_of_bboxes) from src.infer.DetectionEnsemble import GeneralEnsemble list_of_ensemble_bboxes.append(GeneralEnsemble(list_of_detections, iou_thresh=0.4)) list_of_pids.append(pid) #", "test_set=test_set, suffix=suffix) if re.search(\"_flip\", test_set): tmp_df = convert_dict_to_df(tmp_results, flip_mapping, metadata,", "imsizes[0]) fold1_nom = \"fold{}_{}\".format(1, imsizes[1]) fold2_nom = \"fold{}_{}\".format(2, imsizes[2]) fold3_nom", "list_of_dfs = [fold1RCNN0, fold3RCNN0, fold5RCNN0, fold7RCNN0, fold9RCNN0] final_TTA_ensemble = run_ensemble(list_of_dfs,", "metadata = pd.read_csv(METADATA_PATH) def get_TTA_results(fold_imsize, test_image_set, MAIN_DIR): TTAs = []", "352, 384, 416, 448, 480, 512] fold0_nom = \"fold{}_{}\".format(0, imsizes[0])", "row in tmp_df.iterrows(): bbox = row.bbox bbox.append(1) bbox.append(row.score) list_of_bboxes.append(bbox) list_of_detections.append(list_of_bboxes)", "f: return json.load(f) def flip_box(box): \"\"\" box (list, length 4):", "threshold=0.01) else: tmp_df = convert_dict_to_df(tmp_results, mapping, metadata, test_set=test_set, flip=False, threshold=0.01)", "\"bbox\": list_of_bboxes}) results_df = results_df.sort_values([\"patientId\", \"score\"], ascending=False) results_df = results_df[results_df.score", "= pd.DataFrame({\"patientId\": [pid.split(\".\")[0] for pid in list_of_image_ids], \"score\": list_of_scores, \"x\":", "imsizes[7]) fold8_nom = \"fold{}_{}\".format(8, imsizes[8]) fold9_nom = \"fold{}_{}\".format(9, imsizes[9]) fold1RCNN0", "\"fold{}_{}\".format(6, imsizes[6]) fold7_nom = \"fold{}_{}\".format(7, imsizes[7]) fold8_nom = \"fold{}_{}\".format(8, imsizes[8])", "flip_mapping = json.load(f) metadata = pd.read_csv(METADATA_PATH) def get_TTA_results(fold_imsize, test_image_set, MAIN_DIR):", "view = metadata[metadata.patientId == pid][\"view\"].iloc[0] for df_index, each_df in enumerate(list_of_dfs):", "list_of_bboxes.append(res[\"bbox\"]) if flip: list_of_bboxes = [flip_box(_) for _ in list_of_bboxes]", "suffix): filepath = os.path.join(det_folder, test_set, \"results/detections_{}_results_{}.json\".format(test_set, suffix)) with open(filepath) as", "= \"fold{}_{}\".format(5, imsizes[5]) fold6_nom = \"fold{}_{}\".format(6, imsizes[6]) fold7_nom = \"fold{}_{}\".format(7,", "box[0] y1 = box[1] w = box[2] h = box[3]", "RCNN0_DETS_DIR.format(fold7_nom)), metadata) fold9RCNN0 = run_ensemble(get_TTA_results(\"fold9_512\", test_image_set, RCNN0_DETS_DIR.format(fold9_nom)), metadata) list_of_dfs =", "left corner of flipped box is: newTopLeft = (1024. -", "box in list_of_bboxes], \"score\": [box[5] for box in list_of_bboxes], \"votes\":", "if re.search(\"_flip\", test_set): tmp_df = convert_dict_to_df(tmp_results, flip_mapping, metadata, test_set=test_set, flip=True,", "ensemble_bboxes in enumerate(list_of_ensemble_bboxes): for bbox in ensemble_bboxes: list_of_new_pids.append(list_of_pids[i]) list_of_bboxes.append(bbox) ensemble_bbox_df", "= box[1] w = box[2] h = box[3] topRight =", "list_of_bboxes], \"y\": [box[1] for box in list_of_bboxes], \"w\": [box[2] for", "test_image_set, RCNN0_DETS_DIR.format(fold3_nom)), metadata) fold5RCNN0 = run_ensemble(get_TTA_results(\"fold5_384\", test_image_set, RCNN0_DETS_DIR.format(fold5_nom)), metadata) fold7RCNN0", "with open(MAPPINGS_PATH.replace(test_image_set, \"{}_flip\".format(test_image_set))) as f: flip_mapping = json.load(f) metadata =", "ensemble_bbox_df = pd.DataFrame({\"patientId\": list_of_new_pids, \"x\": [box[0] for box in list_of_bboxes],", "+ w, y1) # Top left corner of flipped box", "numpy as np import pandas as pd from src.infer.ExtractDeformableTTA import", "= box[0] y1 = box[1] w = box[2] h =", "[test_image_set, \"{}_flip\".format(test_image_set)]: for suffix in [\"original\", \"scale080\", \"scale120\"]: tmp_results =", "\"fold{}_{}\".format(9, imsizes[9]) fold1RCNN0 = run_ensemble(get_TTA_results(\"fold1_256\", test_image_set, RCNN0_DETS_DIR.format(fold1_nom)), metadata) fold3RCNN0 =", "threshold=0.): list_of_image_ids = [] list_of_scores = [] list_of_bboxes = []", "list_of_bboxes], \"bbox\": list_of_bboxes}) if adjust_score: ensemble_bbox_df[\"score\"] = ensemble_bbox_df.score * ensemble_bbox_df.votes", "fold1RCNN0 = run_ensemble(get_TTA_results(\"fold1_256\", test_image_set, RCNN0_DETS_DIR.format(fold1_nom)), metadata) fold3RCNN0 = run_ensemble(get_TTA_results(\"fold3_320\", test_image_set,", "\"x\": [box[0] for box in list_of_bboxes], \"y\": [box[1] for box", "topRight[0], topRight[1]) return [newTopLeft[0], newTopLeft[1], w, h] def convert_dict_to_df(results, mapping,", "\"score\", \"x\", \"y\", \"w\", \"h\", \"bbox\", \"view\"]] with open(MAPPINGS_PATH) as", "run_ensemble(get_TTA_results(\"fold5_384\", test_image_set, RCNN0_DETS_DIR.format(fold5_nom)), metadata) fold7RCNN0 = run_ensemble(get_TTA_results(\"fold7_448\", test_image_set, RCNN0_DETS_DIR.format(fold7_nom)), metadata)", "in results: coco_image_id = res[\"image_id\"] coco_img_file = \"COCO_{}_{}.png\".format(test_set, str(coco_image_id).zfill(12)) list_of_image_ids.append(mapping[coco_img_file])", "for pid in np.unique(metadata.patientId): list_of_tmp_dfs = [] list_of_detections = []", "[] view = metadata[metadata.patientId == pid][\"view\"].iloc[0] for df_index, each_df in", "get_TTA_results(fold_imsize, test_image_set, MAIN_DIR): TTAs = [] for test_set in [test_image_set,", "= \"fold{}_{}\".format(1, imsizes[1]) fold2_nom = \"fold{}_{}\".format(2, imsizes[2]) fold3_nom = \"fold{}_{}\".format(3,", "list_of_bboxes], \"votes\": [box[-1] for box in list_of_bboxes], \"bbox\": list_of_bboxes}) if", "pandas as pd from src.infer.ExtractDeformableTTA import MAPPINGS_PATH, test_image_set, METADATA_PATH, RCNN0_DETS_DIR", "= run_ensemble(list_of_dfs, metadata, adjust_score=False) final_TTA_ensemble[\"adjustedScore\"] = final_TTA_ensemble.score * final_TTA_ensemble.votes final_TTA_ensemble", "row.bbox bbox.append(1) bbox.append(row.score) list_of_bboxes.append(bbox) list_of_detections.append(list_of_bboxes) from src.infer.DetectionEnsemble import GeneralEnsemble list_of_ensemble_bboxes.append(GeneralEnsemble(list_of_detections,", "prediction x1 = box[0] y1 = box[1] w = box[2]", "fold3RCNN0 = run_ensemble(get_TTA_results(\"fold3_320\", test_image_set, RCNN0_DETS_DIR.format(fold3_nom)), metadata) fold5RCNN0 = run_ensemble(get_TTA_results(\"fold5_384\", test_image_set,", "= os.path.join(det_folder, test_set, \"results/detections_{}_results_{}.json\".format(test_set, suffix)) with open(filepath) as f: return", "[pid.split(\".\")[0] for pid in list_of_image_ids], \"score\": list_of_scores, \"x\": [box[0] for", "imsizes[4]) fold5_nom = \"fold{}_{}\".format(5, imsizes[5]) fold6_nom = \"fold{}_{}\".format(6, imsizes[6]) fold7_nom", "os import re import numpy as np import pandas as", "= pd.DataFrame({\"patientId\": list_of_new_pids, \"x\": [box[0] for box in list_of_bboxes], \"y\":", "= res[\"image_id\"] coco_img_file = \"COCO_{}_{}.png\".format(test_set, str(coco_image_id).zfill(12)) list_of_image_ids.append(mapping[coco_img_file]) list_of_scores.append(res[\"score\"]) list_of_bboxes.append(res[\"bbox\"]) if", "= [] list_of_scores = [] list_of_bboxes = [] for res", "list_of_bboxes], \"score\": [box[5] for box in list_of_bboxes], \"votes\": [box[-1] for", "final_TTA_ensemble = final_TTA_ensemble[[\"patientId\", \"x\", \"y\", \"w\", \"h\", \"score\", \"votes\", \"adjustedScore\"]]", "[] for test_set in [test_image_set, \"{}_flip\".format(test_image_set)]: for suffix in [\"original\",", "= \"fold{}_{}\".format(4, imsizes[4]) fold5_nom = \"fold{}_{}\".format(5, imsizes[5]) fold6_nom = \"fold{}_{}\".format(6,", "in enumerate(list_of_dfs): tmp_df = each_df[each_df.patientId == pid] list_of_bboxes = []", "list_of_bboxes = [] for rownum, row in tmp_df.iterrows(): bbox =", "tmp_df = each_df[each_df.patientId == pid] list_of_bboxes = [] for rownum,", "import pandas as pd from src.infer.ExtractDeformableTTA import MAPPINGS_PATH, test_image_set, METADATA_PATH,", "= [] for test_set in [test_image_set, \"{}_flip\".format(test_image_set)]: for suffix in", "test_image_set, METADATA_PATH, RCNN0_DETS_DIR WDIR = os.path.dirname(os.path.abspath(__file__)) def get_results(det_folder, test_set, suffix):", "in [\"original\", \"scale080\", \"scale120\"]: tmp_results = get_results(os.path.join(MAIN_DIR, \"peepin_{}\".format(fold_imsize, fold_imsize)), test_set=test_set,", "(1024. - topRight[0], topRight[1]) return [newTopLeft[0], newTopLeft[1], w, h] def", "list_of_detections = [] view = metadata[metadata.patientId == pid][\"view\"].iloc[0] for df_index,", "fold9RCNN0] final_TTA_ensemble = run_ensemble(list_of_dfs, metadata, adjust_score=False) final_TTA_ensemble[\"adjustedScore\"] = final_TTA_ensemble.score *", "return [newTopLeft[0], newTopLeft[1], w, h] def convert_dict_to_df(results, mapping, metadata, test_set,", "flip_mapping, metadata, test_set=test_set, flip=True, threshold=0.01) else: tmp_df = convert_dict_to_df(tmp_results, mapping," ]
[ "json.loads(f.read()) uniswap_instance = w3.eth.contract( abi=uniswapABI, address=w3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"), ) pool4_instance = w3.eth.contract(abi=pool4ABI,", "= [YFII, WETH, DAI] with open(\"abi/erc20.json\") as f: erc20ABI =", "def _totalStakedAmount(): token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) return token_instance.functions.balanceOf(POOL4).call() / 1e18", "/ 1e18 def getDATA(): weekly_reward = ( pool4_instance.functions.rewardRate().call() / 1e6", "json.loads(f.read()) with open(\"abi/uniswapRouterv2.json\") as f: uniswapABI = json.loads(f.read()) with open(\"abi/pool4.json\")", "address=POOL4) def getyfiiprice(): price = uniswap_instance.functions.getAmountsOut( w3.toWei(1, \"ether\"), yfii2dai ).call()[-1]", "as f: erc20ABI = json.loads(f.read()) with open(\"abi/uniswapRouterv2.json\") as f: uniswapABI", "1e6 * 7 * 24 * 60 * 60 )", "= json.loads(f.read()) with open(\"abi/uniswapRouterv2.json\") as f: uniswapABI = json.loads(f.read()) with", "w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) totalStakedAmount = token_instance.functions.balanceOf(POOL4).call() / 1e18 YFIIPrice = getyfiiprice()", "w3.eth.contract(abi=pool4ABI, address=POOL4) def getyfiiprice(): price = uniswap_instance.functions.getAmountsOut( w3.toWei(1, \"ether\"), yfii2dai", "yfii2dai = [YFII, WETH, DAI] with open(\"abi/erc20.json\") as f: erc20ABI", "DAI = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\" iUSDT = \"0x72Cf258c852Dc485a853370171d46B9D29fD3184\" POOL4 = \"0x3d367C9529f260B0661e1C1E91167C9319ee96cA\" yfii2dai", "= json.loads(f.read()) uniswap_instance = w3.eth.contract( abi=uniswapABI, address=w3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"), ) pool4_instance =", "\"0x3d367C9529f260B0661e1C1E91167C9319ee96cA\" yfii2dai = [YFII, WETH, DAI] with open(\"abi/erc20.json\") as f:", "float(w3.fromWei(price, \"ether\")) def _weekly_reward(): return pool4_instance.functions.rewardRate().call() / 1e18 * 60480", "return pool4_instance.functions.rewardRate().call() / 1e18 * 60480 def _totalStakedAmount(): token_instance =", "open(\"abi/uniswapRouterv2.json\") as f: uniswapABI = json.loads(f.read()) with open(\"abi/pool4.json\") as f:", "totalStakedAmount * YFIIPrice YFIWeeklyROI = (weekly_reward / TVL) * 100", "w3 = Web3(HTTPProvider(w3url)) WETH = \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\" YFII = \"0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83\" DAI", "f: erc20ABI = json.loads(f.read()) with open(\"abi/uniswapRouterv2.json\") as f: uniswapABI =", "_weekly_reward(): return pool4_instance.functions.rewardRate().call() / 1e18 * 60480 def _totalStakedAmount(): token_instance", "w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) return token_instance.functions.balanceOf(POOL4).call() / 1e18 def getDATA(): weekly_reward =", "token_instance.functions.balanceOf(POOL4).call() / 1e18 YFIIPrice = getyfiiprice() TVL = totalStakedAmount *", "= \"0x72Cf258c852Dc485a853370171d46B9D29fD3184\" POOL4 = \"0x3d367C9529f260B0661e1C1E91167C9319ee96cA\" yfii2dai = [YFII, WETH, DAI]", "52 return {\"apy\": apy, \"totalStakedAmount\": totalStakedAmount, \"TVL\": TVL} if __name__", "price = uniswap_instance.functions.getAmountsOut( w3.toWei(1, \"ether\"), yfii2dai ).call()[-1] return float(w3.fromWei(price, \"ether\"))", "as f: uniswapABI = json.loads(f.read()) with open(\"abi/pool4.json\") as f: pool4ABI", "/ 1e18 YFIIPrice = getyfiiprice() TVL = totalStakedAmount * YFIIPrice", "abi=uniswapABI, address=w3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"), ) pool4_instance = w3.eth.contract(abi=pool4ABI, address=POOL4) def getyfiiprice(): price", "f: pool4ABI = json.loads(f.read()) uniswap_instance = w3.eth.contract( abi=uniswapABI, address=w3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"), )", "( pool4_instance.functions.rewardRate().call() / 1e6 * 7 * 24 * 60", "= w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) return token_instance.functions.balanceOf(POOL4).call() / 1e18 def getDATA(): weekly_reward", "60480 def _totalStakedAmount(): token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) return token_instance.functions.balanceOf(POOL4).call() /", "_totalStakedAmount(): token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) return token_instance.functions.balanceOf(POOL4).call() / 1e18 def", "uniswap_instance = w3.eth.contract( abi=uniswapABI, address=w3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"), ) pool4_instance = w3.eth.contract(abi=pool4ABI, address=POOL4)", "* 7 * 24 * 60 * 60 ) token_instance", "pool4ABI = json.loads(f.read()) uniswap_instance = w3.eth.contract( abi=uniswapABI, address=w3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"), ) pool4_instance", "token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) totalStakedAmount = token_instance.functions.balanceOf(POOL4).call() / 1e18 YFIIPrice", ") token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) totalStakedAmount = token_instance.functions.balanceOf(POOL4).call() / 1e18", "getDATA(): weekly_reward = ( pool4_instance.functions.rewardRate().call() / 1e6 * 7 *", "WETH = \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\" YFII = \"0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83\" DAI = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\" iUSDT", "weekly_reward = ( pool4_instance.functions.rewardRate().call() / 1e6 * 7 * 24", "= \"0x3d367C9529f260B0661e1C1E91167C9319ee96cA\" yfii2dai = [YFII, WETH, DAI] with open(\"abi/erc20.json\") as", "erc20ABI = json.loads(f.read()) with open(\"abi/uniswapRouterv2.json\") as f: uniswapABI = json.loads(f.read())", "HTTPProvider import json w3url = \"https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca\" w3 = Web3(HTTPProvider(w3url)) WETH", "apy, \"totalStakedAmount\": totalStakedAmount, \"TVL\": TVL} if __name__ == \"__main__\": print(getDATA())", "* 60480 def _totalStakedAmount(): token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) return token_instance.functions.balanceOf(POOL4).call()", "Web3(HTTPProvider(w3url)) WETH = \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\" YFII = \"0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83\" DAI = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\"", "with open(\"abi/erc20.json\") as f: erc20ABI = json.loads(f.read()) with open(\"abi/uniswapRouterv2.json\") as", "1e18 def getDATA(): weekly_reward = ( pool4_instance.functions.rewardRate().call() / 1e6 *", "address=w3.toChecksumAddress(YFII)) totalStakedAmount = token_instance.functions.balanceOf(POOL4).call() / 1e18 YFIIPrice = getyfiiprice() TVL", "w3.eth.contract( abi=uniswapABI, address=w3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"), ) pool4_instance = w3.eth.contract(abi=pool4ABI, address=POOL4) def getyfiiprice():", "import json w3url = \"https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca\" w3 = Web3(HTTPProvider(w3url)) WETH =", "address=w3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"), ) pool4_instance = w3.eth.contract(abi=pool4ABI, address=POOL4) def getyfiiprice(): price =", "return {\"apy\": apy, \"totalStakedAmount\": totalStakedAmount, \"TVL\": TVL} if __name__ ==", "= w3.eth.contract( abi=uniswapABI, address=w3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"), ) pool4_instance = w3.eth.contract(abi=pool4ABI, address=POOL4) def", "= totalStakedAmount * YFIIPrice YFIWeeklyROI = (weekly_reward / TVL) *", "* 100 / 1.01 apy = YFIWeeklyROI * 52 return", "pool4_instance = w3.eth.contract(abi=pool4ABI, address=POOL4) def getyfiiprice(): price = uniswap_instance.functions.getAmountsOut( w3.toWei(1,", "def _weekly_reward(): return pool4_instance.functions.rewardRate().call() / 1e18 * 60480 def _totalStakedAmount():", "/ 1e18 * 60480 def _totalStakedAmount(): token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII))", "* YFIIPrice YFIWeeklyROI = (weekly_reward / TVL) * 100 /", "DAI] with open(\"abi/erc20.json\") as f: erc20ABI = json.loads(f.read()) with open(\"abi/uniswapRouterv2.json\")", "= (weekly_reward / TVL) * 100 / 1.01 apy =", "def getDATA(): weekly_reward = ( pool4_instance.functions.rewardRate().call() / 1e6 * 7", "YFIIPrice YFIWeeklyROI = (weekly_reward / TVL) * 100 / 1.01", "= ( pool4_instance.functions.rewardRate().call() / 1e6 * 7 * 24 *", "= getyfiiprice() TVL = totalStakedAmount * YFIIPrice YFIWeeklyROI = (weekly_reward", "json w3url = \"https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca\" w3 = Web3(HTTPProvider(w3url)) WETH = \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\"", "= Web3(HTTPProvider(w3url)) WETH = \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\" YFII = \"0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83\" DAI =", "* 24 * 60 * 60 ) token_instance = w3.eth.contract(abi=erc20ABI,", "* 60 * 60 ) token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) totalStakedAmount", "YFIIPrice = getyfiiprice() TVL = totalStakedAmount * YFIIPrice YFIWeeklyROI =", "[YFII, WETH, DAI] with open(\"abi/erc20.json\") as f: erc20ABI = json.loads(f.read())", "def getyfiiprice(): price = uniswap_instance.functions.getAmountsOut( w3.toWei(1, \"ether\"), yfii2dai ).call()[-1] return", "YFIWeeklyROI = (weekly_reward / TVL) * 100 / 1.01 apy", "= \"0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83\" DAI = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\" iUSDT = \"0x72Cf258c852Dc485a853370171d46B9D29fD3184\" POOL4 =", "= w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) totalStakedAmount = token_instance.functions.balanceOf(POOL4).call() / 1e18 YFIIPrice =", "\"ether\")) def _weekly_reward(): return pool4_instance.functions.rewardRate().call() / 1e18 * 60480 def", "YFIWeeklyROI * 52 return {\"apy\": apy, \"totalStakedAmount\": totalStakedAmount, \"TVL\": TVL}", "pool4_instance.functions.rewardRate().call() / 1e6 * 7 * 24 * 60 *", "web3 import Web3, HTTPProvider import json w3url = \"https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca\" w3", "yfii2dai ).call()[-1] return float(w3.fromWei(price, \"ether\")) def _weekly_reward(): return pool4_instance.functions.rewardRate().call() /", "= \"0x6B175474E89094C44Da98b954EedeAC495271d0F\" iUSDT = \"0x72Cf258c852Dc485a853370171d46B9D29fD3184\" POOL4 = \"0x3d367C9529f260B0661e1C1E91167C9319ee96cA\" yfii2dai =", "60 * 60 ) token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) totalStakedAmount =", "pool4_instance.functions.rewardRate().call() / 1e18 * 60480 def _totalStakedAmount(): token_instance = w3.eth.contract(abi=erc20ABI,", ") pool4_instance = w3.eth.contract(abi=pool4ABI, address=POOL4) def getyfiiprice(): price = uniswap_instance.functions.getAmountsOut(", "json.loads(f.read()) with open(\"abi/pool4.json\") as f: pool4ABI = json.loads(f.read()) uniswap_instance =", "return token_instance.functions.balanceOf(POOL4).call() / 1e18 def getDATA(): weekly_reward = ( pool4_instance.functions.rewardRate().call()", "/ 1e6 * 7 * 24 * 60 * 60", "1e18 * 60480 def _totalStakedAmount(): token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) return", "= \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\" YFII = \"0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83\" DAI = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\" iUSDT =", "= token_instance.functions.balanceOf(POOL4).call() / 1e18 YFIIPrice = getyfiiprice() TVL = totalStakedAmount", "YFII = \"0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83\" DAI = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\" iUSDT = \"0x72Cf258c852Dc485a853370171d46B9D29fD3184\" POOL4", "uniswapABI = json.loads(f.read()) with open(\"abi/pool4.json\") as f: pool4ABI = json.loads(f.read())", "= uniswap_instance.functions.getAmountsOut( w3.toWei(1, \"ether\"), yfii2dai ).call()[-1] return float(w3.fromWei(price, \"ether\")) def", "f: uniswapABI = json.loads(f.read()) with open(\"abi/pool4.json\") as f: pool4ABI =", "as f: pool4ABI = json.loads(f.read()) uniswap_instance = w3.eth.contract( abi=uniswapABI, address=w3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"),", "open(\"abi/erc20.json\") as f: erc20ABI = json.loads(f.read()) with open(\"abi/uniswapRouterv2.json\") as f:", "1e18 YFIIPrice = getyfiiprice() TVL = totalStakedAmount * YFIIPrice YFIWeeklyROI", "token_instance.functions.balanceOf(POOL4).call() / 1e18 def getDATA(): weekly_reward = ( pool4_instance.functions.rewardRate().call() /", ").call()[-1] return float(w3.fromWei(price, \"ether\")) def _weekly_reward(): return pool4_instance.functions.rewardRate().call() / 1e18", "from web3 import Web3, HTTPProvider import json w3url = \"https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca\"", "POOL4 = \"0x3d367C9529f260B0661e1C1E91167C9319ee96cA\" yfii2dai = [YFII, WETH, DAI] with open(\"abi/erc20.json\")", "open(\"abi/pool4.json\") as f: pool4ABI = json.loads(f.read()) uniswap_instance = w3.eth.contract( abi=uniswapABI,", "WETH, DAI] with open(\"abi/erc20.json\") as f: erc20ABI = json.loads(f.read()) with", "address=w3.toChecksumAddress(YFII)) return token_instance.functions.balanceOf(POOL4).call() / 1e18 def getDATA(): weekly_reward = (", "/ 1.01 apy = YFIWeeklyROI * 52 return {\"apy\": apy,", "return float(w3.fromWei(price, \"ether\")) def _weekly_reward(): return pool4_instance.functions.rewardRate().call() / 1e18 *", "{\"apy\": apy, \"totalStakedAmount\": totalStakedAmount, \"TVL\": TVL} if __name__ == \"__main__\":", "totalStakedAmount = token_instance.functions.balanceOf(POOL4).call() / 1e18 YFIIPrice = getyfiiprice() TVL =", "= json.loads(f.read()) with open(\"abi/pool4.json\") as f: pool4ABI = json.loads(f.read()) uniswap_instance", "TVL = totalStakedAmount * YFIIPrice YFIWeeklyROI = (weekly_reward / TVL)", "apy = YFIWeeklyROI * 52 return {\"apy\": apy, \"totalStakedAmount\": totalStakedAmount,", "with open(\"abi/pool4.json\") as f: pool4ABI = json.loads(f.read()) uniswap_instance = w3.eth.contract(", "\"https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca\" w3 = Web3(HTTPProvider(w3url)) WETH = \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\" YFII = \"0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83\"", "getyfiiprice(): price = uniswap_instance.functions.getAmountsOut( w3.toWei(1, \"ether\"), yfii2dai ).call()[-1] return float(w3.fromWei(price,", "\"0x72Cf258c852Dc485a853370171d46B9D29fD3184\" POOL4 = \"0x3d367C9529f260B0661e1C1E91167C9319ee96cA\" yfii2dai = [YFII, WETH, DAI] with", "import Web3, HTTPProvider import json w3url = \"https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca\" w3 =", "\"ether\"), yfii2dai ).call()[-1] return float(w3.fromWei(price, \"ether\")) def _weekly_reward(): return pool4_instance.functions.rewardRate().call()", "* 60 ) token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) totalStakedAmount = token_instance.functions.balanceOf(POOL4).call()", "getyfiiprice() TVL = totalStakedAmount * YFIIPrice YFIWeeklyROI = (weekly_reward /", "uniswap_instance.functions.getAmountsOut( w3.toWei(1, \"ether\"), yfii2dai ).call()[-1] return float(w3.fromWei(price, \"ether\")) def _weekly_reward():", "/ TVL) * 100 / 1.01 apy = YFIWeeklyROI *", "60 ) token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) totalStakedAmount = token_instance.functions.balanceOf(POOL4).call() /", "\"0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83\" DAI = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\" iUSDT = \"0x72Cf258c852Dc485a853370171d46B9D29fD3184\" POOL4 = \"0x3d367C9529f260B0661e1C1E91167C9319ee96cA\"", "(weekly_reward / TVL) * 100 / 1.01 apy = YFIWeeklyROI", "* 52 return {\"apy\": apy, \"totalStakedAmount\": totalStakedAmount, \"TVL\": TVL} if", "24 * 60 * 60 ) token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII))", "w3.toWei(1, \"ether\"), yfii2dai ).call()[-1] return float(w3.fromWei(price, \"ether\")) def _weekly_reward(): return", "with open(\"abi/uniswapRouterv2.json\") as f: uniswapABI = json.loads(f.read()) with open(\"abi/pool4.json\") as", "= \"https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca\" w3 = Web3(HTTPProvider(w3url)) WETH = \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\" YFII =", "= w3.eth.contract(abi=pool4ABI, address=POOL4) def getyfiiprice(): price = uniswap_instance.functions.getAmountsOut( w3.toWei(1, \"ether\"),", "100 / 1.01 apy = YFIWeeklyROI * 52 return {\"apy\":", "1.01 apy = YFIWeeklyROI * 52 return {\"apy\": apy, \"totalStakedAmount\":", "w3url = \"https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca\" w3 = Web3(HTTPProvider(w3url)) WETH = \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\" YFII", "= YFIWeeklyROI * 52 return {\"apy\": apy, \"totalStakedAmount\": totalStakedAmount, \"TVL\":", "\"0x6B175474E89094C44Da98b954EedeAC495271d0F\" iUSDT = \"0x72Cf258c852Dc485a853370171d46B9D29fD3184\" POOL4 = \"0x3d367C9529f260B0661e1C1E91167C9319ee96cA\" yfii2dai = [YFII,", "token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) return token_instance.functions.balanceOf(POOL4).call() / 1e18 def getDATA():", "Web3, HTTPProvider import json w3url = \"https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca\" w3 = Web3(HTTPProvider(w3url))", "7 * 24 * 60 * 60 ) token_instance =", "TVL) * 100 / 1.01 apy = YFIWeeklyROI * 52", "\"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\" YFII = \"0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83\" DAI = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\" iUSDT = \"0x72Cf258c852Dc485a853370171d46B9D29fD3184\"", "iUSDT = \"0x72Cf258c852Dc485a853370171d46B9D29fD3184\" POOL4 = \"0x3d367C9529f260B0661e1C1E91167C9319ee96cA\" yfii2dai = [YFII, WETH," ]
[ "saved projectors. *name* type: String (Optional) Name of the source", "if source of this type provide frames asynchronously *types.*.caps.hasVideo* type:", "__init__(self): Baserequests.__init__(self) self.name = 'GetStudioModeStatus' self.datain['studio-mode'] = None def getStudioMode(self):", "boolean Audio active status of the source. \"\"\" def __init__(self,", "created *item* type: Object New item info *item.id* type: int", "source before scaling. *crop.bottom* type: int (optional) The new amount", "will remain unchanged. Coordinates are relative to the item's parent", "getCustom_width(self): return self.datain['custom_width'] def getDrop_shadow(self): return self.datain['drop_shadow'] def getFont(self): return", "self.name = 'StartRecording' class StopRecording(Baserequests): \"\"\"Stop recording. Will return an", "recording status. *isRecordingPaused* type: boolean Whether the recording is paused", "filename_formatting class GetFilenameFormatting(Baserequests): \"\"\"Get the filename formatting string :Returns: *filename_formatting*", "scene. *sources* type: Array<SceneItem> \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "to false. Defaults to true. \"\"\" def __init__(self, position, release=None):", "return self.datain['settings'] class AddFilterToSource(Baserequests): \"\"\"Add a new filter to a", "\"face\": \"Arial\", \"flags\": 0, \"size\": 150, \"style\": \"\" }` *font.face*", "= None def getPosition(self): return self.datain['position'] class GetTransitionSettings(Baserequests): \"\"\"Get the", "None self.datain['sourceSettings'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceSettings'] = sourceSettings", "monitor type in use. Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def", "GetTextGDIPlusProperties(Baserequests): \"\"\"Get the current properties of a Text GDI Plus", "getOutputHeight(self): return self.datain['outputHeight'] def getScaleType(self): return self.datain['scaleType'] def getFps(self): return", "other words, this is how you add a source into", "of OBS v25.0.8) :Arguments: *sourceName* type: String Source name. *playPause*", "Source. :Arguments: *source* type: String Name of the source. *is_local_file*", "MUST CALL THIS if you called `SetTBarPosition` with the `release`", "self.datain['name'] = None self.datain['settings'] = None self.dataout['sourceName'] = sourceName self.dataout['filterName']", "off (depending on the current stream state). \"\"\" def __init__(self):", "self.dataout['right'] = right self.dataout['scene-name'] = scene_name class DeleteSceneItem(Baserequests): \"\"\"Deletes a", "= 'GetSpecialSources' self.datain['desktop-1'] = None self.datain['desktop-2'] = None self.datain['mic-1'] =", "type: String Unique source name *sources.*.typeId* type: String Non-unique source", "Url. *css* type: String (optional) CSS to inject. *width* type:", "type: String The monitor type in use. Options: `none`, `monitorOnly`,", "before scaling. *crop.right* type: int (optional) The new amount of", "String (optional) Name of a scene item. Sufficiently unique if", "*current_transition* type: String Name of the currently active transition. *transitions*", "authentication should be used when connecting to the streaming server.", "Mute status of the source. \"\"\" def __init__(self, source): Baserequests.__init__(self)", "opacity (0-100). *outline* type: boolean Outline. *outline_color* type: int Outline", "Name of the currently active scene collection. \"\"\" def __init__(self):", "return self.datain['sourceWidth'] def getSourceHeight(self): return self.datain['sourceHeight'] def getWidth(self): return self.datain['width']", "source *filters.*.enabled* type: Boolean Filter status (enabled or not) *filters.*.type*", "sources, you can also provide a scene name. If not", "bounds type of the source. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\",", "__init__(self, source): Baserequests.__init__(self) self.name = 'ToggleMute' self.dataout['source'] = source class", "\"\"\"Get the audio's active status of a specified source. :Arguments:", "self.dataout['sourceName'] = sourceName self.dataout['embedPictureFormat'] = embedPictureFormat self.dataout['saveToFilePath'] = saveToFilePath self.dataout['fileFormat']", "`SetRecordingFolder` is called while a recording is in progress, the", "scene items *sceneItems.*.itemId* type: int Unique item id of the", "*width* type: double Scene item width (base source width multiplied", "(optional) CSS to inject. *width* type: int (optional) Width. *height*", "sources types :Returns: *types* type: Array<Object> Array of source types", "name \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListSceneCollections' self.datain['scene-collections'] =", "__init__(self, with_transition=None): Baserequests.__init__(self) self.name = 'TransitionToProgram' self.dataout['with-transition'] = with_transition class", "= 'ResumeRecording' class SetRecordingFolder(Baserequests): \"\"\" Please note: if `SetRecordingFolder` is", ":Arguments: *source* type: String Source name. *useDecibel* type: boolean (optional)", "def __init__(self): Baserequests.__init__(self) self.name = 'GetStats' self.datain['stats'] = None def", "sources like Desktop Audio and Mic/Aux sources. :Returns: *desktop_1* type:", "width (without scaling) of the source *sourceHeight* type: int Base", "shouldn't be \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSourceTypesList' self.datain['types']", "source. Default response uses mul format, NOT SLIDER PERCENTAGE. :Arguments:", "left of the source item. *right* type: int Pixel position", "current scene's name and source items. :Returns: *name* type: String", "type: String (optional) NAme of the third Mic/Aux input source.", "= 'GetSourceFilters' self.datain['filters'] = None self.dataout['sourceName'] = sourceName def getFilters(self):", ":Returns: *current_scene* type: String Name of the currently active scene.", "class OpenProjector(Baserequests): \"\"\"Open a projector window or create a projector", "with the actual source's type. *sourceSettings* type: Object Source settings", "class SetSceneItemRender(Baserequests): \"\"\"Show or hide a specified source item in", "None self.datain['sceneItems'] = None self.dataout['sceneName'] = sceneName def getSceneName(self): return", "int Transition duration. `-1` if no override is set. \"\"\"", "available from `GetSourceTypesList`. :Arguments: *sourceName* type: String Name of the", "type: String Source name. *sourceKind* type: String Source kind, Eg.", "def __init__(self, transition_name): Baserequests.__init__(self) self.name = 'SetCurrentTransition' self.dataout['transition-name'] = transition_name", "String The name of the transition. \"\"\" def __init__(self, transition_name):", "*filterSettings* type: Object New settings. These will be merged to", "specified filter is removed *filterName* type: String Name of the", "`monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self, sourceName, monitorType): Baserequests.__init__(self) self.name =", "__init__(self): Baserequests.__init__(self) self.name = 'GetSourceTypesList' self.datain['types'] = None def getTypes(self):", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopStreaming' class StartStreaming(Baserequests): \"\"\"Start", "__init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaTime' self.datain['timestamp'] = None self.dataout['sourceName']", "or `Multiview` (case insensitive). *monitor* type: int (Optional) Monitor to", "Chat log. *chatlog_lines* type: int (optional) Chat log lines. *color*", "locked self.dataout['bounds'] = bounds class ResetSceneItem(Baserequests): \"\"\"Reset a scene item.", "of the source item. \"\"\" def __init__(self, item, top, bottom,", "settings. \"\"\" def __init__(self, sourceName, filterName, filterSettings): Baserequests.__init__(self) self.name =", "type: int (optional) Custom width (0 to disable). *drop_shadow* type:", "emitting heartbeat messages \"\"\" def __init__(self, enable): Baserequests.__init__(self) self.name =", "item, x, y, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemPosition' self.dataout['item'] =", "*color* type: int (optional) Text color. *extents* type: boolean (optional)", "= None self.datain['bounds'] = None self.datain['sourceWidth'] = None self.datain['sourceHeight'] =", "opens a window. *geometry* type: String (Optional) Size and position", "'SetTransitionDuration' self.dataout['duration'] = duration class GetTransitionDuration(Baserequests): \"\"\"Get the duration of", "*stream.metadata* type: Object (optional) Adds the given object parameters as", "Baserequests.__init__(self) self.name = 'StopStreaming' class SetStreamSettings(Baserequests): \"\"\"Sets one or more", "Name of the currently active profile. \"\"\" def __init__(self): Baserequests.__init__(self)", "OBS v25.0.8) Note: Due to processing/network delays, this request is", "the current scene. *item* type: Object Scene Item to duplicate", "not given. \"\"\" def __init__(self, sceneName, transitionName, transitionDuration): Baserequests.__init__(self) self.name", "name and/or id specified. Id preferred due to uniqueness per", "type: Object Source settings (varies between source types, may require", "of the source before scaling. *visible* type: bool (optional) The", "= 'EnableStudioMode' class DisableStudioMode(Baserequests): \"\"\"Disables Studio Mode. \"\"\" def __init__(self):", "self.name = 'ReleaseTBar' class SetTBarPosition(Baserequests): \"\"\" If your code needs", "= sourceName self.dataout['sourceKind'] = sourceKind self.dataout['sceneName'] = sceneName self.dataout['sourceSettings'] =", "returns authentication parameters `challenge` and `salt` (see \"Authentication\" for more", "type: boolean Word wrap. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name", "specified source. :Arguments: *source* type: String Source name. \"\"\" def", "source item. *bottom* type: int Pixel position of the bottom", "stream. *stream.settings.server* type: String (optional) The publish URL. *stream.settings.key* type:", "bounding box. (0-2, 4-6, 8-10) *bounds.x* type: double (optional) The", "parent (if this item belongs to a group) *groupChildren* type:", "to create the item in. Defaults to the current scene.", "source's base width. *height* type: int (optional) Screenshot height. Defaults", "= fileFormat self.dataout['compressionQuality'] = compressionQuality self.dataout['width'] = width self.dataout['height'] =", "type: int (optional) Gradient bottom color. *custom_width* type: int (optional)", "return an `error` if the Replay Buffer is already active", "None self.datain['groupChildren'] = None self.dataout['item'] = item self.dataout['scene-name'] = scene_name", "the image file as (one of the values provided in", "of the selected transition. *duration* type: int (optional) Transition duration", "*type* type: String (Optional) Type of projector: `Preview` (default), `Source`,", "add the new source to. *sourceSettings* type: Object (optional) Source", "self.dataout['gradient'] = gradient self.dataout['gradient_color'] = gradient_color self.dataout['gradient_dir'] = gradient_dir self.dataout['gradient_opacity']", "dB values under -100.0 as Inf. Note: The OBS volume", "The new amount of pixels cropped off the left of", "alignment (\"top\", \"center\", \"bottom\"). *vertical* type: boolean (optional) Vertical text", "an animation, or in response to a user moving a", "log lines. *color* type: int Text color. *extents* type: boolean", "'SetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType'] = None self.datain['sourceSettings'] = None", "is how you add a source into a scene. :Arguments:", "Name of the transition. *with_transition.duration* type: int (optional) Transition duration", "Baserequests.__init__(self) self.name = 'GetCurrentProfile' self.datain['profile-name'] = None def getProfileName(self): return", "\"\"\"Set a scene to use a specific transition override. :Arguments:", "= keyId self.dataout['keyModifiers'] = keyModifiers class PlayPauseMedia(Baserequests): \"\"\"Pause or play", "= bottom self.dataout['left'] = left self.dataout['right'] = right self.dataout['scene-name'] =", "Indicates whether authentication should be used when connecting to the", "sourceSettings self.dataout['setVisible'] = setVisible def getItemId(self): return self.datain['itemId'] class GetSourcesList(Baserequests):", "*file* type: String (optional) File path name. *read_from_file* type: boolean", "timestamp class ScrubMedia(Baserequests): \"\"\"Scrub media using a supplied offset. Supports", "__init__(self): Baserequests.__init__(self) self.name = 'GetVersion' self.datain['version'] = None self.datain['obs-websocket-version'] =", "force class SetCurrentProfile(Baserequests): \"\"\"Set the currently active profile. :Arguments: *profile_name*", "'SetSourceFilterVisibility' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterEnabled'] = filterEnabled", "self.datain['groupChildren'] class SetSceneItemProperties(Baserequests): \"\"\"Sets the scene specific properties of a", "(in nanoseconds). \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetSyncOffset'", "type: boolean Audio active status of the source. \"\"\" def", "*profiles.*.profile_name* type: String Filter name \"\"\" def __init__(self): Baserequests.__init__(self) self.name", ":Returns: *source* type: String Source name. *is_local_file* type: boolean Indicates", "folder. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetRecordingFolder' self.datain['rec-folder'] =", "desired scene collection. \"\"\" def __init__(self, sc_name): Baserequests.__init__(self) self.name =", "hotkey routine, identified by bound combination of keys. A single", "type: String Text Alignment (\"left\", \"center\", \"right\"). *bk_color* type: int", "int (optional) Outline opacity (0-100). *text* type: String (optional) Text", "local file is in use. *local_file* type: String (optional) file", "format different from `pictureFormat`. Can be a relative path. *fileFormat*", "in the frontend's dropdown menu. :Returns: *current_transition* type: String Name", "GetSceneItemProperties(Baserequests): \"\"\"Gets the scene specific properties of the specified source", ":Arguments: *source* type: String Source name. \"\"\" def __init__(self, source):", "set `release` to false. Defaults to true. \"\"\" def __init__(self,", "media source) :Returns: *mediaSources* type: Array<Object> Array of sources *mediaSources.*.sourceName*", "= crop self.dataout['visible'] = visible self.dataout['locked'] = locked self.dataout['bounds'] =", "compression. Varies with image type. *width* type: int (optional) Screenshot", "in decibels of attenuation instead of amplitude/mul. :Returns: *name* type:", "media source. Supports ffmpeg and vlc media sources (as of", "Sufficiently unique if no scene items share sources within the", "'StopReplayBuffer' class SaveReplayBuffer(Baserequests): \"\"\"Flush and save the contents of the", "you called `SetTBarPosition` with the `release` parameter set to `false`.*", "None self.datain['itemId'] = None self.datain['position'] = None self.datain['rotation'] = None", "self.name = 'SetTextFreetype2Properties' self.dataout['source'] = source self.dataout['color1'] = color1 self.dataout['color2']", "self.name = 'SetMute' self.dataout['source'] = source self.dataout['mute'] = mute class", "(\"left\", \"center\", \"right\"). *bk_color* type: int Background color. *bk_opacity* type:", "of 50ms. :Arguments: *sourceName* type: String Source name. :Returns: *mediaDuration*", "self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName class ReorderSourceFilter(Baserequests): \"\"\"Move a", "*extents_cy* type: int (optional) Extents cy. *file* type: String (optional)", "\"bottom\"). *vertical* type: boolean (optional) Vertical text enabled. *render* type:", ":Returns: *sc_name* type: String Name of the currently active scene", "self.dataout['sourceName'] = sourceName def getTimestamp(self): return self.datain['timestamp'] class SetMediaTime(Baserequests): \"\"\"Set", "return self.datain['current-transition'] def getTransitions(self): return self.datain['transitions'] class GetCurrentTransition(Baserequests): \"\"\"Get the", "Holds data for the font. Ex: `\"font\": { \"face\": \"Arial\",", "*sc_name* type: String Name of the currently active scene collection.", "toScene def getScene(self): return self.datain['scene'] def getItem(self): return self.datain['item'] class", "GetCurrentScene(Baserequests): \"\"\"Get the current scene's name and source items. :Returns:", "active transition before switching scenes. Defaults to the active transition.", "= font self.dataout['from_file'] = from_file self.dataout['log_mode'] = log_mode self.dataout['outline'] =", "Source name. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'ToggleMute'", "= mute class ToggleMute(Baserequests): \"\"\"Inverts the mute status of a", "of the current scene collection. :Returns: *sc_name* type: String Name", "item was created *item* type: Object New item info *item.id*", "Defaults to the current scene. *item* type: String | Object", "= None self.datain['isRecordingPaused'] = None self.datain['recordTimecode'] = None self.datain['recordingFilename'] =", "left, right, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemCrop' self.dataout['item'] = item", "type: int Unique item id of the source item *sceneItems.*.sourceKind*", "be between 0.0 and 1.0. *release* type: boolean (optional) Whether", "self.dataout['outline'] = outline self.dataout['outline_color'] = outline_color self.dataout['outline_size'] = outline_size self.dataout['outline_opacity']", "String Scene Item name (prefer `id`, including both is acceptable).", "(e.g. \"ReplayBuffer.Save\") \"\"\" def __init__(self, hotkeyName): Baserequests.__init__(self) self.name = 'TriggerHotkeyByName'", "transition if transition is not fixed. Defaults to the current", "the source should be shutdown when not visible. *render* type:", "omit to center on that axis. *rotation* type: double The", "self.datain['font'] def getFrom_file(self): return self.datain['from_file'] def getLog_mode(self): return self.datain['log_mode'] def", "filterType, filterSettings): Baserequests.__init__(self) self.name = 'AddFilterToSource' self.dataout['sourceName'] = sourceName self.dataout['filterName']", "the filename formatting string :Returns: *filename_formatting* type: String Current filename", "*visible* type: bool (optional) The new visibility of the source.", "__init__(self, item, top, bottom, left, right, scene_name=None): Baserequests.__init__(self) self.name =", "v24.0.4 or newer. :Arguments: *type* type: String (Optional) Type of", "Scene Item ID. :Returns: *scene* type: String Name of the", "Source name. :Returns: *mediaDuration* type: int The total length of", "String (optional) Type of the specified source. Useful for type-checking", "the chain (relative positioning) :Arguments: *sourceName* type: String Name of", "(optional) Text vertical alignment (\"top\", \"center\", \"bottom\"). *vertical* type: boolean", "*filterType* type: String Filter type *filterSettings* type: Object Filter settings", "*outputHeight* type: int Output height *scaleType* type: String Scaling method", "boolean Mute status of the source. \"\"\" def __init__(self, source):", "ID if the scene item's source. For example `vlc_source` or", "double T-Bar position. This value must be between 0.0 and", "item. :Arguments: *scene_name* type: String (optional) Name of the scene", "parameters to receive scaled pictures. Aspect ratio is preserved if", "self.datain['mic-3'] class GetSourceFilters(Baserequests): \"\"\"List filters applied to a source :Arguments:", "'AddFilterToSource' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterType'] = filterType", "data to the RTMP service about the streaming. May be", ":Arguments: *enable* type: boolean Starts/Stops emitting heartbeat messages \"\"\" def", "*filename_formatting* type: String Current filename formatting string. \"\"\" def __init__(self):", "source to which the filter belongs *filterName* type: String Name", "double Scene item width (base source width multiplied by the", "\"\"\"Go to the previous media item in the playlist. Supports", "feature of obs-websocket. Some plugins which add outputs to OBS", "cropped off the top of the source before scaling. *crop.bottom*", "This value must be between 0.0 and 1.0. *release* type:", "return self.datain['preview-only'] class StartStopStreaming(Baserequests): \"\"\"Toggle streaming on or off (depending", "\"\"\"Show or hide a specified source item in a specified", "None def getTransitionDuration(self): return self.datain['transition-duration'] class GetTransitionPosition(Baserequests): \"\"\"Get the position", "The new alignment of the source. *rotation* type: double (optional)", "T-Bar control in your User Interface), set `release` to false", "not. *recordTimecode* type: String (optional) Time elapsed since recording started", "name. *align* type: String Text Alignment (\"left\", \"center\", \"right\"). *bk_color*", "item. *right* type: int Pixel position of the right of", "String Name of the desired profile. \"\"\" def __init__(self, profile_name):", "scene to reorder (defaults to current). *items* type: Array<Scene> Ordered", "center on that axis. *rotation* type: double The clockwise rotation", "OBS v25.0.8) :Arguments: *sourceName* type: String Source name. *timestamp* type:", "\"\"\"Get the current settings of a transition :Arguments: *transitionName* type:", "specified in the UI if there is no current override", "*sceneItems.*.sourceType* type: String Type of the scene item's source. Either", "int Gradient bottom color. *custom_width* type: int Custom width (0", "scene_name class SetSceneItemPosition(Baserequests): \"\"\"Sets the coordinates of a specified source", "duration (in milliseconds). \"\"\" def __init__(self, with_transition=None): Baserequests.__init__(self) self.name =", "*drop_shadow* type: boolean Drop shadow. *font* type: Object Holds data", "class SetMute(Baserequests): \"\"\"Sets the mute status of a specified source.", "def getIsReplayBufferActive(self): return self.datain['isReplayBufferActive'] class StartStopReplayBuffer(Baserequests): \"\"\"Toggle the Replay Buffer", "Pixel position of the bottom of the source item. *left*", "__init__(self): Baserequests.__init__(self) self.name = 'StartStopStreaming' class StartStreaming(Baserequests): \"\"\"Start streaming. Will", "`-1` if no override is set. \"\"\" def __init__(self, sceneName):", "is an object) :Returns: *name* type: String Scene Item name.", "sceneitem visible on creation or not. Default `true` :Returns: *itemId*", "CreateScene(Baserequests): \"\"\"Create a new scene scene. :Arguments: *sceneName* type: String", "Baserequests.__init__(self) self.name = 'GetVideoInfo' self.datain['baseWidth'] = None self.datain['baseHeight'] = None", "The type of streaming service configuration, usually `rtmp_custom` or `rtmp_common`.", "PlayPauseMedia(Baserequests): \"\"\"Pause or play a media source. Supports ffmpeg and", "sourceName self.dataout['monitorType'] = monitorType class TakeSourceScreenshot(Baserequests): \"\"\" At least `embedPictureFormat`", "__init__(self, duration): Baserequests.__init__(self) self.name = 'SetTransitionDuration' self.dataout['duration'] = duration class", "type: String Source name. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name", "GetSourceFilterInfo(Baserequests): \"\"\"List filters applied to a source :Arguments: *sourceName* type:", "'SetSourceFilterSettings' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterSettings'] = filterSettings", "Baserequests.__init__(self) self.name = 'GetTextFreetype2Properties' self.datain['source'] = None self.datain['color1'] = None", "type: Object Current transition settings \"\"\" def __init__(self, transitionName): Baserequests.__init__(self)", "self.dataout['position'] = position self.dataout['rotation'] = rotation self.dataout['scale'] = scale self.dataout['crop']", "are relative to the item's parent (the scene or group", "type: int (optional) The new alignment of the source. *rotation*", "\"filter\", \"transition\" or \"other\" *types.*.defaultSettings* type: Object Default settings of", "\"\"\" def __init__(self, source, render, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemRender'", "String (optional) File path. *word_wrap* type: boolean (optional) Word wrap.", "the bounding box. *bounds.y* type: double Height of the bounding", "return self.datain['scene'] def getItem(self): return self.datain['item'] class SetCurrentScene(Baserequests): \"\"\"Switch to", "Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self, sourceName, monitorType): Baserequests.__init__(self)", "the source from the top. *position.alignment* type: int The point", "String CSS to inject. *width* type: int Width. *height* type:", "String Scene Item name. *top* type: int Pixel position of", "this request is not perfect. The processing rate of this", "of the source to be added *setVisible* type: boolean Whether", "`ended`, `error`, `unknown` \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name =", "*extents* type: boolean (optional) Extents wrap. *extents_cx* type: int (optional)", "recording). *recordingFilename* type: String (optional) Absolute path to the recording", "def getTimestamp(self): return self.datain['timestamp'] class SetMediaTime(Baserequests): \"\"\"Set the timestamp of", "the new name already exists as a source, obs-websocket will", "= None self.datain['transitions'] = None def getCurrentTransition(self): return self.datain['current-transition'] def", "the scene. \"\"\" def __init__(self, items, scene=None): Baserequests.__init__(self) self.name =", "of this type should not be fully duplicated *types.*.caps.doNotSelfMonitor* type:", "Type of the specified source. Useful for type-checking to avoid", "Object Source type capabilities *types.*.caps.isAsync* type: Boolean True if source", "= filterEnabled class GetAudioMonitorType(Baserequests): \"\"\"Get the audio monitoring type of", "String The password to use when accessing the streaming server.", "server. *settings.username* type: String The username to use when accessing", ":Returns: *sourceName* type: String Source name *sourceType* type: String Type", "(optional) Chat log lines. *color* type: int (optional) Text color.", "type: String The username to use when accessing the streaming", "name and source items. :Returns: *name* type: String Name of", "Source kind, Eg. `vlc_source`. *sceneName* type: String Scene to add", "Object Holds data for the font. Ex: `\"font\": { \"face\":", "*sources.*.type* type: String Source type. Value is one of the", "collection. :Arguments: *sc_name* type: String Name of the desired scene", "self.name = 'SetStreamSettings' self.dataout['type'] = type self.dataout['settings'] = settings self.dataout['save']", "type: boolean (optional) Extents wrap. *extents_cx* type: int (optional) Extents", "None self.datain['height'] = None self.datain['parentGroupName'] = None self.datain['groupChildren'] = None", "__init__(self, hotkeyName): Baserequests.__init__(self) self.name = 'TriggerHotkeyByName' self.dataout['hotkeyName'] = hotkeyName class", "type: String Image Data URI (if `embedPictureFormat` was specified in", "opacity (0-100). *chatlog* type: boolean (optional) Chat log. *chatlog_lines* type:", "type: boolean Read text from the specified file. *log_mode* type:", "`error` if Studio Mode is not enabled. :Arguments: *scene_name* type:", "item. Coordinates are relative to the item's parent (the scene", "None self.datain['sourceSettings'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceType'] = sourceType", "type: int Outline size. *outline_opacity* type: int Outline opacity (0-100).", "status (enabled or not) *type* type: String Filter type *name*", "the item in degrees around the point of alignment. *scale.x*", "the given type (usually 'rtmp_custom' or 'rtmp_common'). If the currently", ":Returns: *name* type: String Source name. *volume* type: double Volume", "outline=None, text=None, text_file=None, word_wrap=None): Baserequests.__init__(self) self.name = 'SetTextFreetype2Properties' self.dataout['source'] =", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopRecording' class PauseRecording(Baserequests): \"\"\"Pause", "self.datain['log_mode'] = None self.datain['outline'] = None self.datain['text'] = None self.datain['text_file']", "String Source name. *sourceKind* type: String Source kind, Eg. `vlc_source`.", "Name of the filter to reorder *movementType* type: String How", "the filter is added *filterName* type: String Name of the", "def getOutline_size(self): return self.datain['outline_size'] def getOutline_opacity(self): return self.datain['outline_opacity'] def getText(self):", "to disable). *drop_shadow* type: boolean (optional) Drop shadow. *font* type:", "String (optional) Text vertical alignment (\"top\", \"center\", \"bottom\"). *vertical* type:", "\"\"\"List the media state of all media sources (vlc and", "source self.dataout['mute'] = mute class ToggleMute(Baserequests): \"\"\"Inverts the mute status", "of the scene where the new item was created *item*", "self.dataout['extents_cx'] = extents_cx self.dataout['extents_cy'] = extents_cy self.dataout['file'] = file self.dataout['read_from_file']", "data): Baserequests.__init__(self) self.name = 'BroadcastCustomMessage' self.dataout['realm'] = realm self.dataout['data'] =", "self.datain['muted'] = None self.dataout['source'] = source self.dataout['useDecibel'] = useDecibel def", ":Arguments: *source* type: String Name of the source. *align* type:", "'GetCurrentSceneCollection' self.datain['sc-name'] = None def getScName(self): return self.datain['sc-name'] class ListSceneCollections(Baserequests):", "color. *bk_opacity* type: int Background opacity (0-100). *chatlog* type: boolean", "source. *desktop_2* type: String (optional) Name of the second Desktop", "to switch to. *transitionName* type: String Name of the transition", "self.dataout['filterName'] = filterName self.dataout['filterSettings'] = filterSettings class SetSourceFilterVisibility(Baserequests): \"\"\"Change the", "= source self.dataout['align'] = align self.dataout['bk_color'] = bk_color self.dataout['bk_opacity'] =", "Replay Buffer\" hotkey. Will return an `error` if the Replay", "Baserequests.__init__(self) self.name = 'SetFilenameFormatting' self.dataout['filename-formatting'] = filename_formatting class GetFilenameFormatting(Baserequests): \"\"\"Get", "*position.y* type: double (optional) The new y position of the", "def getWidth(self): return self.datain['width'] def getHeight(self): return self.datain['height'] def getFps(self):", "sources *mediaSources.*.sourceName* type: String Unique source name *mediaSources.*.sourceKind* type: String", "type: boolean (optional) Drop shadow. *font* type: Object (optional) Holds", "Source name. :Returns: *name* type: String Source name. *offset* type:", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentTransition' self.datain['name'] = None", "data \"\"\" def __init__(self, realm, data): Baserequests.__init__(self) self.name = 'BroadcastCustomMessage'", "= sourceName self.dataout['sourceType'] = sourceType def getSourceName(self): return self.datain['sourceName'] def", "the bounding box. \"\"\" def __init__(self, item, scene_name=None, position=None, rotation=None,", "boolean (optional) Output volume in decibels of attenuation instead of", "double Width scale factor. *y_scale* type: double Height scale factor.", "# (Generated on 2020-12-20 18:26:33.661372) # from .base_classes import Baserequests", "\"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int Alignment", "(optional) Read text from the specified file. *font* type: Object", "collection. :Returns: *sc_name* type: String Name of the currently active", "cy. *file* type: String File path name. *read_from_file* type: boolean", "int (optional) Font text size. *font.style* type: String (optional) Font", "self.datain['sourceType'] = None self.datain['sourceSettings'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceType']", "= None def getName(self): return self.datain['name'] def getSources(self): return self.datain['sources']", "is not active or already paused. \"\"\" def __init__(self): Baserequests.__init__(self)", "'TriggerHotkeyByName' self.dataout['hotkeyName'] = hotkeyName class TriggerHotkeyBySequence(Baserequests): \"\"\"Executes hotkey routine, identified", "`false`.* \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ReleaseTBar' class SetTBarPosition(Baserequests):", "supported. :Arguments: *duration* type: int Desired duration of the transition", "scaling. *crop.bottom* type: int The number of pixels cropped off", "this source type *types.*.caps* type: Object Source type capabilities *types.*.caps.isAsync*", "'GetStats' self.datain['stats'] = None def getStats(self): return self.datain['stats'] class BroadcastCustomMessage(Baserequests):", "Object (optional) Settings for the stream. *stream.settings.server* type: String (optional)", "None self.datain['log_mode'] = None self.datain['outline'] = None self.datain['text'] = None", "the current playing state of a media source. Supports ffmpeg", "word_wrap class GetBrowserSourceProperties(Baserequests): \"\"\"Get current properties for a Browser Source.", "its current position, 'false' allows movement. *bounds.type* type: String (optional)", "type: String ID if the scene item's source. For example", "type: int Background color. *bk_opacity* type: int Background opacity (0-100).", "of children (if this item is a group) \"\"\" def", "\"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'StopMedia' self.dataout['sourceName'] =", "list of objects with name and/or id specified. Id preferred", "= None def getAuthRequired(self): return self.datain['authRequired'] def getChallenge(self): return self.datain['challenge']", "GetFilenameFormatting(Baserequests): \"\"\"Get the filename formatting string :Returns: *filename_formatting* type: String", "Unique source name *sources.*.typeId* type: String Non-unique source internal type", "int (optional) Id of a specific scene item. Unique on", "self.datain['streaming'] def getRecording(self): return self.datain['recording'] def getStreamTimecode(self): return self.datain['stream-timecode'] def", "= None self.datain['css'] = None self.datain['width'] = None self.datain['height'] =", "type: int (optional) Transition duration (in milliseconds) if supported by", "self.dataout['left'] = left self.dataout['right'] = right self.dataout['scene-name'] = scene_name class", "= outline self.dataout['outline_color'] = outline_color self.dataout['outline_size'] = outline_size self.dataout['outline_opacity'] =", "*profiles* type: Array<Object> List of available profiles. *profiles.*.profile_name* type: String", "*transitions* type: Array<Object> List of transitions. *transitions.*.name* type: String Name", "class SetCurrentTransition(Baserequests): \"\"\"Set the active transition. :Arguments: *transition_name* type: String", "self.datain['name'] def getSources(self): return self.datain['sources'] class GetSceneList(Baserequests): \"\"\"Get a list", "or 2=Right, and 4=Top or 8=Bottom, or omit to center", "= 'GetAudioMonitorType' self.datain['monitorType'] = None self.dataout['sourceName'] = sourceName def getMonitorType(self):", "*url* type: String (optional) Url. *css* type: String (optional) CSS", "= render self.dataout['scene-name'] = scene_name class SetSceneItemPosition(Baserequests): \"\"\"Sets the coordinates", "Chat log. *outline* type: boolean Outline. *text* type: String Text", "= None self.datain['text_file'] = None self.datain['word_wrap'] = None self.dataout['source'] =", "color. *gradient_dir* type: float Gradient direction. *gradient_opacity* type: int Gradient", "def getRecFolder(self): return self.datain['rec-folder'] class GetReplayBufferStatus(Baserequests): \"\"\"Get the status of", "name. :Returns: *source* type: String Source name *color1* type: int", "None def getProfiles(self): return self.datain['profiles'] class GetRecordingStatus(Baserequests): \"\"\"Get current recording", "of the projector window (only if monitor is -1). Encoded", "positioning) :Arguments: *sourceName* type: String Name of the source to", "class StopReplayBuffer(Baserequests): \"\"\"Stop recording into the Replay Buffer. Will return", "None self.datain['text'] = None self.datain['valign'] = None self.datain['vertical'] = None", "parent (the scene or group it belongs to). :Arguments: *scene_name*", "if monitor is -1). Encoded in Base64 using [Qt's geometry", "int Gradient opacity (0-100). *outline* type: boolean Outline. *outline_color* type:", "'NextMedia' self.dataout['sourceName'] = sourceName class PreviousMedia(Baserequests): \"\"\"Go to the previous", "list of the current profile's scenes (See [GetCurrentScene](#getcurrentscene) for more", "offset. Supports ffmpeg and vlc media sources (as of OBS", "__init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetSourceFilters' self.datain['filters'] = None self.dataout['sourceName']", "__init__(self, scene_name): Baserequests.__init__(self) self.name = 'SetPreviewScene' self.dataout['scene-name'] = scene_name class", "\"\"\" If your code needs to perform multiple successive T-Bar", "field is an object) *position.x* type: double (optional) The new", "self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName def getEnabled(self): return self.datain['enabled']", "Baserequests.__init__(self) self.name = 'StopMedia' self.dataout['sourceName'] = sourceName class NextMedia(Baserequests): \"\"\"Skip", "the horizontal scaling factor) *height* type: double Scene item height", "self.datain['color'] = None self.datain['extents'] = None self.datain['extents_cx'] = None self.datain['extents_cy']", "The media state of the provided source. States: `none`, `playing`,", "(Optional) Name of the source or scene to be displayed", "when registering the hotkey (e.g. \"ReplayBuffer.Save\") \"\"\" def __init__(self, hotkeyName):", "class GetRecordingStatus(Baserequests): \"\"\"Get current recording status. :Returns: *isRecording* type: boolean", "None self.datain['font'] = None self.datain['from_file'] = None self.datain['log_mode'] = None", "to the current scene. *toScene* type: String (optional) Name of", "scene_name self.dataout['position'] = position self.dataout['rotation'] = rotation self.dataout['scale'] = scale", "authentication is required. If so, returns authentication parameters `challenge` and", "self.datain['scenes'] = None def getCurrentScene(self): return self.datain['current-scene'] def getScenes(self): return", "Item name (if the `item` field is an object) *item.id*", "item, scene_name=None, position=None, rotation=None, scale=None, crop=None, visible=None, locked=None, bounds=None): Baserequests.__init__(self)", "Unique name of the hotkey, as defined when registering the", "SetHeartbeat(Baserequests): \"\"\"Enable/disable sending of the Heartbeat event :Arguments: *enable* type:", "'TransitionToProgram' self.dataout['with-transition'] = with_transition class EnableStudioMode(Baserequests): \"\"\"Enables Studio Mode. \"\"\"", "Current recording status. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetReplayBufferStatus'", "scaling. *visible* type: bool If the source is visible. *muted*", "create. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'CreateScene' self.dataout['sceneName']", "String (optional) Name of the scene to copy the item", "String Name of the requested (or current) scene *sceneItems* type:", "css self.dataout['width'] = width self.dataout['height'] = height self.dataout['fps'] = fps", "String Source name. :Returns: *mediaState* type: String The media state", "Mic/Aux input source. *mic_2* type: String (optional) Name of the", "width (0 to disable). *drop_shadow* type: boolean Drop shadow. *font*", "Audio capture source. *mic_1* type: String (optional) Name of the", "return self.datain['mediaDuration'] class GetMediaTime(Baserequests): \"\"\"Get the current timestamp of media", "= offset class GetSyncOffset(Baserequests): \"\"\"Get the audio sync offset of", "status of a specified source. :Arguments: *sourceName* type: String Source", "Name of the first Desktop Audio capture source. *desktop_2* type:", "getMonitorType(self): return self.datain['monitorType'] class SetAudioMonitorType(Baserequests): \"\"\"Set the audio monitoring type", "note: if `SetRecordingFolder` is called while a recording is in", "int (optional) Extents cx. *extents_cy* type: int (optional) Extents cy.", "of OBS v25.0.8) :Arguments: *sourceName* type: String Source name. \"\"\"", "= None self.dataout['sourceName'] = sourceName def getTimestamp(self): return self.datain['timestamp'] class", "stream configuration. Please note: these won't be saved to OBS'", "`error` if the Replay Buffer is already active or if", "String Type. Value is one of the following: \"input\", \"filter\",", ":Arguments: *sourceName* type: String Name of the source from which", "Object Scene Item to duplicate from the source scene (required)", "type: String Display name of the source type *types.*.type* type:", "filters for the specified source *filters.*.enabled* type: Boolean Filter status", "GetStreamSettings(Baserequests): \"\"\"Get the current streaming server settings. :Returns: *type* type:", "source before scaling. *visible* type: bool (optional) The new visibility", ":Arguments: *type* type: String (Optional) Type of projector: `Preview` (default),", "both is acceptable). *item.id* type: int Scene Item ID. \"\"\"", "scaling. *crop.right* type: int The number of pixels cropped off", "*align* type: String Text Alignment (\"left\", \"center\", \"right\"). *bk_color* type:", "getColor2(self): return self.datain['color2'] def getCustom_width(self): return self.datain['custom_width'] def getDrop_shadow(self): return", "__init__(self): Baserequests.__init__(self) self.name = 'GetStats' self.datain['stats'] = None def getStats(self):", "self.datain['is_local_file'] def getLocal_file(self): return self.datain['local_file'] def getUrl(self): return self.datain['url'] def", "type: String Name of the selected transition. *duration* type: int", "def getName(self): return self.datain['name'] def getMuted(self): return self.datain['muted'] class SetMute(Baserequests):", "item ID *item.name* type: String New item name \"\"\" def", "self.name = 'GetAudioActive' self.datain['audioActive'] = None self.dataout['sourceName'] = sourceName def", "return self.datain['name'] def getOffset(self): return self.datain['offset'] class GetSourceSettings(Baserequests): \"\"\"Get settings", "Background color. *bk_opacity* type: int Background opacity (0-100). *chatlog* type:", "other value supported by Qt's Image module) *saveToFilePath* type: String", "getIs_local_file(self): return self.datain['is_local_file'] def getLocal_file(self): return self.datain['local_file'] def getUrl(self): return", "be used when connecting to the streaming server. *settings.username* type:", "(optional) The new locked status of the source. 'true' keeps", "setVisible def getItemId(self): return self.datain['itemId'] class GetSourcesList(Baserequests): \"\"\"List all sources", "of the source. *rotation* type: double (optional) The new clockwise", "OBS' settings. Setting this hotkey is mandatory, even when triggering", "getColor(self): return self.datain['color'] def getExtents(self): return self.datain['extents'] def getExtents_cx(self): return", "*groupChildren* type: Array<SceneItemTransform> (optional) List of children (if this item", "path (file extension included) where the captured image is to", "name. *monitorType* type: String The monitor type to use. Options:", "String (optional) Source name. Note that, since scenes are also", "self.name = 'RemoveFilterFromSource' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName class", "in the chain (absolute index positioning) :Arguments: *sourceName* type: String", "= setVisible def getItemId(self): return self.datain['itemId'] class DuplicateSceneItem(Baserequests): \"\"\"Duplicates a", ":Returns: *filename_formatting* type: String Current filename formatting string. \"\"\" def", "\"\"\" def __init__(self, sceneName=None): Baserequests.__init__(self) self.name = 'GetSceneItemList' self.datain['sceneName'] =", "shadow. *font* type: Object (optional) Holds data for the font.", "be added *setVisible* type: boolean Whether to make the sceneitem", "name of the scene to preview. \"\"\" def __init__(self, scene_name):", "\"\"\" def __init__(self, sourceName, filterName): Baserequests.__init__(self) self.name = 'GetSourceFilterInfo' self.datain['enabled']", "def getSourceSettings(self): return self.datain['sourceSettings'] class SetSourceSettings(Baserequests): \"\"\"Set settings of the", "return an `error` if the Replay Buffer is not active.", "profiles. *profiles.*.profile_name* type: String Filter name \"\"\" def __init__(self): Baserequests.__init__(self)", "type: String Output name \"\"\" def __init__(self, outputName): Baserequests.__init__(self) self.name", "\"bottom\"). *vertical* type: boolean Vertical text enabled. \"\"\" def __init__(self,", ":Arguments: *outputName* type: String Output name *force* type: boolean (optional)", "play, `true` for pause. \"\"\" def __init__(self, sourceName, playPause): Baserequests.__init__(self)", "item belongs to a group) *groupChildren* type: Array<SceneItemTransform> (optional) List", "def getColorSpace(self): return self.datain['colorSpace'] def getColorRange(self): return self.datain['colorRange'] class OpenProjector(Baserequests):", "class GetMute(Baserequests): \"\"\"Get the mute status of a specified source.", "is enabled, the username for the streaming server. Ignored if", "in the scene. \"\"\" def __init__(self, sourceName, sourceKind, sceneName, sourceSettings=None,", "'MoveSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['movementType'] = movementType", "outputs is an experimental feature of obs-websocket. Some plugins which", ":Arguments: *sourceName* type: String Source name. :Returns: *monitorType* type: String", "\"\"\" def __init__(self, transitionName): Baserequests.__init__(self) self.name = 'GetTransitionSettings' self.datain['transitionSettings'] =", "None self.datain['muted'] = None self.dataout['source'] = source def getName(self): return", "boolean (optional) Set the created SceneItem as visible or not.", "mandatory, even when triggering saves only through obs-websocket. \"\"\" def", "type: String Name of the requested (or current) scene *sceneItems*", "window or create a projector on a monitor. Requires OBS", "'SaveStreamSettings' class SendCaptions(Baserequests): \"\"\"Send the provided text as embedded CEA-608", "current scene transition override. :Arguments: *sceneName* type: String Name of", "String (optional) The publish key. *settings.use_auth* type: boolean (optional) Indicates", "Array<Object> Array of sources *sources.*.name* type: String Unique source name", "perfect. The processing rate of this request has also not", "as defined when registering the hotkey (e.g. \"ReplayBuffer.Save\") \"\"\" def", "Pixel position of the right of the source item. \"\"\"", "getTransitionName(self): return self.datain['transitionName'] def getTransitionDuration(self): return self.datain['transitionDuration'] class GetStreamingStatus(Baserequests): \"\"\"Get", "def getCurrentScene(self): return self.datain['current-scene'] def getScenes(self): return self.datain['scenes'] class CreateScene(Baserequests):", "(Optional) Optional key modifiers object. False entries can be ommitted", "not enabled. :Arguments: *scene_name* type: String The name of the", "getSources(self): return self.datain['sources'] class GetSourceTypesList(Baserequests): \"\"\"Get a list of all", "`error` if the Replay Buffer is not active. \"\"\" def", "save the contents of the Replay Buffer to disk. This", "*font.style* type: String (optional) Font Style (unknown function). *from_file* type:", "int (optional) Gradient opacity (0-100). *outline* type: boolean (optional) Outline.", "sourceName def getFilters(self): return self.datain['filters'] class GetSourceFilterInfo(Baserequests): \"\"\"List filters applied", "return self.datain['types'] class GetVolume(Baserequests): \"\"\"Get the volume of the specified", "self.dataout['text_file'] = text_file self.dataout['word_wrap'] = word_wrap class GetBrowserSourceProperties(Baserequests): \"\"\"Get current", "in milliseconds. Supports ffmpeg and vlc media sources (as of", "def getGradient_opacity(self): return self.datain['gradient_opacity'] def getOutline(self): return self.datain['outline'] def getOutline_color(self):", "self.datain['sourceHeight'] def getWidth(self): return self.datain['width'] def getHeight(self): return self.datain['height'] def", "__init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetAudioActive' self.datain['audioActive'] = None self.dataout['sourceName']", "None self.datain['align'] = None self.datain['bk_color'] = None self.datain['bk_opacity'] = None", "Note: Transition returns 1.0 when not active. \"\"\" def __init__(self):", "self.datain['width'] def getHeight(self): return self.datain['height'] def getFps(self): return self.datain['fps'] def", "included) where the captured image is to be saved. Can", "lines. *color* type: int (optional) Text color. *extents* type: boolean", "= data class GetVideoInfo(Baserequests): \"\"\"Get basic OBS video information :Returns:", "if there is no current override and this value is", "int (optional) Chat log lines. *color* type: int (optional) Text", "started (only present if currently streaming). *rec_timecode* type: String (optional)", "name of the transition. \"\"\" def __init__(self, transition_name): Baserequests.__init__(self) self.name", "sources. Will return an `error` if Studio Mode is not", "def __init__(self, sourceName, filterName, movementType): Baserequests.__init__(self) self.name = 'MoveSourceFilter' self.dataout['sourceName']", "getColorRange(self): return self.datain['colorRange'] class OpenProjector(Baserequests): \"\"\"Open a projector window or", "second Desktop Audio capture source. *mic_1* type: String (optional) Name", "unique if no scene items share sources within the scene.", "enabled. :Arguments: *with_transition* type: Object (optional) Change the active transition", "be saved. Can be in a format different from `pictureFormat`.", "StopStreaming(Baserequests): \"\"\"Stop streaming. Will return an `error` if streaming is", "*timestamp* type: int The time in milliseconds since the start", "String The publish URL. *settings.key* type: String The publish key", "class AddFilterToSource(Baserequests): \"\"\"Add a new filter to a source. Available", "Source name *color1* type: int Gradient top color. *color2* type:", "transition to use. *transitionDuration* type: int (Optional) Duration in milliseconds", "type: String Name of the filter to reorder *movementType* type:", "(See [GetCurrentScene](#getcurrentscene) for more information). \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "*source* type: String Source name *color1* type: int Gradient top", "error if recording is not active or not paused. \"\"\"", "self.dataout['source'] = source self.dataout['render'] = render self.dataout['scene-name'] = scene_name class", "Call `ReleaseTBar` manually if you set `release` to false. Defaults", "String file path. *url* type: String Url. *css* type: String", "between -1 and 100 to write the image with. -1", "type, monitor, geometry, name): Baserequests.__init__(self) self.name = 'OpenProjector' self.dataout['type'] =", "an `error` if the Replay Buffer is already active or", "settings in response. If 'type' is different than the current", "server. *settings.username* type: String (optional) The username for the streaming", ":Arguments: *outputName* type: String Output name \"\"\" def __init__(self, outputName):", "String (optional) Name of the second Desktop Audio capture source.", "to the item's parent (the scene or group it belongs", "type: String Name of the currently active scene. *sources* type:", "self.dataout['item'] = item self.dataout['x-scale'] = x_scale self.dataout['y-scale'] = y_scale self.dataout['rotation']", "(required) *item.name* type: String Scene Item name (prefer `id`, including", "UI if there is no current override and this value", "*mediaDuration* type: int The total length of media in milliseconds..", "self.name = 'ResetSceneItem' self.dataout['item'] = item self.dataout['scene-name'] = scene_name class", "self.datain['is_local_file'] = None self.datain['local_file'] = None self.datain['url'] = None self.datain['css']", "*types.*.defaultSettings* type: Object Default settings of this source type *types.*.caps*", "current recording state). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopRecording'", "x, y, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemPosition' self.dataout['item'] = item", "*sourceSettings* type: Object Source settings (varies between source types, may", "= None self.datain['chatlog'] = None self.datain['chatlog_lines'] = None self.datain['color'] =", "to remove \"\"\" def __init__(self, sourceName, filterName): Baserequests.__init__(self) self.name =", "type: String Scene Item name. *render* type: boolean true =", "String Output name :Returns: *outputInfo* type: Output Output info \"\"\"", "= item self.dataout['scene'] = scene class AddSceneItem(Baserequests): \"\"\"Creates a scene", "Baserequests.__init__(self) self.name = 'Authenticate' self.dataout['auth'] = auth class SetHeartbeat(Baserequests): \"\"\"Enable/disable", "None self.dataout['sourceName'] = sourceName def getTimestamp(self): return self.datain['timestamp'] class SetMediaTime(Baserequests):", "type-checking if you expect a specific settings schema. :Returns: *sourceName*", "self.datain['fps'] def getShutdown(self): return self.datain['shutdown'] class SetBrowserSourceProperties(Baserequests): \"\"\"Set current properties", "Milliseconds to set the timestamp to. \"\"\" def __init__(self, sourceName,", "\"\"\"Disables Studio Mode. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'DisableStudioMode'", "String Font Style (unknown function). *gradient* type: boolean Gradient enabled.", "current state of the replay buffer). \"\"\" def __init__(self): Baserequests.__init__(self)", "Identifier to be choosen by the client *data* type: Object", "type: Array<SceneItem> \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetPreviewScene' self.datain['name']", "filter in the chain (relative positioning) :Arguments: *sourceName* type: String", "text enabled. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetTextGDIPlusProperties'", "__init__(self, realm, data): Baserequests.__init__(self) self.name = 'BroadcastCustomMessage' self.dataout['realm'] = realm", "the audio's active status of a specified source. :Arguments: *sourceName*", "getSourceType(self): return self.datain['sourceType'] def getSourceSettings(self): return self.datain['sourceSettings'] class GetTextGDIPlusProperties(Baserequests): \"\"\"Get", "*source* type: String Name of the source. *is_local_file* type: boolean", "Name of the filter to remove \"\"\" def __init__(self, sourceName,", "type: String (optional) Text content to be displayed. *text_file* type:", "String (optional) Font Style (unknown function). *gradient* type: boolean (optional)", "class SetCurrentSceneCollection(Baserequests): \"\"\"Change the active scene collection. :Arguments: *sc_name* type:", "animation/interaction is over. :Arguments: *position* type: double T-Bar position. This", "type-checking to avoid settings a set of settings incompatible with", "def getMic1(self): return self.datain['mic-1'] def getMic2(self): return self.datain['mic-2'] def getMic3(self):", "be between `0.0` and `20.0` for mul, and under 26.0", "in use. *local_file* type: String file path. *url* type: String", "the current recording (if paused). Returns an error if recording", "= None self.dataout['source'] = source self.dataout['useDecibel'] = useDecibel def getName(self):", "String Source name. *newName* type: String New source name. \"\"\"", "None self.datain['desktop-2'] = None self.datain['mic-1'] = None self.datain['mic-2'] = None", "= y_scale self.dataout['rotation'] = rotation self.dataout['scene-name'] = scene_name class SetSceneItemCrop(Baserequests):", "the left of the source item. *right* type: int Pixel", "no current override and this value is not given. \"\"\"", "boolean Indicates whether authentication should be used when connecting to", "set in OBS' settings. Setting this hotkey is mandatory, even", "currently recording). *preview_only* type: boolean Always false. Retrocompatibility with OBSRemote.", "this request has also not been tested. :Arguments: *sourceName* type:", "OBS v25.0.8) :Arguments: *sourceName* type: String Source name. :Returns: *mediaState*", "*types.*.displayName* type: String Display name of the source type *types.*.type*", "total duration can be off by upwards of 50ms. :Arguments:", "= 'DisableStudioMode' class ToggleStudioMode(Baserequests): \"\"\"Toggles Studio Mode (depending on the", "of the Heartbeat event :Arguments: *enable* type: boolean Starts/Stops emitting", "sources of this type is possible *types.*.caps.isComposite* type: Boolean True", "drop_shadow self.dataout['font'] = font self.dataout['from_file'] = from_file self.dataout['log_mode'] = log_mode", "the updated settings in response. If 'type' is different than", "current timestamp of media in milliseconds. Supports ffmpeg and vlc", "Desired duration of the transition (in milliseconds). \"\"\" def __init__(self,", "return self.datain['file'] def getRead_from_file(self): return self.datain['read_from_file'] def getFont(self): return self.datain['font']", "transitionName): Baserequests.__init__(self) self.name = 'GetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName'] =", "value must be between 0.0 and 1.0. *release* type: boolean", "class GetAuthRequired(Baserequests): \"\"\"Tells the client if authentication is required. If", "self.dataout['offset'] = offset class GetSyncOffset(Baserequests): \"\"\"Get the audio sync offset", "getScName(self): return self.datain['sc-name'] class ListSceneCollections(Baserequests): \"\"\"List available scene collections :Returns:", "*fps* type: double Frames rendered per second *videoFormat* type: String", "duration of the currently selected transition if supported. :Arguments: *duration*", "def __init__(self, auth): Baserequests.__init__(self) self.name = 'Authenticate' self.dataout['auth'] = auth", "pause or play the source. `false` for play, `true` for", "*monitor* type: int (Optional) Monitor to open the projector on.", "GetStats(Baserequests): \"\"\"Get OBS stats (almost the same info as provided", "the specified source. :Arguments: *sourceName* type: String Source name. *monitorType*", "their settings properties are available from `GetSourceTypesList`. :Arguments: *sourceName* type:", "of scene items *sceneItems.*.itemId* type: int Unique item id of", "scene. \"\"\" def __init__(self, sourceName, sourceKind, sceneName, sourceSettings=None, setVisible=None): Baserequests.__init__(self)", "type: Array<Object> Array of source types *types.*.typeId* type: String Non-unique", "return self.datain['obs-studio-version'] def getAvailableRequests(self): return self.datain['available-requests'] def getSupportedImageExportFormats(self): return self.datain['supported-image-export-formats']", "name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'RestartMedia' self.dataout['sourceName']", "\"up\", \"down\", \"top\" or \"bottom\". \"\"\" def __init__(self, sourceName, filterName,", "smallest file/most compression, 100 is largest file/least compression. Varies with", "position of the source. *position.y* type: double (optional) The new", "OBS Studio program version. *available_requests* type: String List of available", "type: String Name of the source from which the specified", "height self.dataout['fps'] = fps self.dataout['shutdown'] = shutdown self.dataout['render'] = render", "self.name = 'GetOutputInfo' self.datain['outputInfo'] = None self.dataout['outputName'] = outputName def", "type: boolean true = shown ; false = hidden \"\"\"", "Unique on a scene by scene basis. *items.*.name* type: String", "(varies between source types, may require some probing around). :Returns:", "Heartbeat event :Arguments: *enable* type: boolean Starts/Stops emitting heartbeat messages", "'GetPreviewScene' self.datain['name'] = None self.datain['sources'] = None def getName(self): return", "String Scene Item name. *render* type: boolean true = shown", "string to set. \"\"\" def __init__(self, filename_formatting): Baserequests.__init__(self) self.name =", "SendCaptions(Baserequests): \"\"\"Send the provided text as embedded CEA-608 caption data.", "one or more sub-sources *types.*.caps.doNotDuplicate* type: Boolean True if sources", "Updated source settings \"\"\" def __init__(self, sourceName, sourceSettings, sourceType=None): Baserequests.__init__(self)", "int Background opacity (0-100). *chatlog* type: boolean Chat log. *chatlog_lines*", "String Path of the recording folder. \"\"\" def __init__(self, rec_folder):", "\"\"\"Duplicates a scene item. :Arguments: *fromScene* type: String (optional) Name", "from a source :Arguments: *sourceName* type: String Name of the", "Boolean True if sources of this type should not be", "Integer Desired position of the filter in the chain \"\"\"", "source, align=None, bk_color=None, bk_opacity=None, chatlog=None, chatlog_lines=None, color=None, extents=None, extents_cx=None, extents_cy=None,", "def getVolume(self): return self.datain['volume'] def getMuted(self): return self.datain['muted'] class SetVolume(Baserequests):", "def __init__(self, source, render, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemRender' self.dataout['source']", "= force class SetCurrentProfile(Baserequests): \"\"\"Set the currently active profile. :Arguments:", "def __init__(self): Baserequests.__init__(self) self.name = 'EnableStudioMode' class DisableStudioMode(Baserequests): \"\"\"Disables Studio", "scene items from. Defaults to the current scene if not", "Default response uses mul format, NOT SLIDER PERCENTAGE. :Arguments: *source*", "all scene items in a scene. :Arguments: *sceneName* type: String", "or in response to a user moving a T-Bar control", "scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemPosition' self.dataout['item'] = item self.dataout['x'] =", "= sourceType def getSourceName(self): return self.datain['sourceName'] def getSourceType(self): return self.datain['sourceType']", "String Source name *img* type: String Image Data URI (if", "after moving it). *YOU MUST CALL THIS if you called", "*mediaSources.*.mediaState* type: String The current state of media for that", "is currently enabled. :Returns: *studio_mode* type: boolean Indicates if Studio", "is an object) *item.id* type: int (optional) Scene Item ID", "to OBS' configuration. *stream.type* type: String (optional) If specified ensures", "\"\"\"Stop a media source. Supports ffmpeg and vlc media sources", "The new bounds type of the source. Can be \"OBS_BOUNDS_STRETCH\",", "scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemTransform' self.dataout['item'] = item self.dataout['x-scale'] =", "Studio Mode. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'DisableStudioMode' class", "Read text from the specified file. *font* type: Object Holds", ":Arguments: *transitionName* type: String Transition name *transitionSettings* type: Object Transition", "Item name (prefer `id`, including both is acceptable). *item.id* type:", "of the stream. *settings.use_auth* type: boolean Indicates whether authentication should", "size *fps* type: double Frames rendered per second *videoFormat* type:", "return an error. :Arguments: *sourceName* type: String Source name. *newName*", ":Returns: *monitorType* type: String The monitor type in use. Options:", "to move the filter around in the source's filter chain.", "also provide a scene name. If not provided, the currently", "= 'StartRecording' class StopRecording(Baserequests): \"\"\"Stop recording. Will return an `error`", "SetCurrentSceneCollection(Baserequests): \"\"\"Change the active scene collection. :Arguments: *sc_name* type: String", "type: String Captions text \"\"\" def __init__(self, text): Baserequests.__init__(self) self.name", "getSourceSettings(self): return self.datain['sourceSettings'] class GetTextGDIPlusProperties(Baserequests): \"\"\"Get the current properties of", "in milliseconds since the start of the media. \"\"\" def", "String Source name. *mute* type: boolean Desired mute status. \"\"\"", "filterSettings): Baserequests.__init__(self) self.name = 'SetSourceFilterSettings' self.dataout['sourceName'] = sourceName self.dataout['filterName'] =", "self.datain['gradient'] = None self.datain['gradient_color'] = None self.datain['gradient_dir'] = None self.datain['gradient_opacity']", "new x position of the source. *position.y* type: double (optional)", "8=Bottom, or omit to center on that axis. *rotation* type:", "y_scale, rotation, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemTransform' self.dataout['item'] = item", "Source name. *sourceType* type: String (optional) Type of the specified", "of all scene items in a scene. :Arguments: *sceneName* type:", "this field is a string) or specification (if it is", "'CreateScene' self.dataout['sceneName'] = sceneName class ReorderSceneItems(Baserequests): \"\"\"Changes the order of", "type: int The point on the source that the item", "= filename_formatting class GetFilenameFormatting(Baserequests): \"\"\"Get the filename formatting string :Returns:", "type in use. Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self,", "Volume of the source. Between `0.0` and `20.0` if using", "the source before scaling. *crop.left* type: int The number of", "item self.dataout['fromScene'] = fromScene self.dataout['toScene'] = toScene def getScene(self): return", "\"\"\" def __init__(self, transitionName, transitionSettings): Baserequests.__init__(self) self.name = 'SetTransitionSettings' self.datain['transitionSettings']", "*locked* type: bool (optional) The new locked status of the", "a list of scenes in the currently active profile. :Returns:", "error if recording is not active or already paused. \"\"\"", "item's source. Either `input`, `group`, or `scene` \"\"\" def __init__(self,", "module) *saveToFilePath* type: String (optional) Full file path (file extension", "a specified source item. :Arguments: *scene_name* type: String (optional) Name", "item, scene_name=None): Baserequests.__init__(self) self.name = 'GetSceneItemProperties' self.datain['name'] = None self.datain['itemId']", "type: String Filter type *name* type: String Filter name *settings*", "sceneName): Baserequests.__init__(self) self.name = 'CreateScene' self.dataout['sceneName'] = sceneName class ReorderSceneItems(Baserequests):", "None self.datain['baseHeight'] = None self.datain['outputWidth'] = None self.datain['outputHeight'] = None", "name. *timeOffset* type: int Millisecond offset (positive or negative) to", "folder. \"\"\" def __init__(self, rec_folder): Baserequests.__init__(self) self.name = 'SetRecordingFolder' self.dataout['rec-folder']", "= sceneName def getSceneName(self): return self.datain['sceneName'] def getSceneItems(self): return self.datain['sceneItems']", "*name* type: String Source name. *volume* type: double Volume of", "*filterSettings* type: Object Filter settings \"\"\" def __init__(self, sourceName, filterName,", "connecting to the streaming server. *stream.settings.username* type: String (optional) If", "color=None, extents=None, extents_cx=None, extents_cy=None, file=None, read_from_file=None, font=None, gradient=None, gradient_color=None, gradient_dir=None,", "Text Freetype 2 source. :Arguments: *source* type: String Source name.", "double Desired volume. Must be between `0.0` and `20.0` for", "boolean (optional) Vertical text enabled. *render* type: boolean (optional) Visibility", "should not be fully duplicated *types.*.caps.doNotSelfMonitor* type: Boolean True if", "getColorSpace(self): return self.datain['colorSpace'] def getColorRange(self): return self.datain['colorRange'] class OpenProjector(Baserequests): \"\"\"Open", "the current transition. :Returns: *position* type: double current transition position.", "internal type (a.k.a `ffmpeg_source` or `vlc_source`) *mediaSources.*.mediaState* type: String The", "(optional) Name of a scene item. Sufficiently unique if no", "more information). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSceneList' self.datain['current-scene']", "button after moving the T-Bar). Call `ReleaseTBar` manually if you", "an experimental feature of obs-websocket. Some plugins which add outputs", "\"\"\"Enables Studio Mode. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'EnableStudioMode'", "supported formats for features that use image export (like the", "self.datain['name'] = None self.datain['volume'] = None self.datain['muted'] = None self.dataout['source']", "the scene to switch to. :Returns: *transitionName* type: String Name", "double Y coordinate. \"\"\" def __init__(self, item, x, y, scene_name=None):", "'SetBrowserSourceProperties' self.dataout['source'] = source self.dataout['is_local_file'] = is_local_file self.dataout['local_file'] = local_file", "Mode (depending on the current state of studio mode). \"\"\"", "self.name = 'RestartMedia' self.dataout['sourceName'] = sourceName class StopMedia(Baserequests): \"\"\"Stop a", "scene item. :Arguments: *scene_name* type: String (optional) Name of the", "formatted as a comma-separated list string \"\"\" def __init__(self): Baserequests.__init__(self)", "play a media source. Supports ffmpeg and vlc media sources", "*font.flags* type: int Font text styling flag. `Bold=1, Italic=2, Bold", "menu. :Returns: *name* type: String Name of the selected transition.", "def __init__(self, source, offset): Baserequests.__init__(self) self.name = 'SetSyncOffset' self.dataout['source'] =", "self.datain['imageFile'] class ListOutputs(Baserequests): \"\"\"List existing outputs :Returns: *outputs* type: Array<Output>", "to inject. *width* type: int (optional) Width. *height* type: int", "Baserequests.__init__(self) self.name = 'PauseRecording' class ResumeRecording(Baserequests): \"\"\"Resume/unpause the current recording", "filterName, movementType): Baserequests.__init__(self) self.name = 'MoveSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName']", "self.dataout['source'] = source self.dataout['offset'] = offset class GetSyncOffset(Baserequests): \"\"\"Get the", "The new locked status of the source. 'true' keeps it", "*item.id* type: int Scene Item ID. :Returns: *scene* type: String", "type: String (optional) Time elapsed since streaming started (only present", "class ResetSceneItem(Baserequests): \"\"\"Reset a scene item. :Arguments: *scene_name* type: String", "def getFilenameFormatting(self): return self.datain['filename-formatting'] class GetStats(Baserequests): \"\"\"Get OBS stats (almost", "150, \"style\": \"\" }` *font.face* type: String Font face. *font.flags*", "= None self.datain['word_wrap'] = None self.dataout['source'] = source def getSource(self):", "type: int Extents cy. *file* type: String File path name.", "if only one of these two parameters is specified. :Arguments:", "class SetPreviewScene(Baserequests): \"\"\"Set the active preview scene. Will return an", "source internal type (a.k.a kind) *sources.*.type* type: String Source type.", "\"\" }` *font.face* type: String (optional) Font face. *font.flags* type:", "\"\"\" def __init__(self, item, scene_name=None, position=None, rotation=None, scale=None, crop=None, visible=None,", "*settings.server* type: String The publish URL. *settings.key* type: String The", "movementType class SetSourceFilterSettings(Baserequests): \"\"\"Update settings of a filter :Arguments: *sourceName*", "font. Ex: `\"font\": { \"face\": \"Arial\", \"flags\": 0, \"size\": 150,", "Baserequests.__init__(self) self.name = 'SetTextFreetype2Properties' self.dataout['source'] = source self.dataout['color1'] = color1", "= item self.dataout['scene-name'] = scene_name class SetSceneItemRender(Baserequests): \"\"\"Show or hide", "point of alignment. *scale.x* type: double The x-scale factor of", "the current scene. *item* type: String Scene Item name. *x_scale*", "= useDecibel class GetMute(Baserequests): \"\"\"Get the mute status of a", "\"\"\"Get the current scene transition override. :Arguments: *sceneName* type: String", "self.datain['scaleType'] = None self.datain['fps'] = None self.datain['videoFormat'] = None self.datain['colorSpace']", "outputs :Returns: *outputs* type: Array<Output> Outputs list \"\"\" def __init__(self):", "def __init__(self, outputName): Baserequests.__init__(self) self.name = 'StartOutput' self.dataout['outputName'] = outputName", "when not visible. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name =", "*extents_cx* type: int (optional) Extents cx. *extents_cy* type: int (optional)", "type: String Url. *css* type: String CSS to inject. *width*", "to be displayed. *valign* type: String Text vertical alignment (\"top\",", "file (if `saveToFilePath` was specified in the request) \"\"\" def", "render class GetTextFreetype2Properties(Baserequests): \"\"\"Get the current properties of a Text", "the source *width* type: double Scene item width (base source", "with image type. *width* type: int (optional) Screenshot width. Defaults", "recording status. :Returns: *isRecording* type: boolean Current recording status. *isRecordingPaused*", "actually supports larger values. *useDecibel* type: boolean (optional) Interperet `volume`", "source. For example `vlc_source` or `image_source` *sceneItems.*.sourceName* type: String Name", "GetTransitionSettings(Baserequests): \"\"\"Get the current settings of a transition :Arguments: *transitionName*", "Audio active status of the source. \"\"\" def __init__(self, sourceName):", "self.name = 'SetHeartbeat' self.dataout['enable'] = enable class SetFilenameFormatting(Baserequests): \"\"\"Set the", "source item belongs to. Defaults to the current scene. *item*", "__init__(self, sourceName, filterName, newIndex): Baserequests.__init__(self) self.name = 'ReorderSourceFilter' self.dataout['sourceName'] =", "transition. *with_transition.duration* type: int (optional) Transition duration (in milliseconds). \"\"\"", "require some probing around). \"\"\" def __init__(self, sourceName, sourceType=None): Baserequests.__init__(self)", "String Source filter name *filterEnabled* type: Boolean New filter state", "scene the scene item belongs to. Defaults to the current", "filterEnabled): Baserequests.__init__(self) self.name = 'SetSourceFilterVisibility' self.dataout['sourceName'] = sourceName self.dataout['filterName'] =", "class GetOutputInfo(Baserequests): \"\"\"Get information about a single output :Arguments: *outputName*", "return self.datain['scene-collections'] class GetSceneItemList(Baserequests): \"\"\"Get a list of all scene", "movement. *bounds.type* type: String (optional) The new bounds type of", "active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopStreaming' class SetStreamSettings(Baserequests):", "self.dataout['gradient_dir'] = gradient_dir self.dataout['gradient_opacity'] = gradient_opacity self.dataout['outline'] = outline self.dataout['outline_color']", "= 'SetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType'] = None self.datain['sourceSettings'] =", "transition. \"\"\" def __init__(self, transition_name): Baserequests.__init__(self) self.name = 'SetCurrentTransition' self.dataout['transition-name']", "a scene to use a specific transition override. :Arguments: *sceneName*", "running OBS instance :Returns: *sources* type: Array<Object> Array of sources", "= sourceName self.dataout['filterName'] = filterName self.dataout['movementType'] = movementType class SetSourceFilterSettings(Baserequests):", "the currently active scene. *sources* type: Array<SceneItem> Ordered list of", "per scene *items.*.id* type: int (optional) Id of a specific", "Baserequests.__init__(self) self.name = 'GetAuthRequired' self.datain['authRequired'] = None self.datain['challenge'] = None", "recording (if paused). Returns an error if recording is not", "GetAudioMonitorType(Baserequests): \"\"\"Get the audio monitoring type of the specified source.", "and source items. :Returns: *name* type: String Name of the", "stream (the same as GetStreamSettings). :Arguments: *type* type: String The", "SetMute(Baserequests): \"\"\"Sets the mute status of a specified source. :Arguments:", "item, x_scale, y_scale, rotation, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemTransform' self.dataout['item']", "streaming status. *recording* type: boolean Current recording status. *stream_timecode* type:", "None self.datain['outline'] = None self.datain['text'] = None self.datain['text_file'] = None", "type: double Height scale factor. *rotation* type: double Source item", "class DuplicateSceneItem(Baserequests): \"\"\"Duplicates a scene item. :Arguments: *fromScene* type: String", "type: boolean Indicates if Studio Mode is enabled. \"\"\" def", "specified source. :Arguments: *sourceName* type: String Source name. :Returns: *audioActive*", "class NextMedia(Baserequests): \"\"\"Skip to the next media item in the", "= top self.dataout['bottom'] = bottom self.dataout['left'] = left self.dataout['right'] =", "or if the \"Save Replay Buffer\" hotkey is not set", "item's parent (the scene or group it belongs to). :Arguments:", "to use when accessing the streaming server. Only present if", "boolean (optional) Extents wrap. *extents_cx* type: int (optional) Extents cx.", "self.datain['duration'] = None def getName(self): return self.datain['name'] def getDuration(self): return", "(optional) Screenshot width. Defaults to the source's base width. *height*", "profile. :Arguments: *profile_name* type: String Name of the desired profile.", "class TriggerHotkeyByName(Baserequests): \"\"\"Executes hotkey routine, identified by hotkey unique name", "*data* type: Object User-defined data \"\"\" def __init__(self, realm, data):", "same info as provided in OBS' stats window) :Returns: *stats*", "factor) *height* type: double Scene item height (base source height", "Name of the scene to create. \"\"\" def __init__(self, sceneName):", "= 'SetBrowserSourceProperties' self.dataout['source'] = source self.dataout['is_local_file'] = is_local_file self.dataout['local_file'] =", "and will be effective on the next recording. :Arguments: *rec_folder*", "transition settings \"\"\" def __init__(self, transitionName): Baserequests.__init__(self) self.name = 'GetTransitionSettings'", "realm, data): Baserequests.__init__(self) self.name = 'BroadcastCustomMessage' self.dataout['realm'] = realm self.dataout['data']", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionList' self.datain['current-transition'] = None", "return self.datain['text_file'] def getWord_wrap(self): return self.datain['word_wrap'] class SetTextFreetype2Properties(Baserequests): \"\"\"Set the", "self.datain['isRecordingPaused'] = None self.datain['recordTimecode'] = None self.datain['recordingFilename'] = None def", "self.dataout['setVisible'] = setVisible def getItemId(self): return self.datain['itemId'] class DuplicateSceneItem(Baserequests): \"\"\"Duplicates", "in the running OBS instance :Returns: *sources* type: Array<Object> Array", "Baserequests.__init__(self) self.name = 'SetSceneItemTransform' self.dataout['item'] = item self.dataout['x-scale'] = x_scale", "for the first 5 or so seconds that the media", "`ffmpeg_source` or `vlc_source`) *mediaSources.*.mediaState* type: String The current state of", "filter to remove \"\"\" def __init__(self, sourceName, filterName): Baserequests.__init__(self) self.name", "def getWidth(self): return self.datain['width'] def getHeight(self): return self.datain['height'] def getParentGroupName(self):", "processing/network delays, this request is not perfect. The processing rate", "= scene_name class SetSceneItemRender(Baserequests): \"\"\"Show or hide a specified source", "specified source. :Arguments: *sourceName* type: String Source name. :Returns: *monitorType*", "*offset* type: int The desired audio sync offset (in nanoseconds).", "specified in the request) *imageFile* type: String Absolute path to", "for more information). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSceneList'", "self.dataout['text'] = text class GetStudioModeStatus(Baserequests): \"\"\"Indicates if Studio Mode is", "media. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaTime' self.datain['timestamp']", "name. *volume* type: double Volume of the source. Between `0.0`", "'SetMediaTime' self.dataout['sourceName'] = sourceName self.dataout['timestamp'] = timestamp class ScrubMedia(Baserequests): \"\"\"Scrub", "String Source filter name :Returns: *enabled* type: Boolean Filter status", "double (optional) The new height of the bounding box. \"\"\"", "= None def getProfiles(self): return self.datain['profiles'] class GetRecordingStatus(Baserequests): \"\"\"Get current", "scene collections :Returns: *scene_collections* type: Array<String> Scene collections list *scene_collections.*.sc_name*", "self.dataout['sourceName'] = sourceName def getMediaDuration(self): return self.datain['mediaDuration'] class GetMediaTime(Baserequests): \"\"\"Get", "sources of this type may cause a feedback loop if", "*desktop_2* type: String (optional) Name of the second Desktop Audio", "`volume` data as decibels instead of amplitude/mul. \"\"\" def __init__(self,", "Height. *fps* type: int (optional) Framerate. *shutdown* type: boolean (optional)", "(optional) Chat log. *chatlog_lines* type: int (optional) Chat log lines.", "be \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSourceTypesList' self.datain['types'] =", "__init__(self): Baserequests.__init__(self) self.name = 'GetRecordingStatus' self.datain['isRecording'] = None self.datain['isRecordingPaused'] =", "__init__(self, source, useDecibel=None): Baserequests.__init__(self) self.name = 'GetVolume' self.datain['name'] = None", "source items. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentScene' self.datain['name']", "*keyId* type: String Main key identifier (e.g. `OBS_KEY_A` for key", "occur when starting the stream. *stream.metadata* type: Object (optional) Adds", "into a scene. :Arguments: *sceneName* type: String Name of the", "the source. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetMute'", "boolean Read text from the specified file. *font* type: Object", "type: int (optional) The new alignment of the bounding box.", "= 'SetSceneItemPosition' self.dataout['item'] = item self.dataout['x'] = x self.dataout['y'] =", "fromScene=None, toScene=None): Baserequests.__init__(self) self.name = 'DuplicateSceneItem' self.datain['scene'] = None self.datain['item']", "*text* type: String Text content to be displayed. *text_file* type:", "type: String (optional) Name of the item's parent (if this", "Baserequests.__init__(self) self.name = 'GetSceneItemList' self.datain['sceneName'] = None self.datain['sceneItems'] = None", "of the source before scaling. *crop.left* type: int The number", "'ListProfiles' self.datain['profiles'] = None def getProfiles(self): return self.datain['profiles'] class GetRecordingStatus(Baserequests):", "available sources types :Returns: *types* type: Array<Object> Array of source", "(optional) Font Style (unknown function). *gradient* type: boolean (optional) Gradient", "self.dataout['force'] = force class SetCurrentProfile(Baserequests): \"\"\"Set the currently active profile.", "the recording folder. \"\"\" def __init__(self, rec_folder): Baserequests.__init__(self) self.name =", "rotation=None, scale=None, crop=None, visible=None, locked=None, bounds=None): Baserequests.__init__(self) self.name = 'SetSceneItemProperties'", "String (optional) \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetAuthRequired' self.datain['authRequired']", "def getIsRecordingPaused(self): return self.datain['isRecordingPaused'] def getRecordTimecode(self): return self.datain['recordTimecode'] def getRecordingFilename(self):", "Will return an `error` if recording is already active. \"\"\"", "enabled. *gradient_color* type: int Gradient color. *gradient_dir* type: float Gradient", "*scene_name* type: String (optional) Name of the scene the scene", "= sourceName self.dataout['embedPictureFormat'] = embedPictureFormat self.dataout['saveToFilePath'] = saveToFilePath self.dataout['fileFormat'] =", "the current profile's scenes (See [GetCurrentScene](#getcurrentscene) for more information). \"\"\"", "scale factor. *y_scale* type: double Height scale factor. *rotation* type:", "extents_cx self.dataout['extents_cy'] = extents_cy self.dataout['file'] = file self.dataout['read_from_file'] = read_from_file", "None self.datain['settings'] = None self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName", "type: boolean (optional) Word wrap. \"\"\" def __init__(self, source, color1=None,", "however OBS actually supports larger values. *useDecibel* type: boolean (optional)", "= align self.dataout['bk_color'] = bk_color self.dataout['bk_opacity'] = bk_opacity self.dataout['chatlog'] =", "expect a specific settings schema. :Returns: *sourceName* type: String Source", "type: Array<Object> List of filters for the specified source *filters.*.enabled*", "SetSourceName(Baserequests): \"\"\" Note: If the new name already exists as", "\"\"\"Toggles Studio Mode (depending on the current state of studio", "self.datain['name'] = None self.datain['muted'] = None self.dataout['source'] = source def", "type: double Volume of the source. Between `0.0` and `20.0`", "def __init__(self, sceneName=None): Baserequests.__init__(self) self.name = 'GetSceneItemList' self.datain['sceneName'] = None", "Name of a scene item. Sufficiently unique if no scene", "boolean (optional) Whether or not the T-Bar gets released automatically", "keyModifiers): Baserequests.__init__(self) self.name = 'TriggerHotkeyBySequence' self.dataout['keyId'] = keyId self.dataout['keyModifiers'] =", "= 'ReleaseTBar' class SetTBarPosition(Baserequests): \"\"\" If your code needs to", "type: double Scene item height (base source height multiplied by", "to the current scene. *item* type: Object Scene item to", "Trigger Shift Key *keyModifiers.alt* type: boolean Trigger Alt Key *keyModifiers.control*", "sources *sources.*.name* type: String Unique source name *sources.*.typeId* type: String", "enabled. *gradient_color* type: int (optional) Gradient color. *gradient_dir* type: float", "special sources like Desktop Audio and Mic/Aux sources. :Returns: *desktop_1*", "the streaming server. Only present if `use_auth` is `true`. \"\"\"", "source. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetAudioActive' self.datain['audioActive']", "displayed. *valign* type: String (optional) Text vertical alignment (\"top\", \"center\",", "given object parameters as encoded query string parameters to the", "sceneName def getSceneName(self): return self.datain['sceneName'] def getSceneItems(self): return self.datain['sceneItems'] class", "type: boolean Starts/Stops emitting heartbeat messages \"\"\" def __init__(self, enable):", "if currently recording). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetRecordingStatus'", "item to delete (required) *item.name* type: String Scene Item name", "def getChatlog_lines(self): return self.datain['chatlog_lines'] def getColor(self): return self.datain['color'] def getExtents(self):", "self.datain['baseHeight'] def getOutputWidth(self): return self.datain['outputWidth'] def getOutputHeight(self): return self.datain['outputHeight'] def", "= source self.dataout['mute'] = mute class ToggleMute(Baserequests): \"\"\"Inverts the mute", "The OBS volume sliders only reach a maximum of 1.0mul/0.0dB,", "*sourceType* type: String Type of the specified source *sourceSettings* type:", "'type' is different than the current streaming service type, all", "self.datain['css'] def getWidth(self): return self.datain['width'] def getHeight(self): return self.datain['height'] def", "= None self.dataout['sceneName'] = sceneName def getSceneName(self): return self.datain['sceneName'] def", "it). *YOU MUST CALL THIS if you called `SetTBarPosition` with", "self.dataout['item'] = item self.dataout['scene-name'] = scene_name def getName(self): return self.datain['name']", "int (optional) Transition duration (in milliseconds). \"\"\" def __init__(self, with_transition=None):", "None self.datain['visible'] = None self.datain['muted'] = None self.datain['locked'] = None", "width=None, height=None): Baserequests.__init__(self) self.name = 'TakeSourceScreenshot' self.datain['sourceName'] = None self.datain['img']", "*rotation* type: double (optional) The new clockwise rotation of the", "the contents of the Replay Buffer to disk. This is", "x scale of the item. *scale.y* type: double (optional) The", "\"\"\"Inverts the mute status of a specified source. :Arguments: *source*", "For example `vlc_source` or `image_source` *sceneItems.*.sourceName* type: String Name of", "= None self.datain['preview-only'] = None def getStreaming(self): return self.datain['streaming'] def", "(optional) Adds the given object parameters as encoded query string", "*settings.server* type: String (optional) The publish URL. *settings.key* type: String", "sourceKind self.dataout['sceneName'] = sceneName self.dataout['sourceSettings'] = sourceSettings self.dataout['setVisible'] = setVisible", "OBS volume sliders only reach a maximum of 1.0mul/0.0dB, however", "\"\"\" def __init__(self, stream=None): Baserequests.__init__(self) self.name = 'StartStreaming' self.dataout['stream'] =", "field is a string) or specification (if it is an", "name. :Returns: *timestamp* type: int The time in milliseconds since", "boolean (optional) Outline. *outline_color* type: int (optional) Outline color. *outline_size*", "def __init__(self, source, is_local_file=None, local_file=None, url=None, css=None, width=None, height=None, fps=None,", "self.dataout['name'] = name class TriggerHotkeyByName(Baserequests): \"\"\"Executes hotkey routine, identified by", "def getChallenge(self): return self.datain['challenge'] def getSalt(self): return self.datain['salt'] class Authenticate(Baserequests):", "compatible API version. Fixed to 1.1 for retrocompatibility. *obs_websocket_version* type:", "(optional) Name of the scene to reorder (defaults to current).", "Name of the scene to create the scene item in", "the current recording state). \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "current scene. *item* type: String Scene Item name. *x* type:", "self.name = 'ListSceneCollections' self.datain['scene-collections'] = None def getSceneCollections(self): return self.datain['scene-collections']", "self.name = 'SetRecordingFolder' self.dataout['rec-folder'] = rec_folder class GetRecordingFolder(Baserequests): \"\"\"Get the", "*supported_image_export_formats* type: String List of supported formats for features that", "type: String Source name. *color1* type: int (optional) Gradient top", "Note: Due to processing/network delays, this request is not perfect.", "self.dataout['fromScene'] = fromScene self.dataout['toScene'] = toScene def getScene(self): return self.datain['scene']", "is locked. *bounds.type* type: String Type of bounding box. Can", "class SetStreamSettings(Baserequests): \"\"\"Sets one or more attributes of the current", "type: String Source name. *playPause* type: boolean Whether to pause", "= extents_cy self.dataout['file'] = file self.dataout['read_from_file'] = read_from_file self.dataout['font'] =", "= transitionName def getTransitionSettings(self): return self.datain['transitionSettings'] class SetTransitionSettings(Baserequests): \"\"\"Change the", "self.datain['timestamp'] class SetMediaTime(Baserequests): \"\"\"Set the timestamp of a media source.", "which the specified filter is removed *filterName* type: String Name", "getOutputWidth(self): return self.datain['outputWidth'] def getOutputHeight(self): return self.datain['outputHeight'] def getScaleType(self): return", "text self.dataout['valign'] = valign self.dataout['vertical'] = vertical self.dataout['render'] = render", "of the transition. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionList'", "type: OBSStats [OBS stats](#obsstats) \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", ":Arguments: *source* type: String Source name. :Returns: *source* type: String", "password to use when accessing the streaming server. Only present", "the scene item in *sourceName* type: String Name of the", "Gradient direction. *gradient_opacity* type: int Gradient opacity (0-100). *outline* type:", "= 'GetSourceFilterInfo' self.datain['enabled'] = None self.datain['type'] = None self.datain['name'] =", "the filter to reorder *newIndex* type: Integer Desired position of", "state of media for that source. States: `none`, `playing`, `opening`,", "return self.datain['is_local_file'] def getLocal_file(self): return self.datain['local_file'] def getUrl(self): return self.datain['url']", ":Arguments: *transition_name* type: String The name of the transition. \"\"\"", "on user settings :Arguments: *keyId* type: String Main key identifier", "self.name = 'GetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType'] = None self.datain['sourceSettings']", "return self.datain['filename-formatting'] class GetStats(Baserequests): \"\"\"Get OBS stats (almost the same", "*duration* type: int (optional) Transition duration (in milliseconds) if supported", "duration of the currently selected transition if supported. :Returns: *transition_duration*", "getRecording(self): return self.datain['recording'] def getStreamTimecode(self): return self.datain['stream-timecode'] def getRecTimecode(self): return", "fully duplicated *types.*.caps.doNotSelfMonitor* type: Boolean True if sources of this", "self.datain['source'] = None self.datain['color1'] = None self.datain['color2'] = None self.datain['custom_width']", "audio's active status of a specified source. :Arguments: *sourceName* type:", "self.dataout['outputName'] = outputName self.dataout['force'] = force class SetCurrentProfile(Baserequests): \"\"\"Set the", "Gradient top color. *color2* type: int (optional) Gradient bottom color.", "def getOutputInfo(self): return self.datain['outputInfo'] class StartOutput(Baserequests): \"\"\" Note: Controlling outputs", "(prefer `id`, including both is acceptable). *item.id* type: int Scene", "of the scene to get the list of scene items", "self.datain['scene'] def getItem(self): return self.datain['item'] class SetCurrentScene(Baserequests): \"\"\"Switch to the", "media state of the provided source. States: `none`, `playing`, `opening`,", "sceneName): Baserequests.__init__(self) self.name = 'GetSceneTransitionOverride' self.datain['transitionName'] = None self.datain['transitionDuration'] =", "def __init__(self): Baserequests.__init__(self) self.name = 'SaveStreamSettings' class SendCaptions(Baserequests): \"\"\"Send the", "None def getRecFolder(self): return self.datain['rec-folder'] class GetReplayBufferStatus(Baserequests): \"\"\"Get the status", "(optional) Format of the Data URI encoded picture. Can be", "the item in. Defaults to the current scene. *item* type:", "String Color range (full or partial) \"\"\" def __init__(self): Baserequests.__init__(self)", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopReplayBuffer' class StartReplayBuffer(Baserequests): \"\"\"Start", "= 'RemoveFilterFromSource' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName class ReorderSourceFilter(Baserequests):", "was specified in the request) \"\"\" def __init__(self, sourceName=None, embedPictureFormat=None,", "vlc media sources (as of OBS v25.0.8) Note: Due to", "Baserequests.__init__(self) self.name = 'StopOutput' self.dataout['outputName'] = outputName self.dataout['force'] = force", "the OBS replay buffer. :Returns: *isReplayBufferActive* type: boolean Current recording", "if supported. :Returns: *transition_duration* type: int Duration of the current", "def getName(self): return self.datain['name'] def getVolume(self): return self.datain['volume'] def getMuted(self):", "recording is not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "self.datain['muted'] class SetVolume(Baserequests): \"\"\"Set the volume of the specified source.", "Path of the recording folder. \"\"\" def __init__(self, rec_folder): Baserequests.__init__(self)", "Browser Source. :Arguments: *source* type: String Name of the source.", "sourceName, sourceSettings, sourceType=None): Baserequests.__init__(self) self.name = 'SetSourceSettings' self.datain['sourceName'] = None", "self.name = 'GetCurrentSceneCollection' self.datain['sc-name'] = None def getScName(self): return self.datain['sc-name']", "self.datain['word_wrap'] = None self.dataout['source'] = source def getSource(self): return self.datain['source']", "monitoring type of the specified source. :Arguments: *sourceName* type: String", "= 'StopOutput' self.dataout['outputName'] = outputName self.dataout['force'] = force class SetCurrentProfile(Baserequests):", "Object (optional) Adds the given object parameters as encoded query", "the source. *position.y* type: double (optional) The new y position", "type: int (optional) Font text styling flag. `Bold=1, Italic=2, Bold", "(optional) Text content to be displayed. *valign* type: String (optional)", "If authentication is enabled, the password for the streaming server.", "cropped off the left of the source before scaling. *visible*", "status. *recording* type: boolean Current recording status. *stream_timecode* type: String", "= 'GetTransitionPosition' self.datain['position'] = None def getPosition(self): return self.datain['position'] class", "the specified source. Default response uses mul format, NOT SLIDER", "will remain unchanged. Returns the updated settings in response. If", "types, may require some probing around). \"\"\" def __init__(self, sourceName,", "*types.*.caps.doNotSelfMonitor* type: Boolean True if sources of this type may", "Font face. *font.flags* type: int (optional) Font text styling flag.", "generate_classes.py - DO NOT EDIT # # (Generated on 2020-12-20", "Name of the scene to switch to. \"\"\" def __init__(self,", "[OBS stats](#obsstats) \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStats' self.datain['stats']", "getIsRecordingPaused(self): return self.datain['isRecordingPaused'] def getRecordTimecode(self): return self.datain['recordTimecode'] def getRecordingFilename(self): return", "= sceneName class ReorderSceneItems(Baserequests): \"\"\"Changes the order of scene items", "the specified source item. Coordinates are relative to the item's", "X coordinate. *y* type: double Y coordinate. \"\"\" def __init__(self,", "Default request format uses mul, NOT SLIDER PERCENTAGE. :Arguments: *source*", "the transition. \"\"\" def __init__(self, transition_name): Baserequests.__init__(self) self.name = 'SetCurrentTransition'", "for dB. OBS will interpret dB values under -100.0 as", "`item` field is an object) *position.x* type: double (optional) The", "self.datain['position'] = None self.datain['rotation'] = None self.datain['scale'] = None self.datain['crop']", "The username to use when accessing the streaming server. Only", "'StopRecording' class PauseRecording(Baserequests): \"\"\"Pause the current recording. Returns an error", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentProfile' self.datain['profile-name'] = None", "Boolean True if sources of this type may cause a", "__init__(self, outputName, force=None): Baserequests.__init__(self) self.name = 'StopOutput' self.dataout['outputName'] = outputName", "type: String Source name. :Returns: *audioActive* type: boolean Audio active", "*source* type: String Source name. *useDecibel* type: boolean (optional) Output", "scene item. :Arguments: *fromScene* type: String (optional) Name of the", "return self.datain['mic-1'] def getMic2(self): return self.datain['mic-2'] def getMic3(self): return self.datain['mic-3']", "self.name = 'GetStudioModeStatus' self.datain['studio-mode'] = None def getStudioMode(self): return self.datain['studio-mode']", "of the source type *types.*.type* type: String Type. Value is", "number of pixels cropped off the right of the source", "return self.datain['bk_color'] def getBk_opacity(self): return self.datain['bk_opacity'] def getChatlog(self): return self.datain['chatlog']", "transition position. This value will be between 0.0 and 1.0.", "enabled. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetTextGDIPlusProperties' self.datain['source']", "def getCustom_width(self): return self.datain['custom_width'] def getDrop_shadow(self): return self.datain['drop_shadow'] def getFont(self):", "getObsWebsocketVersion(self): return self.datain['obs-websocket-version'] def getObsStudioVersion(self): return self.datain['obs-studio-version'] def getAvailableRequests(self): return", "If the source's transform is locked. *bounds.type* type: String Type", "differs from base size *fps* type: double Frames rendered per", "item. \"\"\" def __init__(self, source, align=None, bk_color=None, bk_opacity=None, chatlog=None, chatlog_lines=None,", "the current state of studio mode). \"\"\" def __init__(self): Baserequests.__init__(self)", "def getGradient(self): return self.datain['gradient'] def getGradient_color(self): return self.datain['gradient_color'] def getGradient_dir(self):", "NOT SLIDER PERCENTAGE. :Arguments: *source* type: String Source name. *useDecibel*", "source. *mic_1* type: String (optional) Name of the first Mic/Aux", "volume of the specified source. Default request format uses mul,", "not provided, the currently active scene is used. *embedPictureFormat* type:", "getName(self): return self.datain['name'] def getOffset(self): return self.datain['offset'] class GetSourceSettings(Baserequests): \"\"\"Get", "*save* type: boolean Persist the settings to disk. \"\"\" def", "type self.dataout['settings'] = settings self.dataout['save'] = save class GetStreamSettings(Baserequests): \"\"\"Get", "Some plugins which add outputs to OBS may not function", "Source name. *mute* type: boolean Desired mute status. \"\"\" def", "\"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetSyncOffset' self.datain['name'] =", "None self.datain['transitions'] = None def getCurrentTransition(self): return self.datain['current-transition'] def getTransitions(self):", "`monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetAudioMonitorType'", "StartStopRecording(Baserequests): \"\"\"Toggle recording on or off (depending on the current", "= sceneName self.dataout['sourceName'] = sourceName self.dataout['setVisible'] = setVisible def getItemId(self):", "self.dataout['sourceType'] = sourceType def getSourceName(self): return self.datain['sourceName'] def getSourceType(self): return", "Either \"up\", \"down\", \"top\" or \"bottom\". \"\"\" def __init__(self, sourceName,", "axis. *rotation* type: double The clockwise rotation of the item", "released automatically after setting its new position (like a user", "an error will occur when starting the stream. *stream.metadata* type:", "transition :Arguments: *transitionName* type: String Transition name *transitionSettings* type: Object", "the latest version of the plugin and the API. :Returns:", "\"\"\" def __init__(self, sourceName, sourceKind, sceneName, sourceSettings=None, setVisible=None): Baserequests.__init__(self) self.name", "type: int Gradient color. *gradient_dir* type: float Gradient direction. *gradient_opacity*", "'CreateSource' self.datain['itemId'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceKind'] = sourceKind", "Array<SceneItemTransform> (optional) List of children (if this item is a", "= auth class SetHeartbeat(Baserequests): \"\"\"Enable/disable sending of the Heartbeat event", "is set. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'GetSceneTransitionOverride'", "*sources* type: Array<SceneItem> Ordered list of the current scene's source", "or scene to be displayed (ignored for other projector types).", "source, offset): Baserequests.__init__(self) self.name = 'SetSyncOffset' self.dataout['source'] = source self.dataout['offset']", "Corresponds to OBS's saved projectors. *name* type: String (Optional) Name", "of a filter :Arguments: *sourceName* type: String Name of the", "= 'ListSceneCollections' self.datain['scene-collections'] = None def getSceneCollections(self): return self.datain['scene-collections'] class", "type: float Gradient direction. *gradient_opacity* type: int Gradient opacity (0-100).", "active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartRecording' class StopRecording(Baserequests):", "type: String Transition name :Returns: *transitionSettings* type: Object Current transition", "return self.datain['name'] def getItemId(self): return self.datain['itemId'] def getPosition(self): return self.datain['position']", "def getSources(self): return self.datain['sources'] class GetSceneList(Baserequests): \"\"\"Get a list of", "source type ID *types.*.displayName* type: String Display name of the", "of the scene item. \"\"\" def __init__(self, source, align=None, bk_color=None,", "boolean Vertical text enabled. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name", "the source on which the filter is added *filterName* type:", "outline_opacity=None, text=None, valign=None, vertical=None, render=None): Baserequests.__init__(self) self.name = 'SetTextGDIPlusProperties' self.dataout['source']", "__init__(self, item, x, y, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemPosition' self.dataout['item']", "Time elapsed since streaming started (only present if currently streaming).", "(optional) Font text size. *font.style* type: String (optional) Font Style", "*isReplayBufferActive* type: boolean Current recording status. \"\"\" def __init__(self): Baserequests.__init__(self)", "Returns the full settings of the stream (the same as", "source. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetMute' self.datain['name']", "offset (positive or negative) to offset the current media position.", "filter is removed *filterName* type: String Name of the filter", "*setVisible* type: boolean Whether to make the sceneitem visible on", "Audio and Mic/Aux sources. :Returns: *desktop_1* type: String (optional) Name", "self.datain['scenes'] class CreateScene(Baserequests): \"\"\"Create a new scene scene. :Arguments: *sceneName*", "= None self.datain['custom_width'] = None self.datain['drop_shadow'] = None self.datain['font'] =", "Compression ratio between -1 and 100 to write the image", "self.datain['name'] def getMuted(self): return self.datain['muted'] class SetMute(Baserequests): \"\"\"Sets the mute", ":Returns: *sources* type: Array<Object> Array of sources *sources.*.name* type: String", "boolean (optional) Word wrap. \"\"\" def __init__(self, source, color1=None, color2=None,", "is specified. :Arguments: *sourceName* type: String (optional) Source name. Note", "String Output name *force* type: boolean (optional) Force stop (default:", "Array<Scene> Ordered list of objects with name and/or id specified.", "Object Filter settings \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name =", "disable). *drop_shadow* type: boolean Drop shadow. *font* type: Object Holds", "'SetFilenameFormatting' self.dataout['filename-formatting'] = filename_formatting class GetFilenameFormatting(Baserequests): \"\"\"Get the filename formatting", "name :Arguments: *hotkeyName* type: String Unique name of the hotkey,", "self.datain['color1'] = None self.datain['color2'] = None self.datain['custom_width'] = None self.datain['drop_shadow']", "self.name = 'GetSourceFilterInfo' self.datain['enabled'] = None self.datain['type'] = None self.datain['name']", "type: boolean Whether the recording is paused or not. *recordTimecode*", "when not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionPosition'", ":Arguments: *sourceName* type: String Source name. *timestamp* type: int Milliseconds", "self.datain['gradient_opacity'] = None self.datain['outline'] = None self.datain['outline_color'] = None self.datain['outline_size']", "custom_width=None, drop_shadow=None, font=None, from_file=None, log_mode=None, outline=None, text=None, text_file=None, word_wrap=None): Baserequests.__init__(self)", "*sceneName* type: String Name of the scene to create. \"\"\"", "routine, identified by hotkey unique name :Arguments: *hotkeyName* type: String", "type: boolean Mute status of the source. \"\"\" def __init__(self,", "= None self.datain['muted'] = None self.dataout['source'] = source def getName(self):", "sceneName, transitionName, transitionDuration): Baserequests.__init__(self) self.name = 'SetSceneTransitionOverride' self.dataout['sceneName'] = sceneName", "self.name = 'ListProfiles' self.datain['profiles'] = None def getProfiles(self): return self.datain['profiles']", "a projector on a monitor. Requires OBS v24.0.4 or newer.", "of the scene to switch to. :Returns: *transitionName* type: String", "scene to copy the item from. Defaults to the current", "*settings.username* type: String (optional) The username for the streaming service.", "transition before switching scenes. Defaults to the active transition. *with_transition.name*", "\"\"\"Restart a media source. Supports ffmpeg and vlc media sources", "GetReplayBufferStatus(Baserequests): \"\"\"Get the status of the OBS replay buffer. :Returns:", "visible=None, locked=None, bounds=None): Baserequests.__init__(self) self.name = 'SetSceneItemProperties' self.dataout['item'] = item", "*source* type: String Scene Item name. *render* type: boolean true", "\"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetTextFreetype2Properties' self.datain['source'] =", "= timestamp class ScrubMedia(Baserequests): \"\"\"Scrub media using a supplied offset.", "this type is possible *types.*.caps.isComposite* type: Boolean True if sources", "of the specified source item. :Arguments: *scene_name* type: String (optional)", "if you set `release` to false. Defaults to true. \"\"\"", "list of available profiles. :Returns: *profiles* type: Array<Object> List of", "Bold Italic=3, Underline=5, Strikeout=8` *font.size* type: int Font text size.", "'GetSourceFilterInfo' self.datain['enabled'] = None self.datain['type'] = None self.datain['name'] = None", "if sources of this type may cause a feedback loop", "type: String CSS to inject. *width* type: int Width. *height*", "self.name = 'PlayPauseMedia' self.dataout['sourceName'] = sourceName self.dataout['playPause'] = playPause class", "def getFile(self): return self.datain['file'] def getRead_from_file(self): return self.datain['read_from_file'] def getFont(self):", "type: String Name of the currently active profile. \"\"\" def", "String Source name *sourceType* type: String Type of the specified", "'SetSourceName' self.dataout['sourceName'] = sourceName self.dataout['newName'] = newName class SetSyncOffset(Baserequests): \"\"\"Set", "type: String Source name *sourceType* type: String Type of the", "function properly when they are controlled in this way. :Arguments:", "may cause a feedback loop if it's audio is monitored", "scene or group it belongs to). :Arguments: *scene_name* type: String", "settings schema. :Returns: *sourceName* type: String Source name *sourceType* type:", "def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'RestartMedia' self.dataout['sourceName'] = sourceName", "(optional) Whether or not the T-Bar gets released automatically after", "scene by scene basis. *items.*.name* type: String (optional) Name of", "type: Object Default settings of this source type *types.*.caps* type:", "getGradient_color(self): return self.datain['gradient_color'] def getGradient_dir(self): return self.datain['gradient_dir'] def getGradient_opacity(self): return", "*filterName* type: String Name of the filter to reorder *movementType*", "self.dataout['file'] = file self.dataout['read_from_file'] = read_from_file self.dataout['font'] = font self.dataout['gradient']", "boolean Indicates whether the source should be shutdown when not", "*available_requests* type: String List of available request types, formatted as", "= shutdown self.dataout['render'] = render class GetSpecialSources(Baserequests): \"\"\"Get configured special", "\"\"\"Set the current properties of a Text GDI Plus source.", "`GetVersion`). If not specified, tries to guess based on file", "(without scaling) of the source *sourceHeight* type: int Base source", "`opening`, `buffering`, `paused`, `stopped`, `ended`, `error`, `unknown` \"\"\" def __init__(self):", "immediately and will be effective on the next recording. :Arguments:", "__init__(self, stream=None): Baserequests.__init__(self) self.name = 'StartStreaming' self.dataout['stream'] = stream class", "type: String (optional) Font Style (unknown function). *from_file* type: boolean", "Source name. Note that, since scenes are also sources, you", "ID (if the `item` field is an object) :Returns: *name*", "to a source. Available source types along with their settings", "Name of the requested (or current) scene *sceneItems* type: Array<Object>", "object parameters as encoded query string parameters to the 'key'", "(one of the values provided in the `supported-image-export-formats` response field", "cx. *extents_cy* type: int Extents cy. *file* type: String File", "\"Arial\", \"flags\": 0, \"size\": 150, \"style\": \"\" }` *font.face* type:", "text=None, text_file=None, word_wrap=None): Baserequests.__init__(self) self.name = 'SetTextFreetype2Properties' self.dataout['source'] = source", ":Arguments: *sourceName* type: String Source name. *monitorType* type: String The", "Scene Item name. *itemId* type: int Scene Item ID. *position.x*", "= item self.dataout['scene-name'] = scene_name def getName(self): return self.datain['name'] def", "= sourceName self.dataout['filterName'] = filterName self.dataout['filterType'] = filterType self.dataout['filterSettings'] =", "String Name of the desired scene collection. \"\"\" def __init__(self,", "align=None, bk_color=None, bk_opacity=None, chatlog=None, chatlog_lines=None, color=None, extents=None, extents_cx=None, extents_cy=None, file=None,", "\"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'GetSceneTransitionOverride' self.datain['transitionName'] =", "__init__(self, type, monitor, geometry, name): Baserequests.__init__(self) self.name = 'OpenProjector' self.dataout['type']", "gradient_color=None, gradient_dir=None, gradient_opacity=None, outline=None, outline_color=None, outline_size=None, outline_opacity=None, text=None, valign=None, vertical=None,", "belongs to). :Arguments: *scene_name* type: String (optional) Name of the", "*types.*.typeId* type: String Non-unique internal source type ID *types.*.displayName* type:", "type: String (optional) Text content to be displayed. *valign* type:", "Font Style (unknown function). *gradient* type: boolean (optional) Gradient enabled.", "recording. :Arguments: *rec_folder* type: String Path of the recording folder.", "filterName, filterType, filterSettings): Baserequests.__init__(self) self.name = 'AddFilterToSource' self.dataout['sourceName'] = sourceName", "return self.datain['name'] def getSettings(self): return self.datain['settings'] class AddFilterToSource(Baserequests): \"\"\"Add a", "| Object Scene Item name (if this field is a", "__init__(self): Baserequests.__init__(self) self.name = 'StopReplayBuffer' class SaveReplayBuffer(Baserequests): \"\"\"Flush and save", "text size. *font.style* type: String Font Style (unknown function). *gradient*", "*newName* type: String New source name. \"\"\" def __init__(self, sourceName,", "return self.datain['settings'] class SaveStreamSettings(Baserequests): \"\"\"Save the current streaming server settings", "the projector window (only if monitor is -1). Encoded in", ":Returns: *name* type: String Source name. *muted* type: boolean Mute", "new name already exists as a source, obs-websocket will return", "self.dataout['fileFormat'] = fileFormat self.dataout['compressionQuality'] = compressionQuality self.dataout['width'] = width self.dataout['height']", "following: \"input\", \"filter\", \"transition\" or \"other\" *types.*.defaultSettings* type: Object Default", "type: double Height of the bounding box. *sourceWidth* type: int", "class GetMediaSourcesList(Baserequests): \"\"\"List the media state of all media sources", "String Color space for YUV *colorRange* type: String Color range", "*mic_2* type: String (optional) Name of the second Mic/Aux input", "String Absolute path to the saved image file (if `saveToFilePath`", "source item. :Arguments: *scene_name* type: String (optional) Name of the", "(optional) Gradient enabled. *gradient_color* type: int (optional) Gradient color. *gradient_dir*", "data class GetVideoInfo(Baserequests): \"\"\"Get basic OBS video information :Returns: *baseWidth*", "to add the new source to. *sourceSettings* type: Object (optional)", "class StartStopReplayBuffer(Baserequests): \"\"\"Toggle the Replay Buffer on/off (depending on the", "obs-websocket. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartReplayBuffer' class StopReplayBuffer(Baserequests):", "self.datain['recording'] = None self.datain['stream-timecode'] = None self.datain['rec-timecode'] = None self.datain['preview-only']", "String Scene to add the new source to. *sourceSettings* type:", "text enabled. *render* type: boolean (optional) Visibility of the scene", "scene. *item* type: String Scene Item name. *x_scale* type: double", "self.datain['mediaDuration'] = None self.dataout['sourceName'] = sourceName def getMediaDuration(self): return self.datain['mediaDuration']", "= None self.dataout['outputName'] = outputName def getOutputInfo(self): return self.datain['outputInfo'] class", "None def getSceneCollections(self): return self.datain['scene-collections'] class GetSceneItemList(Baserequests): \"\"\"Get a list", "Can be in a format different from `pictureFormat`. Can be", "type: Object Scene Item to duplicate from the source scene", "__init__(self, sourceName): Baserequests.__init__(self) self.name = 'StopMedia' self.dataout['sourceName'] = sourceName class", "source. *position.alignment* type: int (optional) The new alignment of the", "Baserequests.__init__(self) self.name = 'ToggleMute' self.dataout['source'] = source class GetAudioActive(Baserequests): \"\"\"Get", "Studio Mode. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'EnableStudioMode' class", "of the provided source. States: `none`, `playing`, `opening`, `buffering`, `paused`,", "displayed. *text_file* type: String File path. *word_wrap* type: boolean Word", "a maximum of 1.0mul/0.0dB, however OBS actually supports larger values.", "= width self.dataout['height'] = height self.dataout['fps'] = fps self.dataout['shutdown'] =", "Font Style (unknown function). *from_file* type: boolean (optional) Read text", "active scene. *source* type: String Scene Item name. *render* type:", "Source name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'NextMedia'", "type: boolean Extents wrap. *extents_cx* type: int Extents cx. *extents_cy*", "String (optional) Text content to be displayed. *text_file* type: String", "Trigger Control (Ctrl) Key *keyModifiers.command* type: boolean Trigger Command Key", "scene item \"\"\" def __init__(self, sceneName, sourceName, setVisible): Baserequests.__init__(self) self.name", "def getColor1(self): return self.datain['color1'] def getColor2(self): return self.datain['color2'] def getCustom_width(self):", "Optional key modifiers object. False entries can be ommitted *keyModifiers.shift*", "class SetSceneItemProperties(Baserequests): \"\"\"Sets the scene specific properties of a source.", "the desired profile. \"\"\" def __init__(self, profile_name): Baserequests.__init__(self) self.name =", "from `pictureFormat`. Can be a relative path. *fileFormat* type: String", "\"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int (optional)", "group) *groupChildren* type: Array<SceneItemTransform> (optional) List of children (if this", "y position of the source from the top. *position.alignment* type:", "*source* type: String Source name. *align* type: String Text Alignment", "you can also provide a scene name. If not provided,", "GetVersion(Baserequests): \"\"\"Returns the latest version of the plugin and the", "Whether the recording is paused or not. *recordTimecode* type: String", "type: String How to move the filter around in the", "\"\"\"Set the timestamp of a media source. Supports ffmpeg and", "type: int Output height *scaleType* type: String Scaling method used", "settings properties are available from `GetSourceTypesList`. :Arguments: *sourceName* type: String", "before switching scenes. Defaults to the active transition. *with_transition.name* type:", "name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'StopMedia' self.dataout['sourceName']", "*mute* type: boolean Desired mute status. \"\"\" def __init__(self, source,", "self.datain['sources'] = None def getSources(self): return self.datain['sources'] class GetSourceTypesList(Baserequests): \"\"\"Get", "\"\"\" def __init__(self, keyId, keyModifiers): Baserequests.__init__(self) self.name = 'TriggerHotkeyBySequence' self.dataout['keyId']", "= filterName self.dataout['filterSettings'] = filterSettings class SetSourceFilterVisibility(Baserequests): \"\"\"Change the visibility/enabled", "fileFormat self.dataout['compressionQuality'] = compressionQuality self.dataout['width'] = width self.dataout['height'] = height", "Text vertical alignment (\"top\", \"center\", \"bottom\"). *vertical* type: boolean (optional)", "[Qt's geometry encoding](https://doc.qt.io/qt-5/qwidget.html#saveGeometry). Corresponds to OBS's saved projectors. *name* type:", "double Source item rotation (in degrees). \"\"\" def __init__(self, item,", "tested. :Arguments: *sourceName* type: String Source name. *timeOffset* type: int", "type: int Alignment of the bounding box. *bounds.x* type: double", "*item* type: String Scene Item name. *top* type: int Pixel", "font=None, gradient=None, gradient_color=None, gradient_dir=None, gradient_opacity=None, outline=None, outline_color=None, outline_size=None, outline_opacity=None, text=None,", "class SetHeartbeat(Baserequests): \"\"\"Enable/disable sending of the Heartbeat event :Arguments: *enable*", "Base64 using [Qt's geometry encoding](https://doc.qt.io/qt-5/qwidget.html#saveGeometry). Corresponds to OBS's saved projectors.", "String (optional) Name of the second Mic/Aux input source. *mic_3*", "type: boolean (optional) Visibility of the scene item. \"\"\" def", "newName): Baserequests.__init__(self) self.name = 'SetSourceName' self.dataout['sourceName'] = sourceName self.dataout['newName'] =", "def getAuthRequired(self): return self.datain['authRequired'] def getChallenge(self): return self.datain['challenge'] def getSalt(self):", "requested scene. :Arguments: *scene* type: String (optional) Name of the", "type: int Millisecond offset (positive or negative) to offset the", "GetSceneTransitionOverride(Baserequests): \"\"\"Get the current scene transition override. :Arguments: *sceneName* type:", "to be displayed. *valign* type: String (optional) Text vertical alignment", "The new y position of the source. *position.alignment* type: int", ":Returns: *transition_duration* type: int Duration of the current transition (in", "Source name *filterName* type: String Source filter name *filterEnabled* type:", "source, 'false' hides source. *locked* type: bool (optional) The new", "*fileFormat* type: String (optional) Format to save the image file", "string if no override is set. *transitionDuration* type: int Transition", ":Returns: *itemId* type: int ID of the SceneItem in the", "Defaults to the source's base width. *height* type: int (optional)", "only vlc media source (as of OBS v25.0.8) :Arguments: *sourceName*", "'RemoveSceneTransitionOverride' self.dataout['sceneName'] = sceneName class GetSceneTransitionOverride(Baserequests): \"\"\"Get the current scene", "Baserequests.__init__(self) self.name = 'SetMediaTime' self.dataout['sourceName'] = sourceName self.dataout['timestamp'] = timestamp", "self.datain['outputInfo'] class StartOutput(Baserequests): \"\"\" Note: Controlling outputs is an experimental", "getTransitionDuration(self): return self.datain['transitionDuration'] class GetStreamingStatus(Baserequests): \"\"\"Get current streaming and recording", "field is an object) :Returns: *name* type: String Scene Item", "Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name", "return self.datain['sourceSettings'] class SetSourceSettings(Baserequests): \"\"\"Set settings of the specified source.", "type: String Source name. *timeOffset* type: int Millisecond offset (positive", "type: String (optional) The new bounds type of the source.", "'ResumeRecording' class SetRecordingFolder(Baserequests): \"\"\" Please note: if `SetRecordingFolder` is called", "current transition position. This value will be between 0.0 and", "the right of the source item. \"\"\" def __init__(self, item,", "int The audio sync offset (in nanoseconds). \"\"\" def __init__(self,", "this item belongs to a group) *groupChildren* type: Array<SceneItemTransform> (optional)", "items. :Returns: *name* type: String Name of the currently active", "String Name of the transition. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "source, obs-websocket will return an error. :Arguments: *sourceName* type: String", "the current duration specified in the UI if there is", "\"\"\"Get configured special sources like Desktop Audio and Mic/Aux sources.", "type: int Custom width (0 to disable). *drop_shadow* type: boolean", "the source's filter chain. Either \"up\", \"down\", \"top\" or \"bottom\".", "of a transition :Arguments: *transitionName* type: String Transition name :Returns:", "(depending on the current state of studio mode). \"\"\" def", "*settings.username* type: String The username to use when accessing the", "String Identifier to be choosen by the client *data* type:", "the API. :Returns: *version* type: double OBSRemote compatible API version.", "self.name = 'SaveReplayBuffer' class SetCurrentSceneCollection(Baserequests): \"\"\"Change the active scene collection.", "is `true`. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStreamSettings' self.datain['type']", "= sceneName def getTransitionName(self): return self.datain['transitionName'] def getTransitionDuration(self): return self.datain['transitionDuration']", "*sourceName* type: String Source name. *timeOffset* type: int Millisecond offset", "to reorder *newIndex* type: Integer Desired position of the filter", "already exists as a source, obs-websocket will return an error.", "None self.datain['color2'] = None self.datain['custom_width'] = None self.datain['drop_shadow'] = None", "whether the source should be shutdown when not visible. *render*", "Image Data URI (if `embedPictureFormat` was specified in the request)", "double Scene item height (base source height multiplied by the", "(optional) Width. *height* type: int (optional) Height. *fps* type: int", "render=None): Baserequests.__init__(self) self.name = 'SetTextGDIPlusProperties' self.dataout['source'] = source self.dataout['align'] =", "type: String Non-unique source internal type (a.k.a kind) *sources.*.type* type:", "the desired scene collection. \"\"\" def __init__(self, sc_name): Baserequests.__init__(self) self.name", "*stream.settings.use_auth* type: boolean (optional) Indicates whether authentication should be used", "type: String (optional) If authentication is enabled, the username for", "(optional) Indicates whether the source should be shutdown when not", "def getExtents(self): return self.datain['extents'] def getExtents_cx(self): return self.datain['extents_cx'] def getExtents_cy(self):", "ToggleMute(Baserequests): \"\"\"Inverts the mute status of a specified source. :Arguments:", "(as of OBS v25.0.8) Note: For some reason, for the", "streaming). *rec_timecode* type: String (optional) Time elapsed since recording started", "self.datain['parentGroupName'] def getGroupChildren(self): return self.datain['groupChildren'] class SetSceneItemProperties(Baserequests): \"\"\"Sets the scene", "String Source type. Value is one of the following: \"input\",", "type: boolean Whether to pause or play the source. `false`", "getMic2(self): return self.datain['mic-2'] def getMic3(self): return self.datain['mic-3'] class GetSourceFilters(Baserequests): \"\"\"List", "self.datain['filters'] = None self.dataout['sourceName'] = sourceName def getFilters(self): return self.datain['filters']", "= 'ResetSceneItem' self.dataout['item'] = item self.dataout['scene-name'] = scene_name class SetSceneItemRender(Baserequests):", "*valign* type: String Text vertical alignment (\"top\", \"center\", \"bottom\"). *vertical*", "(optional) The new visibility of the source. 'true' shows source,", "int Pixel position of the bottom of the source item.", "def getOutline(self): return self.datain['outline'] def getText(self): return self.datain['text'] def getText_file(self):", "a specified source item in a specified scene. :Arguments: *scene_name*", "type: Array<Object> Array of scene items *sceneItems.*.itemId* type: int Unique", "`rtmp_common`. *settings* type: Object The actual settings of the stream.", "return self.datain['sourceType'] def getSourceSettings(self): return self.datain['sourceSettings'] class SetSourceSettings(Baserequests): \"\"\"Set settings", "Duration of the current transition (in milliseconds). \"\"\" def __init__(self):", "return self.datain['rec-folder'] class GetReplayBufferStatus(Baserequests): \"\"\"Get the status of the OBS", "password for the streaming server. Ignored if `use_auth` is not", "*word_wrap* type: boolean Word wrap. \"\"\" def __init__(self, source): Baserequests.__init__(self)", "publish key of the stream. *settings.use_auth* type: boolean Indicates whether", "where the new item was created *item* type: Object New", "getAudioActive(self): return self.datain['audioActive'] class SetSourceName(Baserequests): \"\"\" Note: If the new", "box. \"\"\" def __init__(self, item, scene_name=None, position=None, rotation=None, scale=None, crop=None,", "of this type is possible *types.*.caps.isComposite* type: Boolean True if", "__init__(self, enable): Baserequests.__init__(self) self.name = 'SetHeartbeat' self.dataout['enable'] = enable class", "visible self.dataout['locked'] = locked self.dataout['bounds'] = bounds class ResetSceneItem(Baserequests): \"\"\"Reset", "def getScene(self): return self.datain['scene'] def getItem(self): return self.datain['item'] class SetCurrentScene(Baserequests):", "not perfect. The processing rate of this request has also", "type: String (optional) The publish key of the stream. *stream.settings.use_auth*", "String Name of the scene to switch to. *transitionName* type:", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListSceneCollections' self.datain['scene-collections'] = None", "`ended`, `error`, `unknown` \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetMediaSourcesList'", "class DisableStudioMode(Baserequests): \"\"\"Disables Studio Mode. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "\"Save Replay Buffer\" hotkey is not set in OBS' settings.", "type: int (optional) Outline color. *outline_size* type: int (optional) Outline", "basis. *items.*.name* type: String (optional) Name of a scene item.", "= 'GetMediaState' self.datain['mediaState'] = None self.dataout['sourceName'] = sourceName def getMediaState(self):", "\"style\": \"\" }` *font.face* type: String (optional) Font face. *font.flags*", "type: boolean (optional) Whether or not the T-Bar gets released", "GDI Plus source. :Arguments: *source* type: String Name of the", "self.name = 'GetCurrentProfile' self.datain['profile-name'] = None def getProfileName(self): return self.datain['profile-name']", "scene to switch to. :Returns: *transitionName* type: String Name of", "*obs_studio_version* type: String OBS Studio program version. *available_requests* type: String", "the TakeSourceScreenshot request type) formatted as a comma-separated list string", "recording into the Replay Buffer. Will return an `error` if", "save): Baserequests.__init__(self) self.name = 'SetStreamSettings' self.dataout['type'] = type self.dataout['settings'] =", "gradient_dir self.dataout['gradient_opacity'] = gradient_opacity self.dataout['outline'] = outline self.dataout['outline_color'] = outline_color", "font self.dataout['from_file'] = from_file self.dataout['log_mode'] = log_mode self.dataout['outline'] = outline", "*enabled* type: Boolean Filter status (enabled or not) *type* type:", "in its current position, 'false' allows movement. *bounds.type* type: String", "of stream matches the given type (usually 'rtmp_custom' or 'rtmp_common').", "bounding box. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\"", "since the start of the media. \"\"\" def __init__(self, sourceName):", "name. *x_scale* type: double Width scale factor. *y_scale* type: double", "String Filter name *filters.*.settings* type: Object Filter settings \"\"\" def", "id specified. Id preferred due to uniqueness per scene *items.*.id*", "None self.dataout['source'] = source def getSource(self): return self.datain['source'] def getIs_local_file(self):", "class SetMediaTime(Baserequests): \"\"\"Set the timestamp of a media source. Supports", "def getSourceName(self): return self.datain['sourceName'] def getImg(self): return self.datain['img'] def getImageFile(self):", "specification (if it is an object). *item.name* type: String (optional)", "item. :Arguments: *fromScene* type: String (optional) Name of the scene", "box. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or", "int (optional) The new amount of pixels cropped off the", "= transition_name class SetTransitionDuration(Baserequests): \"\"\"Set the duration of the currently", "current scene. *item* type: String | Object Scene Item name", "automatically after setting its new position (like a user releasing", "position of the source from the left. *position.y* type: double", "self.dataout['filterName'] = filterName self.dataout['newIndex'] = newIndex class MoveSourceFilter(Baserequests): \"\"\"Move a", "BroadcastCustomMessage(Baserequests): \"\"\"Broadcast custom message to all connected WebSocket clients :Arguments:", "__init__(self): Baserequests.__init__(self) self.name = 'GetCurrentProfile' self.datain['profile-name'] = None def getProfileName(self):", "self.datain['color2'] def getCustom_width(self): return self.datain['custom_width'] def getDrop_shadow(self): return self.datain['drop_shadow'] def", "return self.datain['desktop-1'] def getDesktop2(self): return self.datain['desktop-2'] def getMic1(self): return self.datain['mic-1']", "provided source. States: `none`, `playing`, `opening`, `buffering`, `paused`, `stopped`, `ended`,", "bk_color self.dataout['bk_opacity'] = bk_opacity self.dataout['chatlog'] = chatlog self.dataout['chatlog_lines'] = chatlog_lines", "not. Default `true` :Returns: *itemId* type: int Numerical ID of", "Ignored if `use_auth` is not set to `true`. *stream.settings.password* type:", "enabled, the username for the streaming server. Ignored if `use_auth`", "the name of the currently selected transition in the frontend's", "box. (0-2, 4-6, 8-10) *bounds.x* type: double (optional) The new", "before scaling. *visible* type: bool If the source is visible.", "class RestartMedia(Baserequests): \"\"\"Restart a media source. Supports ffmpeg and vlc", "the bounding box. *bounds.x* type: double Width of the bounding", "your code needs to perform multiple successive T-Bar moves (e.g.", "this hotkey is mandatory, even when triggering saves only through", "filter :Arguments: *sourceName* type: String Name of the source to", "force=None): Baserequests.__init__(self) self.name = 'StopOutput' self.dataout['outputName'] = outputName self.dataout['force'] =", "source from which the specified filter is removed *filterName* type:", "= 'BroadcastCustomMessage' self.dataout['realm'] = realm self.dataout['data'] = data class GetVideoInfo(Baserequests):", "Scene to add the new source to. *sourceSettings* type: Object", "the coordinates of a specified source item. :Arguments: *scene_name* type:", "type: String (optional) Full file path (file extension included) where", "a source :Arguments: *sourceName* type: String Name of the source", "menu. :Returns: *current_transition* type: String Name of the currently active", "supplied offset. Supports ffmpeg and vlc media sources (as of", "copy the item from. Defaults to the current scene. *toScene*", "Absolute path to the recording file (only present if currently", "String The current state of media for that source. States:", "*sources.*.name* type: String Unique source name *sources.*.typeId* type: String Non-unique", "'GetAudioMonitorType' self.datain['monitorType'] = None self.dataout['sourceName'] = sourceName def getMonitorType(self): return", "getRead_from_file(self): return self.datain['read_from_file'] def getFont(self): return self.datain['font'] def getGradient(self): return", "if recording is not active or already paused. \"\"\" def", "def __init__(self, item, scene_name=None, position=None, rotation=None, scale=None, crop=None, visible=None, locked=None,", "*scale.y* type: double (optional) The new y scale of the", "format uses mul, NOT SLIDER PERCENTAGE. :Arguments: *source* type: String", "self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['newIndex'] = newIndex class", "media in milliseconds. Supports ffmpeg and vlc media sources (as", "items self.dataout['scene'] = scene class SetSceneTransitionOverride(Baserequests): \"\"\"Set a scene to", "= sourceName def getTimestamp(self): return self.datain['timestamp'] class SetMediaTime(Baserequests): \"\"\"Set the", "to save the image file as (one of the values", "a filter in the chain (relative positioning) :Arguments: *sourceName* type:", "def getScName(self): return self.datain['sc-name'] class ListSceneCollections(Baserequests): \"\"\"List available scene collections", "'StartStreaming' self.dataout['stream'] = stream class StopStreaming(Baserequests): \"\"\"Stop streaming. Will return", "self.datain['version'] def getObsWebsocketVersion(self): return self.datain['obs-websocket-version'] def getObsStudioVersion(self): return self.datain['obs-studio-version'] def", "String Source name. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name =", "WAS GENERATED BY generate_classes.py - DO NOT EDIT # #", "def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentSceneCollection' self.datain['sc-name'] = None def", "scene and its list of sources. Will return an `error`", "(optional) The publish URL. *stream.settings.key* type: String (optional) The publish", "in use. Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self, sourceName):", "item self.dataout['scene-name'] = scene_name class SetSceneItemRender(Baserequests): \"\"\"Show or hide a", "as embedded CEA-608 caption data. :Arguments: *text* type: String Captions", "tries to guess based on file extension. *compressionQuality* type: int", "the currently active scene. *scenes* type: Array<Scene> Ordered list of", "of streaming service configuration. Possible values: 'rtmp_custom' or 'rtmp_common'. *settings*", "useDecibel=None): Baserequests.__init__(self) self.name = 'SetVolume' self.dataout['source'] = source self.dataout['volume'] =", "*text* type: String Text content to be displayed. *valign* type:", "disk. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'SaveStreamSettings' class SendCaptions(Baserequests):", "auth challenge (see \"Authentication\" for more information). \"\"\" def __init__(self,", "item is a group) \"\"\" def __init__(self, item, scene_name=None): Baserequests.__init__(self)", "None self.datain['bounds'] = None self.datain['sourceWidth'] = None self.datain['sourceHeight'] = None", "= 'GetCurrentTransition' self.datain['name'] = None self.datain['duration'] = None def getName(self):", "None self.datain['gradient_dir'] = None self.datain['gradient_opacity'] = None self.datain['outline'] = None", "boolean Trigger Shift Key *keyModifiers.alt* type: boolean Trigger Alt Key", "= None self.datain['log_mode'] = None self.datain['outline'] = None self.datain['text'] =", "name. :Returns: *source* type: String Source name. *align* type: String", "to false and call `ReleaseTBar` later once the animation/interaction is", "Baserequests.__init__(self) self.name = 'StartStopReplayBuffer' class StartReplayBuffer(Baserequests): \"\"\"Start recording into the", "paused. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ResumeRecording' class SetRecordingFolder(Baserequests):", "OBSRemote compatible API version. Fixed to 1.1 for retrocompatibility. *obs_websocket_version*", "compressionQuality self.dataout['width'] = width self.dataout['height'] = height def getSourceName(self): return", "Unique item id of the source item *sceneItems.*.sourceKind* type: String", "make the sceneitem visible on creation or not. Default `true`", "*shutdown* type: boolean (optional) Indicates whether the source should be", "int (Optional) Monitor to open the projector on. If -1", "*position.alignment* type: int The point on the source that the", "keyModifiers class PlayPauseMedia(Baserequests): \"\"\"Pause or play a media source. Supports", "*font* type: Object Holds data for the font. Ex: `\"font\":", "item. \"\"\" def __init__(self, source, is_local_file=None, local_file=None, url=None, css=None, width=None,", "return self.datain['mic-2'] def getMic3(self): return self.datain['mic-3'] class GetSourceFilters(Baserequests): \"\"\"List filters", "Aspect ratio is preserved if only one of these two", "__init__(self): Baserequests.__init__(self) self.name = 'SaveStreamSettings' class SendCaptions(Baserequests): \"\"\"Send the provided", "base size *fps* type: double Frames rendered per second *videoFormat*", "Strikeout=8` *font.size* type: int Font text size. *font.style* type: String", "more information). \"\"\" def __init__(self, auth): Baserequests.__init__(self) self.name = 'Authenticate'", "of the scene to switch to. \"\"\" def __init__(self, scene_name):", "filter from a source :Arguments: *sourceName* type: String Name of", "(full or partial) \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetVideoInfo'", "'GetSourcesList' self.datain['sources'] = None def getSources(self): return self.datain['sources'] class GetSourceTypesList(Baserequests):", "self.datain['name'] = None self.datain['sources'] = None def getName(self): return self.datain['name']", "Note: If the new name already exists as a source,", "embedPictureFormat self.dataout['saveToFilePath'] = saveToFilePath self.dataout['fileFormat'] = fileFormat self.dataout['compressionQuality'] = compressionQuality", "Type. Value is one of the following: \"input\", \"filter\", \"transition\"", "of the currently selected transition if supported. :Arguments: *duration* type:", "text_file=None, word_wrap=None): Baserequests.__init__(self) self.name = 'SetTextFreetype2Properties' self.dataout['source'] = source self.dataout['color1']", "self.datain['url'] = None self.datain['css'] = None self.datain['width'] = None self.datain['height']", "return self.datain['vertical'] class SetTextGDIPlusProperties(Baserequests): \"\"\"Set the current properties of a", "using dB. *muted* type: boolean Indicates whether the source is", "type: String Source name. *volume* type: double Volume of the", "SetTransitionSettings(Baserequests): \"\"\"Change the current settings of a transition :Arguments: *transitionName*", "`none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name =", "class GetCurrentTransition(Baserequests): \"\"\"Get the name of the currently selected transition", "reorder *newIndex* type: Integer Desired position of the filter in", "`embedPictureFormat` was specified in the request) *imageFile* type: String Absolute", "type: Boolean True if sources of this type provide audio", "a scene. :Arguments: *sourceName* type: String Source name. *sourceKind* type:", "Italic=2, Bold Italic=3, Underline=5, Strikeout=8` *font.size* type: int (optional) Font", "log. *outline* type: boolean Outline. *text* type: String Text content", "already active or if the \"Save Replay Buffer\" hotkey is", "Baserequests.__init__(self) self.name = 'TriggerHotkeyBySequence' self.dataout['keyId'] = keyId self.dataout['keyModifiers'] = keyModifiers", "Buffer\" hotkey is not set in OBS' settings. Setting this", "type: int (Optional) Duration in milliseconds of the transition if", "ID of the SceneItem in the scene. \"\"\" def __init__(self,", "Array<Object> Array of scene items *sceneItems.*.itemId* type: int Unique item", "source *width* type: double Scene item width (base source width", "of all transitions available in the frontend's dropdown menu. :Returns:", "def getRecordingFilename(self): return self.datain['recordingFilename'] class StartStopRecording(Baserequests): \"\"\"Toggle recording on or", "for that source. States: `none`, `playing`, `opening`, `buffering`, `paused`, `stopped`,", "self.dataout['from_file'] = from_file self.dataout['log_mode'] = log_mode self.dataout['outline'] = outline self.dataout['text']", "active transition. *transitions* type: Array<Object> List of transitions. *transitions.*.name* type:", "of the source before scaling. *visible* type: bool If the", "on the source that the item is manipulated from. The", "GetTransitionList(Baserequests): \"\"\"List of all transitions available in the frontend's dropdown", "type: String Name of the source. *is_local_file* type: boolean (optional)", "mute status of a specified source. :Arguments: *source* type: String", "Baserequests.__init__(self) self.name = 'GetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType'] = None", "String Name of the currently active scene collection. \"\"\" def", "processing rate of this request has also not been tested.", "*locked* type: bool If the source's transform is locked. *bounds.type*", "None self.datain['extents'] = None self.datain['extents_cx'] = None self.datain['extents_cy'] = None", "file (only present if currently recording). \"\"\" def __init__(self): Baserequests.__init__(self)", "types). \"\"\" def __init__(self, type, monitor, geometry, name): Baserequests.__init__(self) self.name", "= source def getSource(self): return self.datain['source'] def getColor1(self): return self.datain['color1']", "self.dataout['outline_size'] = outline_size self.dataout['outline_opacity'] = outline_opacity self.dataout['text'] = text self.dataout['valign']", "to true. \"\"\" def __init__(self, position, release=None): Baserequests.__init__(self) self.name =", "self.dataout['word_wrap'] = word_wrap class GetBrowserSourceProperties(Baserequests): \"\"\"Get current properties for a", "\"\"\"Move a filter in the chain (absolute index positioning) :Arguments:", "*transitionDuration* type: int Transition duration. `-1` if no override is", "= sourceName self.dataout['filterName'] = filterName self.dataout['newIndex'] = newIndex class MoveSourceFilter(Baserequests):", "Baserequests.__init__(self) self.name = 'GetMediaTime' self.datain['timestamp'] = None self.dataout['sourceName'] = sourceName", "position of the current transition. :Returns: *position* type: double current", "def getSource(self): return self.datain['source'] def getColor1(self): return self.datain['color1'] def getColor2(self):", "= source def getName(self): return self.datain['name'] def getMuted(self): return self.datain['muted']", "self.datain['obs-studio-version'] = None self.datain['available-requests'] = None self.datain['supported-image-export-formats'] = None def", "stats](#obsstats) \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStats' self.datain['stats'] =", "String Source name *filterName* type: String Source filter name *filterEnabled*", "function). *gradient* type: boolean Gradient enabled. *gradient_color* type: int Gradient", "projector window or create a projector on a monitor. Requires", "type: String (optional) If authentication is enabled, the password for", "item *sceneItems.*.sourceKind* type: String ID if the scene item's source.", "self.dataout['useDecibel'] = useDecibel def getName(self): return self.datain['name'] def getVolume(self): return", "transition override on a scene. :Arguments: *sceneName* type: String Name", "self.name = 'SetCurrentTransition' self.dataout['transition-name'] = transition_name class SetTransitionDuration(Baserequests): \"\"\"Set the", "name. *muted* type: boolean Mute status of the source. \"\"\"", "self.datain['itemId'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceKind'] = sourceKind self.dataout['sceneName']", "boolean (optional) Visibility of the scene item. \"\"\" def __init__(self,", "= None self.datain['sourceWidth'] = None self.datain['sourceHeight'] = None self.datain['width'] =", "self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterSettings'] = filterSettings class", "visible. *render* type: boolean (optional) Visibility of the scene item.", "'GetSyncOffset' self.datain['name'] = None self.datain['offset'] = None self.dataout['source'] = source", "passed will remain unchanged. Returns the updated settings in response.", "Source name. *volume* type: double Volume of the source. Between", "of the source. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name =", "None self.datain['colorRange'] = None def getBaseWidth(self): return self.datain['baseWidth'] def getBaseHeight(self):", "class StopRecording(Baserequests): \"\"\"Stop recording. Will return an `error` if recording", "\"\"\"Get the length of media in milliseconds. Supports ffmpeg and", "Gradient bottom color. *custom_width* type: int Custom width (0 to", "on/off (depending on the current state of the replay buffer).", "source (as of OBS v25.0.8) :Arguments: *sourceName* type: String Source", "source before scaling. *crop.left* type: int The number of pixels", "source's transform is locked. *bounds.type* type: String Type of bounding", "self.name = 'SetCurrentScene' self.dataout['scene-name'] = scene_name class GetCurrentScene(Baserequests): \"\"\"Get the", "Data URI encoded picture. Can be \"png\", \"jpg\", \"jpeg\" or", "relative to the item's parent (the scene or group it", "self.datain['itemId'] = None self.datain['position'] = None self.datain['rotation'] = None self.datain['scale']", "or 'rtmp_common'). If the currently configured stream type does not", "off the top of the source before scaling. *crop.bottom* type:", "User-defined data \"\"\" def __init__(self, realm, data): Baserequests.__init__(self) self.name =", "return self.datain['name'] def getVolume(self): return self.datain['volume'] def getMuted(self): return self.datain['muted']", "type: boolean Current recording status. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "GetMediaSourcesList(Baserequests): \"\"\"List the media state of all media sources (vlc", "= 'SetRecordingFolder' self.dataout['rec-folder'] = rec_folder class GetRecordingFolder(Baserequests): \"\"\"Get the path", "*stats* type: OBSStats [OBS stats](#obsstats) \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "or group it belongs to). :Arguments: *scene_name* type: String (optional)", "type: int (optional) Transition duration (in milliseconds). \"\"\" def __init__(self,", "*baseHeight* type: int Base (canvas) height *outputWidth* type: int Output", "None def getProfileName(self): return self.datain['profile-name'] class ListProfiles(Baserequests): \"\"\"Get a list", "self.name = 'MoveSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['movementType']", "self.dataout['chatlog'] = chatlog self.dataout['chatlog_lines'] = chatlog_lines self.dataout['color'] = color self.dataout['extents']", "a new filter to a source. Available source types along", "Source name. *timeOffset* type: int Millisecond offset (positive or negative)", "Baserequests.__init__(self) self.name = 'GetVersion' self.datain['version'] = None self.datain['obs-websocket-version'] = None", "Array<Object> Array of source types *types.*.typeId* type: String Non-unique internal", "def __init__(self, items, scene=None): Baserequests.__init__(self) self.name = 'ReorderSceneItems' self.dataout['items'] =", "Eg. `vlc_source`. *sceneName* type: String Scene to add the new", "type: Array<Scene> Ordered list of the current profile's scenes (See", "source. :Arguments: *source* type: String Source name. :Returns: *source* type:", "self.datain['chatlog'] = None self.datain['chatlog_lines'] = None self.datain['color'] = None self.datain['extents']", "*local_file* type: String (optional) file path. *url* type: String (optional)", "*timestamp* type: int Milliseconds to set the timestamp to. \"\"\"", "self.datain['sources'] = None def getName(self): return self.datain['name'] def getSources(self): return", "Font Style (unknown function). *gradient* type: boolean Gradient enabled. *gradient_color*", "= item self.dataout['fromScene'] = fromScene self.dataout['toScene'] = toScene def getScene(self):", "new filter to a source. Available source types along with", "item's source. For example `vlc_source` or `image_source` *sceneItems.*.sourceName* type: String", "settings \"\"\" def __init__(self, sourceName, filterName): Baserequests.__init__(self) self.name = 'GetSourceFilterInfo'", "it as a sceneitem to a scene. :Arguments: *sourceName* type:", "provide audio *types.*.caps.canInteract* type: Boolean True if interaction with this", "the currently active scene is used. *embedPictureFormat* type: String (optional)", "you set `release` to false. Defaults to true. \"\"\" def", "= None self.datain['fps'] = None self.datain['videoFormat'] = None self.datain['colorSpace'] =", "= 'CreateScene' self.dataout['sceneName'] = sceneName class ReorderSceneItems(Baserequests): \"\"\"Changes the order", "None self.dataout['source'] = source self.dataout['useDecibel'] = useDecibel def getName(self): return", "type: String (optional) If specified ensures the type of stream", "type: String Source name. :Returns: *name* type: String Source name.", "status of the source. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name", "saveToFilePath=None, fileFormat=None, compressionQuality=None, width=None, height=None): Baserequests.__init__(self) self.name = 'TakeSourceScreenshot' self.datain['sourceName']", "None self.dataout['source'] = source def getSource(self): return self.datain['source'] def getAlign(self):", "= None self.datain['videoFormat'] = None self.datain['colorSpace'] = None self.datain['colorRange'] =", "active preview scene. *sources* type: Array<SceneItem> \"\"\" def __init__(self): Baserequests.__init__(self)", "Path of the recording folder. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "String List of supported formats for features that use image", "None self.datain['rotation'] = None self.datain['scale'] = None self.datain['crop'] = None", "getExtents_cy(self): return self.datain['extents_cy'] def getFile(self): return self.datain['file'] def getRead_from_file(self): return", "formatting string to set. \"\"\" def __init__(self, filename_formatting): Baserequests.__init__(self) self.name", "Word wrap. \"\"\" def __init__(self, source, color1=None, color2=None, custom_width=None, drop_shadow=None,", "later once the animation/interaction is over. :Arguments: *position* type: double", "version. Fixed to 1.1 for retrocompatibility. *obs_websocket_version* type: String obs-websocket", "The password for the streaming service. *save* type: boolean Persist", "-*- # THIS FILE WAS GENERATED BY generate_classes.py - DO", "return self.datain['colorSpace'] def getColorRange(self): return self.datain['colorRange'] class OpenProjector(Baserequests): \"\"\"Open a", "export (like the TakeSourceScreenshot request type) formatted as a comma-separated", "self.datain['settings'] class SaveStreamSettings(Baserequests): \"\"\"Save the current streaming server settings to", "text=None, valign=None, vertical=None, render=None): Baserequests.__init__(self) self.name = 'SetTextGDIPlusProperties' self.dataout['source'] =", "ID (if the `item` field is an object) *position.x* type:", "to a group) *groupChildren* type: Array<SceneItemTransform> (optional) List of children", "this way. :Arguments: *outputName* type: String Output name *force* type:", ":Returns: *scene_collections* type: Array<String> Scene collections list *scene_collections.*.sc_name* type: String", "\"\"\"Get the current scene's name and source items. :Returns: *name*", "the frontend's dropdown menu. :Returns: *name* type: String Name of", "visible on creation or not. Default `true` :Returns: *itemId* type:", "source def getSource(self): return self.datain['source'] def getAlign(self): return self.datain['align'] def", "= 'SetSceneItemRender' self.dataout['source'] = source self.dataout['render'] = render self.dataout['scene-name'] =", "(canvas) height *outputWidth* type: int Output width *outputHeight* type: int", "item, scene_name=None): Baserequests.__init__(self) self.name = 'ResetSceneItem' self.dataout['item'] = item self.dataout['scene-name']", "= sourceSettings self.dataout['setVisible'] = setVisible def getItemId(self): return self.datain['itemId'] class", "the streaming server. Only present if `use_auth` is `true`. *settings.password*", "amount of pixels cropped off the left of the source", "type: int Pixel position of the top of the source", "SceneItem in the scene. \"\"\" def __init__(self, sourceName, sourceKind, sceneName,", "type: double (optional) The new clockwise rotation of the item", "OBS' configuration. *stream.type* type: String (optional) If specified ensures the", "of the item in degrees. *scale.x* type: double (optional) The", "string) or specification (if it is an object). *item.name* type:", "item. *scale.y* type: double (optional) The new y scale of", "is removed *filterName* type: String Name of the filter to", "Defaults to the current scene. *item* type: Object Scene Item", "*item* type: String Scene Item name. *x* type: double X", "= scene_name class SetSceneItemPosition(Baserequests): \"\"\"Sets the coordinates of a specified", "off the right of the source before scaling. *crop.bottom* type:", "*useDecibel* type: boolean (optional) Interperet `volume` data as decibels instead", "= 'SetSceneTransitionOverride' self.dataout['sceneName'] = sceneName self.dataout['transitionName'] = transitionName self.dataout['transitionDuration'] =", "*saveToFilePath* type: String (optional) Full file path (file extension included)", "enable class SetFilenameFormatting(Baserequests): \"\"\"Set the filename formatting string :Arguments: *filename_formatting*", "sourceName): Baserequests.__init__(self) self.name = 'NextMedia' self.dataout['sourceName'] = sourceName class PreviousMedia(Baserequests):", "\"\"\" def __init__(self, position, release=None): Baserequests.__init__(self) self.name = 'SetTBarPosition' self.dataout['position']", "name (if this field is a string) or specification (if", "composite one or more sub-sources *types.*.caps.doNotDuplicate* type: Boolean True if", "OBS's saved projectors. *name* type: String (Optional) Name of the", "return self.datain['studio-mode'] class GetPreviewScene(Baserequests): \"\"\"Get the name of the currently", "source from the top. *position.alignment* type: int The point on", "self.datain['volume'] = None self.datain['muted'] = None self.dataout['source'] = source self.dataout['useDecibel']", "recording started (only present if currently recording). *preview_only* type: boolean", "scene. :Arguments: *scene* type: String (optional) Name of the scene", "Font Style (unknown function). *from_file* type: boolean Read text from", "base width. *height* type: int (optional) Screenshot height. Defaults to", "def __init__(self, sourceName, filterName, filterSettings): Baserequests.__init__(self) self.name = 'SetSourceFilterSettings' self.dataout['sourceName']", "= profile_name class GetCurrentProfile(Baserequests): \"\"\"Get the name of the current", "sourceName, filterName): Baserequests.__init__(self) self.name = 'RemoveFilterFromSource' self.dataout['sourceName'] = sourceName self.dataout['filterName']", "__init__(self): Baserequests.__init__(self) self.name = 'GetAuthRequired' self.datain['authRequired'] = None self.datain['challenge'] =", "reconfigure *filterSettings* type: Object New settings. These will be merged", "is different than the current streaming service type, all settings", "*source* type: String Source name. *volume* type: double Desired volume.", "on the current stream state). \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "self.datain['recordingFilename'] = None def getIsRecording(self): return self.datain['isRecording'] def getIsRecordingPaused(self): return", "type: Object (Optional) Optional key modifiers object. False entries can", "Name of the desired scene collection. \"\"\" def __init__(self, sc_name):", "`paused`, `stopped`, `ended`, `error`, `unknown` \"\"\" def __init__(self, sourceName): Baserequests.__init__(self)", ":Arguments: *source* type: String Source name. :Returns: *name* type: String", "to. \"\"\" def __init__(self, sourceName, timestamp): Baserequests.__init__(self) self.name = 'SetMediaTime'", "(if the `item` field is an object) :Returns: *name* type:", "__init__(self, item, fromScene=None, toScene=None): Baserequests.__init__(self) self.name = 'DuplicateSceneItem' self.datain['scene'] =", "self.datain['settings'] = None def getType(self): return self.datain['type'] def getSettings(self): return", "the source. *crop.top* type: int The number of pixels cropped", "Output name *force* type: boolean (optional) Force stop (default: false)", "face. *font.flags* type: int (optional) Font text styling flag. `Bold=1,", "*filterName* type: String Source filter name *filterEnabled* type: Boolean New", "obs-websocket. Some plugins which add outputs to OBS may not", "\"\"\"Create a new scene scene. :Arguments: *sceneName* type: String Name", "self.datain['scene-collections'] = None def getSceneCollections(self): return self.datain['scene-collections'] class GetSceneItemList(Baserequests): \"\"\"Get", "whether the source should be shutdown when not visible. \"\"\"", "the total duration can be off by upwards of 50ms.", "specified source. :Arguments: *source* type: String Source name. *mute* type:", "*filters.*.enabled* type: Boolean Filter status (enabled or not) *filters.*.type* type:", "return self.datain['item'] class SetCurrentScene(Baserequests): \"\"\"Switch to the specified scene. :Arguments:", "*name* type: String Name of the selected transition. *duration* type:", "the specified file. *font* type: Object (optional) Holds data for", "Array<Object> Array of sources *mediaSources.*.sourceName* type: String Unique source name", ":Returns: *authRequired* type: boolean Indicates whether authentication is required. *challenge*", "scene. *item* type: String Scene Item name. *x* type: double", "self.dataout['playPause'] = playPause class RestartMedia(Baserequests): \"\"\"Restart a media source. Supports", "create a projector on a monitor. Requires OBS v24.0.4 or", "sceneName self.dataout['transitionName'] = transitionName self.dataout['transitionDuration'] = transitionDuration class RemoveSceneTransitionOverride(Baserequests): \"\"\"Remove", "(optional) The new bounds type of the source. Can be", "type: boolean Indicates that a local file is in use.", "type: boolean Chat log. *outline* type: boolean Outline. *text* type:", "to use. *transitionDuration* type: int (Optional) Duration in milliseconds of", "file is in use. *local_file* type: String (optional) file path.", "*sourceSettings* type: Object Updated source settings \"\"\" def __init__(self, sourceName,", "self.dataout['transitionSettings'] = transitionSettings def getTransitionSettings(self): return self.datain['transitionSettings'] class ReleaseTBar(Baserequests): \"\"\"Release", "the scene the source item belongs to. Defaults to the", "None self.datain['mic-2'] = None self.datain['mic-3'] = None def getDesktop1(self): return", "type: int (optional) Width. *height* type: int (optional) Height. *fps*", "(optional) Force stop (default: false) \"\"\" def __init__(self, outputName, force=None):", "None self.datain['gradient_color'] = None self.datain['gradient_dir'] = None self.datain['gradient_opacity'] = None", "class MoveSourceFilter(Baserequests): \"\"\"Move a filter in the chain (relative positioning)", "(optional) Name of the item's parent (if this item belongs", "Studio program version. *available_requests* type: String List of available request", "*embedPictureFormat* type: String (optional) Format of the Data URI encoded", "self.name = 'GetSceneItemProperties' self.datain['name'] = None self.datain['itemId'] = None self.datain['position']", "-100.0 as Inf. Note: The OBS volume sliders only reach", "getProfileName(self): return self.datain['profile-name'] class ListProfiles(Baserequests): \"\"\"Get a list of available", "\"\"\" def __init__(self, source, mute): Baserequests.__init__(self) self.name = 'SetMute' self.dataout['source']", "type: String Source name. :Returns: *source* type: String Source name", "rendered per second *videoFormat* type: String Video color format *colorSpace*", "Current streaming status. *recording* type: boolean Current recording status. *stream_timecode*", "source, mute): Baserequests.__init__(self) self.name = 'SetMute' self.dataout['source'] = source self.dataout['mute']", "scale factor. *rotation* type: double Source item rotation (in degrees).", "of these two parameters is specified. :Arguments: *sourceName* type: String", "outline_size=None, outline_opacity=None, text=None, valign=None, vertical=None, render=None): Baserequests.__init__(self) self.name = 'SetTextGDIPlusProperties'", "Scene Item name. *x* type: double X coordinate. *y* type:", "int (optional) Background opacity (0-100). *chatlog* type: boolean (optional) Chat", "transitionName, transitionDuration): Baserequests.__init__(self) self.name = 'SetSceneTransitionOverride' self.dataout['sceneName'] = sceneName self.dataout['transitionName']", "*position* type: double T-Bar position. This value must be between", "content to be displayed. *text_file* type: String File path. *word_wrap*", "specific settings schema. :Returns: *sourceName* type: String Source name *sourceType*", "scene. *item* type: Object Scene Item to duplicate from the", "getGradient(self): return self.datain['gradient'] def getGradient_color(self): return self.datain['gradient_color'] def getGradient_dir(self): return", "bounds=None): Baserequests.__init__(self) self.name = 'SetSceneItemProperties' self.dataout['item'] = item self.dataout['scene-name'] =", "= outputName class StopOutput(Baserequests): \"\"\" Note: Controlling outputs is an", "*filters.*.name* type: String Filter name *filters.*.settings* type: Object Filter settings", "for key \"A\"). Available identifiers [here](https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h) *keyModifiers* type: Object (Optional)", "(vlc and media source) :Returns: *mediaSources* type: Array<Object> Array of", "*custom_width* type: int Custom width (0 to disable). *drop_shadow* type:", "off the right of the source before scaling. *visible* type:", "If so, returns authentication parameters `challenge` and `salt` (see \"Authentication\"", "return self.datain['profile-name'] class ListProfiles(Baserequests): \"\"\"Get a list of available profiles.", "realm self.dataout['data'] = data class GetVideoInfo(Baserequests): \"\"\"Get basic OBS video", "getIsRecording(self): return self.datain['isRecording'] def getIsRecordingPaused(self): return self.datain['isRecordingPaused'] def getRecordTimecode(self): return", "height of the bounding box. \"\"\" def __init__(self, item, scene_name=None,", "properties of a Text Freetype 2 source. :Arguments: *source* type:", "self.datain['muted'] = None self.datain['locked'] = None self.datain['bounds'] = None self.datain['sourceWidth']", "Ordered list of the current scene's source items. \"\"\" def", "the currently active scene collection. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemCrop' self.dataout['item'] = item self.dataout['top'] =", "Baserequests.__init__(self) self.name = 'StartStreaming' self.dataout['stream'] = stream class StopStreaming(Baserequests): \"\"\"Stop", "under 26.0 for dB. OBS will interpret dB values under", "def __init__(self): Baserequests.__init__(self) self.name = 'SaveReplayBuffer' class SetCurrentSceneCollection(Baserequests): \"\"\"Change the", "class GetCurrentScene(Baserequests): \"\"\"Get the current scene's name and source items.", "For some reason, for the first 5 or so seconds", "name \"\"\" def __init__(self, outputName): Baserequests.__init__(self) self.name = 'StartOutput' self.dataout['outputName']", "this type should not be fully duplicated *types.*.caps.doNotSelfMonitor* type: Boolean", "*types.*.caps.isAsync* type: Boolean True if source of this type provide", "\"\"\"Save the current streaming server settings to disk. \"\"\" def", "self.dataout['sourceName'] = sourceName self.dataout['setVisible'] = setVisible def getItemId(self): return self.datain['itemId']", "a source and add it as a sceneitem to a", "mouse button after moving it). *YOU MUST CALL THIS if", "Plus source. :Arguments: *source* type: String Source name. :Returns: *source*", "String (optional) Name of the scene the source item belongs", "ommitted *keyModifiers.shift* type: boolean Trigger Shift Key *keyModifiers.alt* type: boolean", "None def getSources(self): return self.datain['sources'] class GetSourceTypesList(Baserequests): \"\"\"Get a list", "type: String Source name. *timestamp* type: int Milliseconds to set", "= None def getStreaming(self): return self.datain['streaming'] def getRecording(self): return self.datain['recording']", "Desired volume. Must be between `0.0` and `20.0` for mul,", "to open the projector on. If -1 or omitted, opens", "*read_from_file* type: boolean Read text from the specified file. *font*", "def getSources(self): return self.datain['sources'] class GetSourceTypesList(Baserequests): \"\"\"Get a list of", "feedback loop if it's audio is monitored and shouldn't be", "getImg(self): return self.datain['img'] def getImageFile(self): return self.datain['imageFile'] class ListOutputs(Baserequests): \"\"\"List", "media in milliseconds.. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name =", "active profile. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentProfile' self.datain['profile-name']", "= 'GetTextFreetype2Properties' self.datain['source'] = None self.datain['color1'] = None self.datain['color2'] =", "String Source name. *is_local_file* type: boolean Indicates that a local", "'SetRecordingFolder' self.dataout['rec-folder'] = rec_folder class GetRecordingFolder(Baserequests): \"\"\"Get the path of", "your User Interface), set `release` to false and call `ReleaseTBar`", "(optional) Text color. *extents* type: boolean (optional) Extents wrap. *extents_cx*", "response field of `GetVersion`). If not specified, tries to guess", "move the filter around in the source's filter chain. Either", "color2 self.dataout['custom_width'] = custom_width self.dataout['drop_shadow'] = drop_shadow self.dataout['font'] = font", "Output width *outputHeight* type: int Output height *scaleType* type: String", "String Source name. *offset* type: int The desired audio sync", "self.dataout['custom_width'] = custom_width self.dataout['drop_shadow'] = drop_shadow self.dataout['font'] = font self.dataout['from_file']", "type: String (Optional) Size and position of the projector window", "\"\"\" Please note: if `SetRecordingFolder` is called while a recording", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetAuthRequired' self.datain['authRequired'] = None", "self.datain['outline_size'] def getOutline_opacity(self): return self.datain['outline_opacity'] def getText(self): return self.datain['text'] def", "in milliseconds of the transition if transition is not fixed.", "item height (base source height multiplied by the vertical scaling", "self.datain['mediaSources'] = None def getMediaSources(self): return self.datain['mediaSources'] class CreateSource(Baserequests): \"\"\"Create", "'EnableStudioMode' class DisableStudioMode(Baserequests): \"\"\"Disables Studio Mode. \"\"\" def __init__(self): Baserequests.__init__(self)", "self.dataout['bk_color'] = bk_color self.dataout['bk_opacity'] = bk_opacity self.dataout['chatlog'] = chatlog self.dataout['chatlog_lines']", "__init__(self): Baserequests.__init__(self) self.name = 'GetMediaSourcesList' self.datain['mediaSources'] = None def getMediaSources(self):", "scene_name): Baserequests.__init__(self) self.name = 'SetPreviewScene' self.dataout['scene-name'] = scene_name class TransitionToProgram(Baserequests):", "self.datain['monitorType'] class SetAudioMonitorType(Baserequests): \"\"\"Set the audio monitoring type of the", "= sourceName self.dataout['playPause'] = playPause class RestartMedia(Baserequests): \"\"\"Restart a media", "or \"other\" *types.*.defaultSettings* type: Object Default settings of this source", "the specified source item. :Arguments: *scene_name* type: String (optional) Name", "the source before scaling. *crop.right* type: int The number of", "\"\"\"Get current streaming and recording status. :Returns: *streaming* type: boolean", "def getFont(self): return self.datain['font'] def getFrom_file(self): return self.datain['from_file'] def getLog_mode(self):", "type provide video *types.*.caps.hasAudio* type: Boolean True if sources of", "return an `error` if recording is not active. \"\"\" def", "= 'StartReplayBuffer' class StopReplayBuffer(Baserequests): \"\"\"Stop recording into the Replay Buffer.", "def __init__(self, source): Baserequests.__init__(self) self.name = 'GetTextFreetype2Properties' self.datain['source'] = None", "__init__(self, source): Baserequests.__init__(self) self.name = 'GetSyncOffset' self.datain['name'] = None self.datain['offset']", "(case insensitive). *monitor* type: int (Optional) Monitor to open the", "whether authentication is required. *challenge* type: String (optional) *salt* type:", "or not) *filters.*.type* type: String Filter type *filters.*.name* type: String", "`input`, `group`, or `scene` \"\"\" def __init__(self, sceneName=None): Baserequests.__init__(self) self.name", "to the current scene. *item* type: String Scene Item name.", "*crop.right* type: int The number of pixels cropped off the", "class ResumeRecording(Baserequests): \"\"\"Resume/unpause the current recording (if paused). Returns an", "scene item in a scene. In other words, this is", "scene to create the scene item in *sourceName* type: String", "type: int (optional) Compression ratio between -1 and 100 to", "def getMuted(self): return self.datain['muted'] class SetVolume(Baserequests): \"\"\"Set the volume of", "currently active scene. *source* type: String Scene Item name. *render*", "self.name = 'SetBrowserSourceProperties' self.dataout['source'] = source self.dataout['is_local_file'] = is_local_file self.dataout['local_file']", "and vlc media sources (as of OBS v25.0.8) Note: For", "will be between 0.0 and 1.0. Note: Transition returns 1.0", "it's audio is monitored and shouldn't be \"\"\" def __init__(self):", "wrap. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetTextFreetype2Properties' self.datain['source']", "items from. Defaults to the current scene if not specified.", "\"\"\" def __init__(self, item, scene_name=None): Baserequests.__init__(self) self.name = 'GetSceneItemProperties' self.datain['name']", "*top* type: int Pixel position of the top of the", "\"\"\"Change the visibility/enabled state of a filter :Arguments: *sourceName* type:", "__init__(self): Baserequests.__init__(self) self.name = 'GetReplayBufferStatus' self.datain['isReplayBufferActive'] = None def getIsReplayBufferActive(self):", "acceptable). *item.id* type: int Scene Item ID. :Returns: *scene* type:", "= custom_width self.dataout['drop_shadow'] = drop_shadow self.dataout['font'] = font self.dataout['from_file'] =", "= source self.dataout['volume'] = volume self.dataout['useDecibel'] = useDecibel class GetMute(Baserequests):", "getSourceHeight(self): return self.datain['sourceHeight'] def getWidth(self): return self.datain['width'] def getHeight(self): return", "source. Useful for type-checking if you expect a specific settings", "self.dataout['scene-name'] = scene_name class SetSceneItemPosition(Baserequests): \"\"\"Sets the coordinates of a", "of this type provide video *types.*.caps.hasAudio* type: Boolean True if", "boolean Starts/Stops emitting heartbeat messages \"\"\" def __init__(self, enable): Baserequests.__init__(self)", "of the current transition. :Returns: *position* type: double current transition", "Must be between `0.0` and `20.0` for mul, and under", "(optional) Gradient color. *gradient_dir* type: float (optional) Gradient direction. *gradient_opacity*", "is paused or not. *recordTimecode* type: String (optional) Time elapsed", "The publish key of the stream. *settings.use_auth* type: boolean Indicates", "filterName class ReorderSourceFilter(Baserequests): \"\"\"Move a filter in the chain (absolute", "by upwards of 50ms. :Arguments: *sourceName* type: String Source name.", "self.datain['bk_color'] = None self.datain['bk_opacity'] = None self.datain['chatlog'] = None self.datain['chatlog_lines']", "scene_name def getName(self): return self.datain['name'] def getItemId(self): return self.datain['itemId'] def", "collection. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentSceneCollection' self.datain['sc-name'] =", "`Bold=1, Italic=2, Bold Italic=3, Underline=5, Strikeout=8` *font.size* type: int (optional)", "service type, all settings are required. Returns the full settings", "configuration, usually `rtmp_custom` or `rtmp_common`. *settings* type: Object The actual", "getParentGroupName(self): return self.datain['parentGroupName'] def getGroupChildren(self): return self.datain['groupChildren'] class SetSceneItemProperties(Baserequests): \"\"\"Sets", "switch to. \"\"\" def __init__(self, scene_name): Baserequests.__init__(self) self.name = 'SetCurrentScene'", "*videoFormat* type: String Video color format *colorSpace* type: String Color", "type of streaming service configuration, usually `rtmp_custom` or `rtmp_common`. *settings*", "is_local_file=None, local_file=None, url=None, css=None, width=None, height=None, fps=None, shutdown=None, render=None): Baserequests.__init__(self)", "List of filters for the specified source *filters.*.enabled* type: Boolean", "self.name = 'SetCurrentSceneCollection' self.dataout['sc-name'] = sc_name class GetCurrentSceneCollection(Baserequests): \"\"\"Get the", "__init__(self): Baserequests.__init__(self) self.name = 'ListSceneCollections' self.datain['scene-collections'] = None def getSceneCollections(self):", "Baserequests.__init__(self) self.name = 'SetCurrentProfile' self.dataout['profile-name'] = profile_name class GetCurrentProfile(Baserequests): \"\"\"Get", "the source before scaling. *crop.bottom* type: int The number of", "data. :Arguments: *text* type: String Captions text \"\"\" def __init__(self,", "is not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'SaveReplayBuffer'", "sources within the scene. \"\"\" def __init__(self, items, scene=None): Baserequests.__init__(self)", "self.dataout['timestamp'] = timestamp class ScrubMedia(Baserequests): \"\"\"Scrub media using a supplied", "String (optional) Text Alignment (\"left\", \"center\", \"right\"). *bk_color* type: int", "type: int Background opacity (0-100). *chatlog* type: boolean Chat log.", "String (optional) Font Style (unknown function). *from_file* type: boolean (optional)", "is `true`. *settings.password* type: String The password to use when", "filterSettings): Baserequests.__init__(self) self.name = 'AddFilterToSource' self.dataout['sourceName'] = sourceName self.dataout['filterName'] =", "String File path. *word_wrap* type: boolean Word wrap. \"\"\" def", "*read_from_file* type: boolean (optional) Read text from the specified file.", "publish key. *settings.use_auth* type: boolean (optional) Indicates whether authentication should", "__init__(self, transitionName): Baserequests.__init__(self) self.name = 'GetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName']", "audio sync offset (in nanoseconds). \"\"\" def __init__(self, source, offset):", "type: Array<SceneItemTransform> (optional) List of children (if this item is", "server settings. :Returns: *type* type: String The type of streaming", "of the scene to copy the item from. Defaults to", "Item ID. *position.x* type: double The x position of the", "float Gradient direction. *gradient_opacity* type: int Gradient opacity (0-100). *outline*", "Control (Ctrl) Key *keyModifiers.command* type: boolean Trigger Command Key (Mac)", "the name of the currently previewed scene and its list", "= 'SetSceneItemCrop' self.dataout['item'] = item self.dataout['top'] = top self.dataout['bottom'] =", "height (base source height multiplied by the vertical scaling factor)", "return self.datain['sources'] class SetPreviewScene(Baserequests): \"\"\"Set the active preview scene. Will", "= sourceName class NextMedia(Baserequests): \"\"\"Skip to the next media item", "list of scene items from. Defaults to the current scene", "of the source *sourceHeight* type: int Base source (without scaling)", ":Returns: *types* type: Array<Object> Array of source types *types.*.typeId* type:", "self.datain['challenge'] def getSalt(self): return self.datain['salt'] class Authenticate(Baserequests): \"\"\"Attempt to authenticate", "already active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartRecording' class", "open the projector on. If -1 or omitted, opens a", "self.datain['vertical'] = None self.dataout['source'] = source def getSource(self): return self.datain['source']", "Source name. :Returns: *monitorType* type: String The monitor type in", "type: int Framerate. *shutdown* type: boolean Indicates whether the source", "folder. :Returns: *rec_folder* type: String Path of the recording folder.", "*gradient_color* type: int Gradient color. *gradient_dir* type: float Gradient direction.", "int Custom width (0 to disable). *drop_shadow* type: boolean Drop", "Source type. Value is one of the following: \"input\", \"filter\",", "GENERATED BY generate_classes.py - DO NOT EDIT # # (Generated", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartReplayBuffer' class StopReplayBuffer(Baserequests): \"\"\"Stop", "setting its new position (like a user releasing their mouse", "= None self.dataout['sourceName'] = sourceName def getMediaState(self): return self.datain['mediaState'] class", "self.datain['source'] def getColor1(self): return self.datain['color1'] def getColor2(self): return self.datain['color2'] def", "Only present if `use_auth` is `true`. *settings.password* type: String The", "to reorder *movementType* type: String How to move the filter", "sources of this type provide video *types.*.caps.hasAudio* type: Boolean True", "self.dataout['color2'] = color2 self.dataout['custom_width'] = custom_width self.dataout['drop_shadow'] = drop_shadow self.dataout['font']", "self.dataout['shutdown'] = shutdown self.dataout['render'] = render class GetSpecialSources(Baserequests): \"\"\"Get configured", "required. *challenge* type: String (optional) *salt* type: String (optional) \"\"\"", "type: Boolean True if sources of this type may cause", "type: String (optional) Name of a scene item. Sufficiently unique", "is mandatory, even when triggering saves only through obs-websocket. \"\"\"", "of the specified source. Useful for type-checking if you expect", "getColor1(self): return self.datain['color1'] def getColor2(self): return self.datain['color2'] def getCustom_width(self): return", "scene is used. *embedPictureFormat* type: String (optional) Format of the", "return self.datain['sourceName'] def getSourceType(self): return self.datain['sourceType'] def getSourceSettings(self): return self.datain['sourceSettings']", "self.datain['fps'] = None self.datain['shutdown'] = None self.dataout['source'] = source def", "base height. :Returns: *sourceName* type: String Source name *img* type:", "getImageFile(self): return self.datain['imageFile'] class ListOutputs(Baserequests): \"\"\"List existing outputs :Returns: *outputs*", "the streaming. May be any String, Numeric, or Boolean field.", "type: String The type of streaming service configuration, usually `rtmp_custom`", "stats (almost the same info as provided in OBS' stats", "not fixed. Defaults to the current duration specified in the", "of the item. *crop.top* type: int (optional) The new amount", "None self.datain['outline_opacity'] = None self.datain['text'] = None self.datain['valign'] = None", ":Arguments: *position* type: double T-Bar position. This value must be", "text_file self.dataout['word_wrap'] = word_wrap class GetBrowserSourceProperties(Baserequests): \"\"\"Get current properties for", "String Name of the scene to switch to. \"\"\" def", "type: boolean (optional) Chat log. *outline* type: boolean (optional) Outline.", "is in use. *local_file* type: String (optional) file path. *url*", "'GetTransitionList' self.datain['current-transition'] = None self.datain['transitions'] = None def getCurrentTransition(self): return", "using mul, under `26.0` if using dB. *muted* type: boolean", "`unknown` \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaState' self.datain['mediaState']", "(\"top\", \"center\", \"bottom\"). *vertical* type: boolean (optional) Vertical text enabled.", "(optional) Time elapsed since streaming started (only present if currently", "provided, the currently active scene is used. *embedPictureFormat* type: String", "the source from which the specified filter is removed *filterName*", "self.datain['sourceSettings'] class GetTextGDIPlusProperties(Baserequests): \"\"\"Get the current properties of a Text", "def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetAudioActive' self.datain['audioActive'] = None", "Outputs list \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListOutputs' self.datain['outputs']", "Type of projector: `Preview` (default), `Source`, `Scene`, `StudioProgram`, or `Multiview`", "streaming server settings to disk. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "getSceneName(self): return self.datain['sceneName'] def getSceneItems(self): return self.datain['sceneItems'] class GetSceneItemProperties(Baserequests): \"\"\"Gets", "*sourceName* type: String Source name. *sourceType* type: String (optional) Type", "= None self.datain['gradient'] = None self.datain['gradient_color'] = None self.datain['gradient_dir'] =", "uniqueness per scene *items.*.id* type: int (optional) Id of a", "def getRecordTimecode(self): return self.datain['recordTimecode'] def getRecordingFilename(self): return self.datain['recordingFilename'] class StartStopRecording(Baserequests):", "source self.dataout['volume'] = volume self.dataout['useDecibel'] = useDecibel class GetMute(Baserequests): \"\"\"Get", "\"\"\"List filters applied to a source :Arguments: *sourceName* type: String", "that the media is playing, the total duration can be", "(base source height multiplied by the vertical scaling factor) *parentGroupName*", "self.datain['file'] = None self.datain['read_from_file'] = None self.datain['font'] = None self.datain['gradient']", "*transitionSettings* type: Object Updated transition settings \"\"\" def __init__(self, transitionName,", "getFont(self): return self.datain['font'] def getFrom_file(self): return self.datain['from_file'] def getLog_mode(self): return", "= x_scale self.dataout['y-scale'] = y_scale self.dataout['rotation'] = rotation self.dataout['scene-name'] =", "or 'rtmp_common'. *settings* type: Object Stream settings object. *settings.server* type:", "Item name (if this field is a string) or specification", "the Data URI encoded picture. Can be \"png\", \"jpg\", \"jpeg\"", "scene to create the item in. Defaults to the current", "multiple hotkey routines depending on user settings :Arguments: *keyId* type:", "in the `settings` object or an error will occur when", ":Arguments: *sceneName* type: String (optional) Name of the scene to", "y, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemPosition' self.dataout['item'] = item self.dataout['x']", "*scaleType* type: String Scaling method used if output size differs", "ID (if the `item` field is an object) \"\"\" def", "sceneName, sourceSettings=None, setVisible=None): Baserequests.__init__(self) self.name = 'CreateSource' self.datain['itemId'] = None", "return self.datain['muted'] class SetMute(Baserequests): \"\"\"Sets the mute status of a", "sources of this type should not be fully duplicated *types.*.caps.doNotSelfMonitor*", "type: boolean (optional) Indicates that a local file is in", "Baserequests.__init__(self) self.name = 'ReorderSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName", "-1 is automatic, 1 is smallest file/most compression, 100 is", "the current recording. Returns an error if recording is not", "Baserequests.__init__(self) self.name = 'GetStreamingStatus' self.datain['streaming'] = None self.datain['recording'] = None", "The publish key of the stream. *stream.settings.use_auth* type: boolean (optional)", "*recordTimecode* type: String (optional) Time elapsed since recording started (only", "available profiles. :Returns: *profiles* type: Array<Object> List of available profiles.", "the `item` field is an object) \"\"\" def __init__(self, item,", "type: Object Source type capabilities *types.*.caps.isAsync* type: Boolean True if", "OpenProjector(Baserequests): \"\"\"Open a projector window or create a projector on", "scene_name class DeleteSceneItem(Baserequests): \"\"\"Deletes a scene item. :Arguments: *scene* type:", "self.dataout['sourceName'] = sourceName class StopMedia(Baserequests): \"\"\"Stop a media source. Supports", "sources of this type composite one or more sub-sources *types.*.caps.doNotDuplicate*", "; false = hidden \"\"\" def __init__(self, source, render, scene_name=None):", "enable): Baserequests.__init__(self) self.name = 'SetHeartbeat' self.dataout['enable'] = enable class SetFilenameFormatting(Baserequests):", "the point of alignment. *scale.x* type: double The x-scale factor", "(optional) Font face. *font.flags* type: int (optional) Font text styling", "self.datain['stats'] class BroadcastCustomMessage(Baserequests): \"\"\"Broadcast custom message to all connected WebSocket", "self.dataout['scene-name'] = scene_name class SetSceneItemRender(Baserequests): \"\"\"Show or hide a specified", "media using a supplied offset. Supports ffmpeg and vlc media", "that the item is manipulated from. The sum of 1=Left", "String (optional) Absolute path to the recording file (only present", "class PreviousMedia(Baserequests): \"\"\"Go to the previous media item in the", "is an experimental feature of obs-websocket. Some plugins which add", "return self.datain['visible'] def getMuted(self): return self.datain['muted'] def getLocked(self): return self.datain['locked']", "the transition. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentTransition' self.datain['name']", "self.name = 'StartStopReplayBuffer' class StartReplayBuffer(Baserequests): \"\"\"Start recording into the Replay", "of the Data URI encoded picture. Can be \"png\", \"jpg\",", "String Filter type *name* type: String Filter name *settings* type:", "TakeSourceScreenshot(Baserequests): \"\"\" At least `embedPictureFormat` or `saveToFilePath` must be specified.", "and add it as a sceneitem to a scene. :Arguments:", "decibels instead of amplitude/mul. \"\"\" def __init__(self, source, volume, useDecibel=None):", "return self.datain['transitionSettings'] class SetTransitionSettings(Baserequests): \"\"\"Change the current settings of a", "scene to use a specific transition override. :Arguments: *sceneName* type:", "(if this item belongs to a group) *groupChildren* type: Array<SceneItemTransform>", "if `use_auth` is `true`. *settings.password* type: String The password to", "self.datain['sceneItems'] = None self.dataout['sceneName'] = sceneName def getSceneName(self): return self.datain['sceneName']", "to preview. \"\"\" def __init__(self, scene_name): Baserequests.__init__(self) self.name = 'SetPreviewScene'", "schema. :Returns: *sourceName* type: String Source name *sourceType* type: String", "= None def getName(self): return self.datain['name'] def getDuration(self): return self.datain['duration']", "current scene. *item* type: Object Scene Item to duplicate from", "`true` :Returns: *itemId* type: int Numerical ID of the created", "in an animation, or in response to a user moving", "self.dataout['items'] = items self.dataout['scene'] = scene class SetSceneTransitionOverride(Baserequests): \"\"\"Set a", "source self.dataout['align'] = align self.dataout['bk_color'] = bk_color self.dataout['bk_opacity'] = bk_opacity", "*settings.password* type: String The password to use when accessing the", "the current transition (in milliseconds). \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "`26.0` if using dB. *muted* type: boolean Indicates whether the", "return self.datain['baseWidth'] def getBaseHeight(self): return self.datain['baseHeight'] def getOutputWidth(self): return self.datain['outputWidth']", "(optional) Name of the scene the scene item belongs to.", "settings. Any options not passed will remain unchanged. Returns the", "int The time in milliseconds since the start of the", "return self.datain['name'] def getMuted(self): return self.datain['muted'] class SetMute(Baserequests): \"\"\"Sets the", "type: int (optional) Scene Item ID (if the `item` field", "this is how you add a source into a scene.", "transitionDuration): Baserequests.__init__(self) self.name = 'SetSceneTransitionOverride' self.dataout['sceneName'] = sceneName self.dataout['transitionName'] =", "= None self.dataout['sourceName'] = sourceName self.dataout['sourceSettings'] = sourceSettings self.dataout['sourceType'] =", "is not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopRecording'", "attributes of the current streaming server settings. Any options not", "self.datain['custom_width'] def getDrop_shadow(self): return self.datain['drop_shadow'] def getFont(self): return self.datain['font'] def", "allows movement. *bounds.type* type: String (optional) The new bounds type", "source into a scene. :Arguments: *sceneName* type: String Name of", "1=Left or 2=Right, and 4=Top or 8=Bottom, or omit to", "a relative path. *fileFormat* type: String (optional) Format to save", "setVisible def getItemId(self): return self.datain['itemId'] class DuplicateSceneItem(Baserequests): \"\"\"Duplicates a scene", "width=None, height=None, fps=None, shutdown=None, render=None): Baserequests.__init__(self) self.name = 'SetBrowserSourceProperties' self.dataout['source']", "box. *sourceWidth* type: int Base width (without scaling) of the", "getTransitionSettings(self): return self.datain['transitionSettings'] class ReleaseTBar(Baserequests): \"\"\"Release the T-Bar (like a", "String (optional) The publish URL. *stream.settings.key* type: String (optional) The", ":Arguments: *rec_folder* type: String Path of the recording folder. \"\"\"", "(Optional) Duration in milliseconds of the transition if transition is", "type: int Scene Item ID. :Returns: *scene* type: String Name", "source. *scale.y* type: double The y-scale factor of the source.", "render, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemRender' self.dataout['source'] = source self.dataout['render']", "'GetStudioModeStatus' self.datain['studio-mode'] = None def getStudioMode(self): return self.datain['studio-mode'] class GetPreviewScene(Baserequests):", "__init__(self, source, align=None, bk_color=None, bk_opacity=None, chatlog=None, chatlog_lines=None, color=None, extents=None, extents_cx=None,", "type: int Milliseconds to set the timestamp to. \"\"\" def", "Will return an `error` if Studio Mode is not enabled.", "String | Object Scene Item name (if this field is", "server. :Arguments: *auth* type: String Response to the auth challenge", "'StartRecording' class StopRecording(Baserequests): \"\"\"Stop recording. Will return an `error` if", "type: double (optional) The new x position of the source.", "int The point on the source that the item is", "*mic_3* type: String (optional) NAme of the third Mic/Aux input", "Either `input`, `group`, or `scene` \"\"\" def __init__(self, sceneName=None): Baserequests.__init__(self)", "type: String (optional) file path. *url* type: String (optional) Url.", "scale of the item. *crop.top* type: int (optional) The new", "Array<SceneItem> Ordered list of the current scene's source items. \"\"\"", "*filters.*.type* type: String Filter type *filters.*.name* type: String Filter name", "'GetReplayBufferStatus' self.datain['isReplayBufferActive'] = None def getIsReplayBufferActive(self): return self.datain['isReplayBufferActive'] class StartStopReplayBuffer(Baserequests):", "Outline color. *outline_size* type: int (optional) Outline size. *outline_opacity* type:", "sourceName, filterName, filterType, filterSettings): Baserequests.__init__(self) self.name = 'AddFilterToSource' self.dataout['sourceName'] =", "Baserequests.__init__(self) self.name = 'GetCurrentTransition' self.datain['name'] = None self.datain['duration'] = None", "\"\"\" At least `embedPictureFormat` or `saveToFilePath` must be specified. Clients", "sourceName def getAudioActive(self): return self.datain['audioActive'] class SetSourceName(Baserequests): \"\"\" Note: If", "Video color format *colorSpace* type: String Color space for YUV", "object or an error will occur when starting the stream.", "Will return an `error` if streaming is not active. \"\"\"", "type: int Extents cx. *extents_cy* type: int Extents cy. *file*", "return self.datain['colorRange'] class OpenProjector(Baserequests): \"\"\"Open a projector window or create", "settings (varies between source types, may require some probing around).", "File path name. *read_from_file* type: boolean (optional) Read text from", "API version. Fixed to 1.1 for retrocompatibility. *obs_websocket_version* type: String", "of the source from the left. *position.y* type: double The", "the source is muted. *locked* type: bool If the source's", "name. *newName* type: String New source name. \"\"\" def __init__(self,", "type: int Outline color. *outline_size* type: int Outline size. *outline_opacity*", "CEA-608 caption data. :Arguments: *text* type: String Captions text \"\"\"", "filename formatting string :Returns: *filename_formatting* type: String Current filename formatting", "is one of the following: \"input\", \"filter\", \"transition\", \"scene\" or", "Baserequests.__init__(self) self.name = 'SetMute' self.dataout['source'] = source self.dataout['mute'] = mute", "or hide a specified source item in a specified scene.", "of the transition to use. *transitionDuration* type: int (Optional) Duration", "gradient self.dataout['gradient_color'] = gradient_color self.dataout['gradient_dir'] = gradient_dir self.dataout['gradient_opacity'] = gradient_opacity", "media sources (as of OBS v25.0.8) :Arguments: *sourceName* type: String", "def __init__(self, outputName, force=None): Baserequests.__init__(self) self.name = 'StopOutput' self.dataout['outputName'] =", "self.datain['height'] def getFps(self): return self.datain['fps'] def getShutdown(self): return self.datain['shutdown'] class", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentScene' self.datain['name'] = None", "String (optional) The publish URL. *settings.key* type: String (optional) The", ":Arguments: *scene_name* type: String The name of the scene to", "of the new filter *filterType* type: String Filter type *filterSettings*", "Width scale factor. *y_scale* type: double Height scale factor. *rotation*", "active profile. :Returns: *current_scene* type: String Name of the currently", "filter state \"\"\" def __init__(self, sourceName, filterName, filterEnabled): Baserequests.__init__(self) self.name", "if Studio Mode is not enabled. :Returns: *name* type: String", "to the next media item in the playlist. Supports only", "= sourceName self.dataout['filterName'] = filterName self.dataout['filterEnabled'] = filterEnabled class GetAudioMonitorType(Baserequests):", "type: String File path. *word_wrap* type: boolean Word wrap. \"\"\"", "(0-100). *text* type: String Text content to be displayed. *valign*", "the source item belongs to. Defaults to the current scene.", "self.datain['outline'] def getOutline_color(self): return self.datain['outline_color'] def getOutline_size(self): return self.datain['outline_size'] def", "type: String Source name *color1* type: int Gradient top color.", "the active preview scene. *sources* type: Array<SceneItem> \"\"\" def __init__(self):", "= keyModifiers class PlayPauseMedia(Baserequests): \"\"\"Pause or play a media source.", "Baserequests.__init__(self) self.name = 'StopReplayBuffer' class SaveReplayBuffer(Baserequests): \"\"\"Flush and save the", "this value is not given. \"\"\" def __init__(self, sceneName, transitionName,", "= 'RemoveSceneTransitionOverride' self.dataout['sceneName'] = sceneName class GetSceneTransitionOverride(Baserequests): \"\"\"Get the current", "String Unique source name *sources.*.typeId* type: String Non-unique source internal", "left of the source before scaling. *crop.right* type: int (optional)", "of the scene item's source *sceneItems.*.sourceType* type: String Type of", "def getBaseHeight(self): return self.datain['baseHeight'] def getOutputWidth(self): return self.datain['outputWidth'] def getOutputHeight(self):", "None self.dataout['sourceName'] = sourceName def getFilters(self): return self.datain['filters'] class GetSourceFilterInfo(Baserequests):", "__init__(self, item, scene_name=None, position=None, rotation=None, scale=None, crop=None, visible=None, locked=None, bounds=None):", "type: String Source name. :Returns: *monitorType* type: String The monitor", "__init__(self): Baserequests.__init__(self) self.name = 'GetCurrentSceneCollection' self.datain['sc-name'] = None def getScName(self):", "FILE WAS GENERATED BY generate_classes.py - DO NOT EDIT #", "state of the provided source. States: `none`, `playing`, `opening`, `buffering`,", "locked status of the source. 'true' keeps it in its", "(0-100). *outline* type: boolean Outline. *outline_color* type: int Outline color.", "of the source. *is_local_file* type: boolean (optional) Indicates that a", "Varies with image type. *width* type: int (optional) Screenshot width.", "type: Array<Object> Array of sources *sources.*.name* type: String Unique source", "first Desktop Audio capture source. *desktop_2* type: String (optional) Name", "a scene item. :Arguments: *fromScene* type: String (optional) Name of", "return self.datain['isRecording'] def getIsRecordingPaused(self): return self.datain['isRecordingPaused'] def getRecordTimecode(self): return self.datain['recordTimecode']", "`salt` (see \"Authentication\" for more information). :Returns: *authRequired* type: boolean", "self.datain['sourceHeight'] = None self.datain['width'] = None self.datain['height'] = None self.datain['parentGroupName']", "of the scene to reorder (defaults to current). *items* type:", "to the active transition. *with_transition.name* type: String Name of the", "= None self.datain['extents_cy'] = None self.datain['file'] = None self.datain['read_from_file'] =", "filter to reconfigure *filterSettings* type: Object New settings. These will", "self.dataout['sourceName'] = sourceName self.dataout['sourceType'] = sourceType def getSourceName(self): return self.datain['sourceName']", "'StartOutput' self.dataout['outputName'] = outputName class StopOutput(Baserequests): \"\"\" Note: Controlling outputs", "Will return an `error` if streaming is already active. :Arguments:", "new item was created *item* type: Object New item info", "*timeOffset* type: int Millisecond offset (positive or negative) to offset", "getRecordTimecode(self): return self.datain['recordTimecode'] def getRecordingFilename(self): return self.datain['recordingFilename'] class StartStopRecording(Baserequests): \"\"\"Toggle", "self.dataout['sceneName'] = sceneName def getSceneName(self): return self.datain['sceneName'] def getSceneItems(self): return", "getScale(self): return self.datain['scale'] def getCrop(self): return self.datain['crop'] def getVisible(self): return", "the source. Between `0.0` and `20.0` if using mul, under", "transition settings \"\"\" def __init__(self, transitionName, transitionSettings): Baserequests.__init__(self) self.name =", "getEnabled(self): return self.datain['enabled'] def getType(self): return self.datain['type'] def getName(self): return", "(optional) If authentication is enabled, the password for the streaming", "to use. Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self, sourceName,", "of sources. Will return an `error` if Studio Mode is", "a specified source. :Arguments: *source* type: String Source name. :Returns:", "\"\"\" def __init__(self, sourceName, filterName, filterSettings): Baserequests.__init__(self) self.name = 'SetSourceFilterSettings'", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSourcesList' self.datain['sources'] = None", "Baserequests.__init__(self) self.name = 'CreateScene' self.dataout['sceneName'] = sceneName class ReorderSceneItems(Baserequests): \"\"\"Changes", "filter in the chain \"\"\" def __init__(self, sourceName, filterName, newIndex):", "or Boolean field. *stream.settings* type: Object (optional) Settings for the", "rotation of the item in degrees around the point of", "Audio capture source. *desktop_2* type: String (optional) Name of the", "return self.datain['stats'] class BroadcastCustomMessage(Baserequests): \"\"\"Broadcast custom message to all connected", "= None self.datain['height'] = None self.datain['parentGroupName'] = None self.datain['groupChildren'] =", "Mode. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'DisableStudioMode' class ToggleStudioMode(Baserequests):", "THIS FILE WAS GENERATED BY generate_classes.py - DO NOT EDIT", "to the server. :Arguments: *auth* type: String Response to the", "self.datain['from_file'] def getLog_mode(self): return self.datain['log_mode'] def getOutline(self): return self.datain['outline'] def", "self.datain['gradient'] def getGradient_color(self): return self.datain['gradient_color'] def getGradient_dir(self): return self.datain['gradient_dir'] def", "If the new name already exists as a source, obs-websocket", "supported. :Returns: *transition_duration* type: int Duration of the current transition", "self.datain['sources'] class GetSceneList(Baserequests): \"\"\"Get a list of scenes in the", "type: String (optional) Scene Item name (if the `item` field", "only reach a maximum of 1.0mul/0.0dB, however OBS actually supports", "\"\"\" def __init__(self, auth): Baserequests.__init__(self) self.name = 'Authenticate' self.dataout['auth'] =", "self.datain['supported-image-export-formats'] class GetAuthRequired(Baserequests): \"\"\"Tells the client if authentication is required.", "status of a specified source. :Arguments: *source* type: String Source", "Baserequests.__init__(self) self.name = 'DuplicateSceneItem' self.datain['scene'] = None self.datain['item'] = None", "settings are required. Returns the full settings of the stream", "\"\"\"Stop recording. Will return an `error` if recording is not", "is not active or not paused. \"\"\" def __init__(self): Baserequests.__init__(self)", "automatic, 1 is smallest file/most compression, 100 is largest file/least", "= None self.datain['gradient_color'] = None self.datain['gradient_dir'] = None self.datain['gradient_opacity'] =", "a filter :Arguments: *sourceName* type: String Name of the source", "\"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'PreviousMedia' self.dataout['sourceName'] =", "GetTextFreetype2Properties(Baserequests): \"\"\"Get the current properties of a Text Freetype 2", "boolean Whether to pause or play the source. `false` for", "= filterName def getEnabled(self): return self.datain['enabled'] def getType(self): return self.datain['type']", "the media. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaTime'", "If the source is visible. *muted* type: bool If the", "stream state). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopStreaming' class", "type: String (optional) Name of the scene to copy the", "int Base (canvas) width *baseHeight* type: int Base (canvas) height", "int Unique item id of the source item *sceneItems.*.sourceKind* type:", "return self.datain['audioActive'] class SetSourceName(Baserequests): \"\"\" Note: If the new name", "(optional) Set the created SceneItem as visible or not. Defaults", "\"\"\"Resume/unpause the current recording (if paused). Returns an error if", "a list of all scene items in a scene. :Arguments:", "geometry self.dataout['name'] = name class TriggerHotkeyByName(Baserequests): \"\"\"Executes hotkey routine, identified", "return self.datain['videoFormat'] def getColorSpace(self): return self.datain['colorSpace'] def getColorRange(self): return self.datain['colorRange']", "class SetFilenameFormatting(Baserequests): \"\"\"Set the filename formatting string :Arguments: *filename_formatting* type:", "of scene items in the requested scene. :Arguments: *scene* type:", "outputName): Baserequests.__init__(self) self.name = 'StartOutput' self.dataout['outputName'] = outputName class StopOutput(Baserequests):", "class GetTransitionPosition(Baserequests): \"\"\"Get the position of the current transition. :Returns:", "recording started (only present if currently recording). *recordingFilename* type: String", "type: String (optional) The publish URL. *stream.settings.key* type: String (optional)", "file path (file extension included) where the captured image is", "self.datain['available-requests'] def getSupportedImageExportFormats(self): return self.datain['supported-image-export-formats'] class GetAuthRequired(Baserequests): \"\"\"Tells the client", "The desired audio sync offset (in nanoseconds). \"\"\" def __init__(self,", "String Current filename formatting string. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "GetAuthRequired(Baserequests): \"\"\"Tells the client if authentication is required. If so,", "receive scaled pictures. Aspect ratio is preserved if only one", "currently previewed scene to the main output. Will return an", "name. :Returns: *name* type: String Source name. *muted* type: boolean", "before scaling. *crop.bottom* type: int (optional) The new amount of", "sourceName self.dataout['filterName'] = filterName def getEnabled(self): return self.datain['enabled'] def getType(self):", "moving a T-Bar control in your User Interface), set `release`", "__init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaDuration' self.datain['mediaDuration'] = None self.dataout['sourceName']", "= transitionSettings def getTransitionSettings(self): return self.datain['transitionSettings'] class ReleaseTBar(Baserequests): \"\"\"Release the", "of the currently selected transition if supported. :Returns: *transition_duration* type:", "than the current streaming service type, all settings are required.", "self.datain['outputWidth'] def getOutputHeight(self): return self.datain['outputHeight'] def getScaleType(self): return self.datain['scaleType'] def", "save class GetStreamSettings(Baserequests): \"\"\"Get the current streaming server settings. :Returns:", "return self.datain['transitions'] class GetCurrentTransition(Baserequests): \"\"\"Get the name of the currently", "self.dataout['local_file'] = local_file self.dataout['url'] = url self.dataout['css'] = css self.dataout['width']", "type: String Filter type *filterSettings* type: Object Filter settings \"\"\"", "= None def getOutputs(self): return self.datain['outputs'] class GetOutputInfo(Baserequests): \"\"\"Get information", "valign=None, vertical=None, render=None): Baserequests.__init__(self) self.name = 'SetTextGDIPlusProperties' self.dataout['source'] = source", "\"\"\"Get settings of the specified source :Arguments: *sourceName* type: String", "= None self.datain['vertical'] = None self.dataout['source'] = source def getSource(self):", "*color2* type: int (optional) Gradient bottom color. *custom_width* type: int", "Captions text \"\"\" def __init__(self, text): Baserequests.__init__(self) self.name = 'SendCaptions'", "*sceneName* type: String Scene to add the new source to.", "*sourceWidth* type: int Base width (without scaling) of the source", "type: int (optional) Outline opacity (0-100). *text* type: String (optional)", "self.datain['stream-timecode'] = None self.datain['rec-timecode'] = None self.datain['preview-only'] = None def", "replay buffer. :Returns: *isReplayBufferActive* type: boolean Current recording status. \"\"\"", "path to the saved image file (if `saveToFilePath` was specified", "of the scene to create. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self)", "is acceptable). *item.id* type: int Scene Item ID. \"\"\" def", "width *baseHeight* type: int Base (canvas) height *outputWidth* type: int", "\"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetAudioMonitorType' self.datain['monitorType'] =", "`monitorAndOutput`. \"\"\" def __init__(self, sourceName, monitorType): Baserequests.__init__(self) self.name = 'SetAudioMonitorType'", "Source name. :Returns: *source* type: String Source name *color1* type:", "be a relative path. *fileFormat* type: String (optional) Format to", "self.datain['profiles'] = None def getProfiles(self): return self.datain['profiles'] class GetRecordingStatus(Baserequests): \"\"\"Get", "*sceneName* type: String Name of the scene to switch to.", "the streaming server. *settings.username* type: String (optional) The username for", "duration class GetTransitionDuration(Baserequests): \"\"\"Get the duration of the currently selected", "None self.datain['height'] = None self.datain['fps'] = None self.datain['shutdown'] = None", "current properties of a Text Freetype 2 source. :Arguments: *source*", "\"Authentication\" for more information). \"\"\" def __init__(self, auth): Baserequests.__init__(self) self.name", "'SendCaptions' self.dataout['text'] = text class GetStudioModeStatus(Baserequests): \"\"\"Indicates if Studio Mode", "class CreateSource(Baserequests): \"\"\"Create a source and add it as a", "Color space for YUV *colorRange* type: String Color range (full", "(like a user releasing their mouse button after moving the", "heartbeat messages \"\"\" def __init__(self, enable): Baserequests.__init__(self) self.name = 'SetHeartbeat'", "media is playing, the total duration can be off by", "`SetTBarPosition` with the `release` parameter set to `false`.* \"\"\" def", "factor. *y_scale* type: double Height scale factor. *rotation* type: double", "type: boolean Current recording status. *isRecordingPaused* type: boolean Whether the", "= sourceName self.dataout['filterName'] = filterName self.dataout['filterSettings'] = filterSettings class SetSourceFilterVisibility(Baserequests):", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetMediaSourcesList' self.datain['mediaSources'] = None", "not visible. *render* type: boolean (optional) Visibility of the scene", ":Arguments: *sourceName* type: String Source name *filterName* type: String Source", "provide frames asynchronously *types.*.caps.hasVideo* type: Boolean True if sources of", "type: String Source name. *is_local_file* type: boolean Indicates that a", "*source* type: String Source name. *color1* type: int (optional) Gradient", "String (optional) File path name. *read_from_file* type: boolean (optional) Read", "self.datain['settings'] class AddFilterToSource(Baserequests): \"\"\"Add a new filter to a source.", "Please note: if `SetRecordingFolder` is called while a recording is", "\"style\": \"\" }` *font.face* type: String Font face. *font.flags* type:", "instead of amplitude/mul. :Returns: *name* type: String Source name. *volume*", "on the next recording. :Arguments: *rec_folder* type: String Path of", "Baserequests.__init__(self) self.name = 'RemoveFilterFromSource' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName", "*with_transition* type: Object (optional) Change the active transition before switching", "def getScale(self): return self.datain['scale'] def getCrop(self): return self.datain['crop'] def getVisible(self):", "in this way. :Arguments: *outputName* type: String Output name \"\"\"", "self.datain['videoFormat'] def getColorSpace(self): return self.datain['colorSpace'] def getColorRange(self): return self.datain['colorRange'] class", "*keyModifiers.alt* type: boolean Trigger Alt Key *keyModifiers.control* type: boolean Trigger", "def __init__(self, type, monitor, geometry, name): Baserequests.__init__(self) self.name = 'OpenProjector'", "'ResetSceneItem' self.dataout['item'] = item self.dataout['scene-name'] = scene_name class SetSceneItemRender(Baserequests): \"\"\"Show", "boolean Extents wrap. *extents_cx* type: int Extents cx. *extents_cy* type:", "int (optional) Width. *height* type: int (optional) Height. *fps* type:", "type: String Filter name *settings* type: Object Filter settings \"\"\"", "sourceName self.dataout['filterName'] = filterName self.dataout['filterSettings'] = filterSettings class SetSourceFilterVisibility(Baserequests): \"\"\"Change", "None self.datain['stream-timecode'] = None self.datain['rec-timecode'] = None self.datain['preview-only'] = None", "the specified source. Useful for type-checking to avoid settings a", "hotkey unique name :Arguments: *hotkeyName* type: String Unique name of", "space for YUV *colorRange* type: String Color range (full or", "= saveToFilePath self.dataout['fileFormat'] = fileFormat self.dataout['compressionQuality'] = compressionQuality self.dataout['width'] =", "is not given. \"\"\" def __init__(self, sceneName, transitionName, transitionDuration): Baserequests.__init__(self)", "self.datain['name'] = None self.datain['itemId'] = None self.datain['position'] = None self.datain['rotation']", "\"\"\"Set the active transition. :Arguments: *transition_name* type: String The name", "return self.datain['css'] def getWidth(self): return self.datain['width'] def getHeight(self): return self.datain['height']", "settings must be specified in the `settings` object or an", "self.dataout['scale'] = scale self.dataout['crop'] = crop self.dataout['visible'] = visible self.dataout['locked']", "call `ReleaseTBar` later once the animation/interaction is over. :Arguments: *position*", "(if it is an object). *item.name* type: String (optional) Scene", "type: Object Scene item to delete (required) *item.name* type: String", "`none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self, sourceName, monitorType): Baserequests.__init__(self) self.name", "self.datain['preview-only'] = None def getStreaming(self): return self.datain['streaming'] def getRecording(self): return", "Underline=5, Strikeout=8` *font.size* type: int (optional) Font text size. *font.style*", "string :Arguments: *filename_formatting* type: String Filename formatting string to set.", "scene basis. *items.*.name* type: String (optional) Name of a scene", "type: String Name of the source to which the filter", "def getSourceHeight(self): return self.datain['sourceHeight'] def getWidth(self): return self.datain['width'] def getHeight(self):", "stream. *settings.use_auth* type: boolean Indicates whether authentication should be used", "boolean Trigger Command Key (Mac) \"\"\" def __init__(self, keyId, keyModifiers):", "def getVisible(self): return self.datain['visible'] def getMuted(self): return self.datain['muted'] def getLocked(self):", "cause a feedback loop if it's audio is monitored and", "the Replay Buffer is not active. \"\"\" def __init__(self): Baserequests.__init__(self)", "String Source name. *playPause* type: boolean Whether to pause or", "present if currently recording). *preview_only* type: boolean Always false. Retrocompatibility", "a source :Arguments: *sourceName* type: String Source name *filterName* type:", "self.dataout['filterSettings'] = filterSettings class SetSourceFilterVisibility(Baserequests): \"\"\"Change the visibility/enabled state of", "(optional) The new alignment of the bounding box. (0-2, 4-6,", "the source. *scale.y* type: double The y-scale factor of the", "= None self.datain['desktop-2'] = None self.datain['mic-1'] = None self.datain['mic-2'] =", "def __init__(self, sourceName, filterName, filterType, filterSettings): Baserequests.__init__(self) self.name = 'AddFilterToSource'", "return self.datain['itemId'] def getPosition(self): return self.datain['position'] def getRotation(self): return self.datain['rotation']", "None self.datain['muted'] = None self.datain['locked'] = None self.datain['bounds'] = None", "__init__(self, sourceName): Baserequests.__init__(self) self.name = 'PreviousMedia' self.dataout['sourceName'] = sourceName class", "= 'StartStopRecording' class StartRecording(Baserequests): \"\"\"Start recording. Will return an `error`", "to. :Returns: *transitionName* type: String Name of the current overriding", "field is an object) *item.id* type: int (optional) Scene Item", "int (optional) Gradient bottom color. *custom_width* type: int (optional) Custom", "formatted as a comma-separated list string (e.g. : \"Method1,Method2,Method3\"). *supported_image_export_formats*", "boolean Whether to make the sceneitem visible on creation or", "to the 'key' of the RTMP stream. Used to pass", "'BroadcastCustomMessage' self.dataout['realm'] = realm self.dataout['data'] = data class GetVideoInfo(Baserequests): \"\"\"Get", "source) :Returns: *mediaSources* type: Array<Object> Array of sources *mediaSources.*.sourceName* type:", "recording. Will return an `error` if recording is not active.", "source of this type provide frames asynchronously *types.*.caps.hasVideo* type: Boolean", "factor of the source. *scale.y* type: double The y-scale factor", "Extents wrap. *extents_cx* type: int (optional) Extents cx. *extents_cy* type:", "'GetTextFreetype2Properties' self.datain['source'] = None self.datain['color1'] = None self.datain['color2'] = None", "*extents* type: boolean Extents wrap. *extents_cx* type: int Extents cx.", "active. :Arguments: *stream* type: Object (optional) Special stream configuration. Please", "not the T-Bar gets released automatically after setting its new", "if `use_auth` is not set to `true`. *stream.settings.password* type: String", "getWidth(self): return self.datain['width'] def getHeight(self): return self.datain['height'] def getFps(self): return", "transition (in milliseconds). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionDuration'", "response. If 'type' is different than the current streaming service", "return self.datain['extents'] def getExtents_cx(self): return self.datain['extents_cx'] def getExtents_cy(self): return self.datain['extents_cy']", "total length of media in milliseconds.. \"\"\" def __init__(self, sourceName):", "(default), `Source`, `Scene`, `StudioProgram`, or `Multiview` (case insensitive). *monitor* type:", "whether authentication should be used when connecting to the streaming", "int (optional) Font text styling flag. `Bold=1, Italic=2, Bold Italic=3,", "getSourceSettings(self): return self.datain['sourceSettings'] class SetSourceSettings(Baserequests): \"\"\"Set settings of the specified", "name already exists as a source, obs-websocket will return an", "manipulated from. The sum of 1=Left or 2=Right, and 4=Top", "return self.datain['available-requests'] def getSupportedImageExportFormats(self): return self.datain['supported-image-export-formats'] class GetAuthRequired(Baserequests): \"\"\"Tells the", "started (only present if currently recording). *preview_only* type: boolean Always", "will be effective on the next recording. :Arguments: *rec_folder* type:", "active profile. :Arguments: *profile_name* type: String Name of the desired", "type: String Font Style (unknown function). *from_file* type: boolean Read", "self.name = 'SetPreviewScene' self.dataout['scene-name'] = scene_name class TransitionToProgram(Baserequests): \"\"\"Transitions the", "Boolean New filter state \"\"\" def __init__(self, sourceName, filterName, filterEnabled):", "*force* type: boolean (optional) Force stop (default: false) \"\"\" def", "= x self.dataout['y'] = y self.dataout['scene-name'] = scene_name class SetSceneItemTransform(Baserequests):", "None def getCurrentTransition(self): return self.datain['current-transition'] def getTransitions(self): return self.datain['transitions'] class", "self.datain['name'] = None self.datain['offset'] = None self.dataout['source'] = source def", "Baserequests.__init__(self) self.name = 'ListSceneCollections' self.datain['scene-collections'] = None def getSceneCollections(self): return", "= 'GetMediaSourcesList' self.datain['mediaSources'] = None def getMediaSources(self): return self.datain['mediaSources'] class", "String The name of the scene to preview. \"\"\" def", "python # -*- coding: utf-8 -*- # THIS FILE WAS", "double OBSRemote compatible API version. Fixed to 1.1 for retrocompatibility.", "the specified source *filters.*.enabled* type: Boolean Filter status (enabled or", "Background opacity (0-100). *chatlog* type: boolean (optional) Chat log. *chatlog_lines*", "getSourceName(self): return self.datain['sourceName'] def getSourceType(self): return self.datain['sourceType'] def getSourceSettings(self): return", "Set the created SceneItem as visible or not. Defaults to", "= filterSettings class RemoveFilterFromSource(Baserequests): \"\"\"Remove a filter from a source", "__init__(self, rec_folder): Baserequests.__init__(self) self.name = 'SetRecordingFolder' self.dataout['rec-folder'] = rec_folder class", "Buffer to disk. This is basically the same as triggering", "source item *sceneItems.*.sourceKind* type: String ID if the scene item's", "(optional) Custom width (0 to disable). *drop_shadow* type: boolean (optional)", "String Source name. *volume* type: double Desired volume. Must be", "between 0.0 and 1.0. Note: Transition returns 1.0 when not", "Mode. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'EnableStudioMode' class DisableStudioMode(Baserequests):", "Base (canvas) width *baseHeight* type: int Base (canvas) height *outputWidth*", "= None self.datain['text'] = None self.datain['text_file'] = None self.datain['word_wrap'] =", "recording folder. \"\"\" def __init__(self, rec_folder): Baserequests.__init__(self) self.name = 'SetRecordingFolder'", "__init__(self, outputName): Baserequests.__init__(self) self.name = 'GetOutputInfo' self.datain['outputInfo'] = None self.dataout['outputName']", "cropped off the top of the source before scaling. *crop.right*", "}` *font.face* type: String Font face. *font.flags* type: int Font", "by hotkey unique name :Arguments: *hotkeyName* type: String Unique name", "gradient_dir=None, gradient_opacity=None, outline=None, outline_color=None, outline_size=None, outline_opacity=None, text=None, valign=None, vertical=None, render=None):", "def __init__(self, sourceName, filterName, newIndex): Baserequests.__init__(self) self.name = 'ReorderSourceFilter' self.dataout['sourceName']", "number of pixels cropped off the top of the source", "Always false. Retrocompatibility with OBSRemote. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "their mouse button after moving the T-Bar). Call `ReleaseTBar` manually", "List of available request types, formatted as a comma-separated list", "used if output size differs from base size *fps* type:", "Note: For some reason, for the first 5 or so", "*custom_width* type: int (optional) Custom width (0 to disable). *drop_shadow*", "type: String Color range (full or partial) \"\"\" def __init__(self):", "def __init__(self, text): Baserequests.__init__(self) self.name = 'SendCaptions' self.dataout['text'] = text", "or `scene` \"\"\" def __init__(self, sceneName=None): Baserequests.__init__(self) self.name = 'GetSceneItemList'", "= 'GetAuthRequired' self.datain['authRequired'] = None self.datain['challenge'] = None self.datain['salt'] =", "\"\"\" def __init__(self, sourceName, newName): Baserequests.__init__(self) self.name = 'SetSourceName' self.dataout['sourceName']", "Source name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'PreviousMedia'", "the scene to copy the item from. Defaults to the", "self.dataout['geometry'] = geometry self.dataout['name'] = name class TriggerHotkeyByName(Baserequests): \"\"\"Executes hotkey", "'RemoveFilterFromSource' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName class ReorderSourceFilter(Baserequests): \"\"\"Move", "list of the current scene's source items. \"\"\" def __init__(self):", "of this request has also not been tested. :Arguments: *sourceName*", "Width of the bounding box. *bounds.y* type: double Height of", "supported by the transition. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "name of the hotkey, as defined when registering the hotkey", "`paused`, `stopped`, `ended`, `error`, `unknown` \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "\"other\" *types.*.defaultSettings* type: Object Default settings of this source type", "types, may require some probing around). :Returns: *sourceName* type: String", "int (optional) Custom width (0 to disable). *drop_shadow* type: boolean", "User Interface), set `release` to false and call `ReleaseTBar` later", "(optional) The new amount of pixels cropped off the right", "`release` parameter set to `false`.* \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "item. *bottom* type: int Pixel position of the bottom of", "return self.datain['custom_width'] def getDrop_shadow(self): return self.datain['drop_shadow'] def getFont(self): return self.datain['font']", "(optional) Name of the second Mic/Aux input source. *mic_3* type:", "None self.dataout['transitionName'] = transitionName self.dataout['transitionSettings'] = transitionSettings def getTransitionSettings(self): return", "StopRecording(Baserequests): \"\"\"Stop recording. Will return an `error` if recording is", "= 'GetOutputInfo' self.datain['outputInfo'] = None self.dataout['outputName'] = outputName def getOutputInfo(self):", "hides source. *locked* type: bool (optional) The new locked status", "a supplied offset. Supports ffmpeg and vlc media sources (as", "Value is one of the following: \"input\", \"filter\", \"transition\" or", "settings of this source type *types.*.caps* type: Object Source type", "type: String Name of the scene where the new item", "Height of the bounding box. *sourceWidth* type: int Base width", "duplicated *types.*.caps.doNotSelfMonitor* type: Boolean True if sources of this type", "sourceName, sourceType=None): Baserequests.__init__(self) self.name = 'GetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType']", "(optional) file path. *url* type: String (optional) Url. *css* type:", "actual settings of the stream. *settings.server* type: String (optional) The", "y-scale factor of the source. *crop.top* type: int The number", "getSceneItems(self): return self.datain['sceneItems'] class GetSceneItemProperties(Baserequests): \"\"\"Gets the scene specific properties", "int Outline size. *outline_opacity* type: int Outline opacity (0-100). *text*", "is required. *challenge* type: String (optional) *salt* type: String (optional)", "True if sources of this type provide video *types.*.caps.hasAudio* type:", "text class GetStudioModeStatus(Baserequests): \"\"\"Indicates if Studio Mode is currently enabled.", "name (prefer `id`, including both is acceptable). *item.id* type: int", "in a scene. :Arguments: *sceneName* type: String (optional) Name of", "to receive scaled pictures. Aspect ratio is preserved if only", "double current transition position. This value will be between 0.0", "log_mode self.dataout['outline'] = outline self.dataout['text'] = text self.dataout['text_file'] = text_file", "def getMic2(self): return self.datain['mic-2'] def getMic3(self): return self.datain['mic-3'] class GetSourceFilters(Baserequests):", "Replay Buffer is already active or if the \"Save Replay", "(the scene or group it belongs to). :Arguments: *scene_name* type:", "__init__(self): Baserequests.__init__(self) self.name = 'StartRecording' class StopRecording(Baserequests): \"\"\"Stop recording. Will", "cropped off the right of the source before scaling. *crop.bottom*", "filterName self.dataout['movementType'] = movementType class SetSourceFilterSettings(Baserequests): \"\"\"Update settings of a", "*shutdown* type: boolean Indicates whether the source should be shutdown", "not match the given stream type, all settings must be", "self.datain['offset'] class GetSourceSettings(Baserequests): \"\"\"Get settings of the specified source :Arguments:", "the settings to disk. \"\"\" def __init__(self, type, settings, save):", "return self.datain['duration'] class SetCurrentTransition(Baserequests): \"\"\"Set the active transition. :Arguments: *transition_name*", "Object The actual settings of the stream. *settings.server* type: String", "self.dataout['source'] = source def getName(self): return self.datain['name'] def getMuted(self): return", "projectors. *name* type: String (Optional) Name of the source or", "currently active profile. :Arguments: *profile_name* type: String Name of the", "__init__(self): Baserequests.__init__(self) self.name = 'GetSceneList' self.datain['current-scene'] = None self.datain['scenes'] =", "(Mac) \"\"\" def __init__(self, keyId, keyModifiers): Baserequests.__init__(self) self.name = 'TriggerHotkeyBySequence'", "'GetTransitionDuration' self.datain['transition-duration'] = None def getTransitionDuration(self): return self.datain['transition-duration'] class GetTransitionPosition(Baserequests):", "chain (relative positioning) :Arguments: *sourceName* type: String Name of the", "the current filter settings. \"\"\" def __init__(self, sourceName, filterName, filterSettings):", "def getText_file(self): return self.datain['text_file'] def getWord_wrap(self): return self.datain['word_wrap'] class SetTextFreetype2Properties(Baserequests):", "type: String Path of the recording folder. \"\"\" def __init__(self):", "Source name. :Returns: *audioActive* type: boolean Audio active status of", "URL. *settings.key* type: String (optional) The publish key. *settings.use_auth* type:", "self.dataout['sc-name'] = sc_name class GetCurrentSceneCollection(Baserequests): \"\"\"Get the name of the", "getSourceName(self): return self.datain['sourceName'] def getImg(self): return self.datain['img'] def getImageFile(self): return", "of the bounding box. *bounds.y* type: double Height of the", "(optional) Drop shadow. *font* type: Object (optional) Holds data for", "SetSceneItemCrop(Baserequests): \"\"\"Sets the crop coordinates of the specified source item.", "type: Array<Object> List of available profiles. *profiles.*.profile_name* type: String Filter", "item, scene=None): Baserequests.__init__(self) self.name = 'DeleteSceneItem' self.dataout['item'] = item self.dataout['scene']", ":Arguments: *sourceName* type: String Source name. :Returns: *audioActive* type: boolean", "self.name = 'SetCurrentProfile' self.dataout['profile-name'] = profile_name class GetCurrentProfile(Baserequests): \"\"\"Get the", "type: Object User-defined data \"\"\" def __init__(self, realm, data): Baserequests.__init__(self)", "self.dataout['visible'] = visible self.dataout['locked'] = locked self.dataout['bounds'] = bounds class", "*version* type: double OBSRemote compatible API version. Fixed to 1.1", "= None self.datain['position'] = None self.datain['rotation'] = None self.datain['scale'] =", "\"\"\"Update settings of a filter :Arguments: *sourceName* type: String Name", "return self.datain['scaleType'] def getFps(self): return self.datain['fps'] def getVideoFormat(self): return self.datain['videoFormat']", "it in its current position, 'false' allows movement. *bounds.type* type:", "int (optional) Framerate. *shutdown* type: boolean (optional) Indicates whether the", "String Filter type *filters.*.name* type: String Filter name *filters.*.settings* type:", "the currently active profile. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "self.datain['align'] def getBk_color(self): return self.datain['bk_color'] def getBk_opacity(self): return self.datain['bk_opacity'] def", "crop self.dataout['visible'] = visible self.dataout['locked'] = locked self.dataout['bounds'] = bounds", "is muted. \"\"\" def __init__(self, source, useDecibel=None): Baserequests.__init__(self) self.name =", "formatting string :Returns: *filename_formatting* type: String Current filename formatting string.", "saves only through obs-websocket. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "self.name = 'ToggleMute' self.dataout['source'] = source class GetAudioActive(Baserequests): \"\"\"Get the", "__init__(self, text): Baserequests.__init__(self) self.name = 'SendCaptions' self.dataout['text'] = text class", "items. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentScene' self.datain['name'] =", "import Baserequests class GetVersion(Baserequests): \"\"\"Returns the latest version of the", "sourceName class PreviousMedia(Baserequests): \"\"\"Go to the previous media item in", "scene to switch to. \"\"\" def __init__(self, scene_name): Baserequests.__init__(self) self.name", "scene_name class SetSceneItemCrop(Baserequests): \"\"\"Sets the crop coordinates of the specified", "to use a specific transition override. :Arguments: *sceneName* type: String", "'GetStreamSettings' self.datain['type'] = None self.datain['settings'] = None def getType(self): return", "filter to a source. Available source types along with their", "(in milliseconds). \"\"\" def __init__(self, duration): Baserequests.__init__(self) self.name = 'SetTransitionDuration'", "SetPreviewScene(Baserequests): \"\"\"Set the active preview scene. Will return an `error`", "main output. Will return an `error` if Studio Mode is", "None def getScName(self): return self.datain['sc-name'] class ListSceneCollections(Baserequests): \"\"\"List available scene", "= 'RestartMedia' self.dataout['sourceName'] = sourceName class StopMedia(Baserequests): \"\"\"Stop a media", "Boolean True if interaction with this sources of this type", "*bk_color* type: int (optional) Background color. *bk_opacity* type: int (optional)", "recording. Will return an `error` if recording is already active.", "self.datain['extents'] = None self.datain['extents_cx'] = None self.datain['extents_cy'] = None self.datain['file']", "the source's base height. :Returns: *sourceName* type: String Source name", "(e.g. : in an animation, or in response to a", "source def getName(self): return self.datain['name'] def getMuted(self): return self.datain['muted'] class", "type: Boolean True if sources of this type provide video", "New item name \"\"\" def __init__(self, item, fromScene=None, toScene=None): Baserequests.__init__(self)", "None self.datain['scenes'] = None def getCurrentScene(self): return self.datain['current-scene'] def getScenes(self):", "__init__(self): Baserequests.__init__(self) self.name = 'GetPreviewScene' self.datain['name'] = None self.datain['sources'] =", "Mode is currently enabled. :Returns: *studio_mode* type: boolean Indicates if", "= outputName self.dataout['force'] = force class SetCurrentProfile(Baserequests): \"\"\"Set the currently", "of the first Mic/Aux input source. *mic_2* type: String (optional)", "*stream.settings* type: Object (optional) Settings for the stream. *stream.settings.server* type:", "(optional) The publish URL. *settings.key* type: String (optional) The publish", "*items.*.id* type: int (optional) Id of a specific scene item.", "= None def getVersion(self): return self.datain['version'] def getObsWebsocketVersion(self): return self.datain['obs-websocket-version']", "same as triggering the \"Save Replay Buffer\" hotkey. Will return", "'StopOutput' self.dataout['outputName'] = outputName self.dataout['force'] = force class SetCurrentProfile(Baserequests): \"\"\"Set", "Scene Item name (if the `item` field is an object)", "Transition duration (in milliseconds). \"\"\" def __init__(self, with_transition=None): Baserequests.__init__(self) self.name", "*left* type: int Pixel position of the left of the", "Item name. *top* type: int Pixel position of the top", "where the captured image is to be saved. Can be", "state of a filter :Arguments: *sourceName* type: String Source name", "= 'ListOutputs' self.datain['outputs'] = None def getOutputs(self): return self.datain['outputs'] class", "return self.datain['sources'] class GetSceneList(Baserequests): \"\"\"Get a list of scenes in", "self.name = 'SetSourceName' self.dataout['sourceName'] = sourceName self.dataout['newName'] = newName class", "\"\"\"Reset a scene item. :Arguments: *scene_name* type: String (optional) Name", "self.datain['imageFile'] = None self.dataout['sourceName'] = sourceName self.dataout['embedPictureFormat'] = embedPictureFormat self.dataout['saveToFilePath']", "Array<String> Scene collections list *scene_collections.*.sc_name* type: String Scene collection name", "self.datain['outputHeight'] = None self.datain['scaleType'] = None self.datain['fps'] = None self.datain['videoFormat']", "read_from_file=None, font=None, gradient=None, gradient_color=None, gradient_dir=None, gradient_opacity=None, outline=None, outline_color=None, outline_size=None, outline_opacity=None,", "-1). Encoded in Base64 using [Qt's geometry encoding](https://doc.qt.io/qt-5/qwidget.html#saveGeometry). Corresponds to", "before scaling. *crop.left* type: int The number of pixels cropped", "a new scene scene. :Arguments: *sceneName* type: String Name of", "read_from_file self.dataout['font'] = font self.dataout['gradient'] = gradient self.dataout['gradient_color'] = gradient_color", "available in the frontend's dropdown menu. :Returns: *current_transition* type: String", "profile_name class GetCurrentProfile(Baserequests): \"\"\"Get the name of the current profile.", "of the source item. *bottom* type: int Pixel position of", "Baserequests.__init__(self) self.name = 'SetSourceFilterSettings' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName", "= None self.datain['muted'] = None self.datain['locked'] = None self.datain['bounds'] =", "settings of the specified source. :Arguments: *sourceName* type: String Source", "String Name of the filter to remove \"\"\" def __init__(self,", "the source. 'true' keeps it in its current position, 'false'", "= sourceKind self.dataout['sceneName'] = sceneName self.dataout['sourceSettings'] = sourceSettings self.dataout['setVisible'] =", "visible or not. Defaults to true :Returns: *itemId* type: int", "(varies between source types, may require some probing around). \"\"\"", "type: String Source type. Value is one of the following:", "self.datain['transitionDuration'] class GetStreamingStatus(Baserequests): \"\"\"Get current streaming and recording status. :Returns:", "options not passed will remain unchanged. Returns the updated settings", "\"\"\" def __init__(self, type, settings, save): Baserequests.__init__(self) self.name = 'SetStreamSettings'", "from the specified file. *font* type: Object (optional) Holds data", "string parameters to the 'key' of the RTMP stream. Used", "= None def getDesktop1(self): return self.datain['desktop-1'] def getDesktop2(self): return self.datain['desktop-2']", "scene the scene item belongs to. Defaults to the currently", "instance :Returns: *sources* type: Array<Object> Array of sources *sources.*.name* type:", "Source item rotation (in degrees). \"\"\" def __init__(self, item, x_scale,", "Framerate. *shutdown* type: boolean (optional) Indicates whether the source should", "Transition duration. `-1` if no override is set. \"\"\" def", "set to `true`. \"\"\" def __init__(self, stream=None): Baserequests.__init__(self) self.name =", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStudioModeStatus' self.datain['studio-mode'] = None", "present if `use_auth` is `true`. *settings.password* type: String The password", "the bounding box. *sourceWidth* type: int Base width (without scaling)", "scene *sceneItems* type: Array<Object> Array of scene items *sceneItems.*.itemId* type:", "self.name = 'GetMediaDuration' self.datain['mediaDuration'] = None self.dataout['sourceName'] = sourceName def", "type: String Scene Item name. *top* type: int Pixel position", "interpret dB values under -100.0 as Inf. Note: The OBS", "type: String Current filename formatting string. \"\"\" def __init__(self): Baserequests.__init__(self)", "profile. \"\"\" def __init__(self, profile_name): Baserequests.__init__(self) self.name = 'SetCurrentProfile' self.dataout['profile-name']", "The password to use when accessing the streaming server. Only", "name of the active preview scene. *sources* type: Array<SceneItem> \"\"\"", "= None self.datain['outputWidth'] = None self.datain['outputHeight'] = None self.datain['scaleType'] =", "def __init__(self, keyId, keyModifiers): Baserequests.__init__(self) self.name = 'TriggerHotkeyBySequence' self.dataout['keyId'] =", "Replay Buffer is not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "String Source name. :Returns: *name* type: String Source name. *offset*", "not active or already paused. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "different than the current streaming service type, all settings are", "(unknown function). *gradient* type: boolean (optional) Gradient enabled. *gradient_color* type:", "group it belongs to). :Arguments: *scene_name* type: String (optional) Name", ":Arguments: *text* type: String Captions text \"\"\" def __init__(self, text):", "\"\"\"Toggle the Replay Buffer on/off (depending on the current state", "Returns an error if recording is not active or already", "paused. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'PauseRecording' class ResumeRecording(Baserequests):", "the given object parameters as encoded query string parameters to", "object) \"\"\" def __init__(self, item, scene_name=None): Baserequests.__init__(self) self.name = 'ResetSceneItem'", "belongs to a group) *groupChildren* type: Array<SceneItemTransform> (optional) List of", "in the `supported-image-export-formats` response field of `GetVersion`). If not specified,", "int The number of pixels cropped off the right of", "= sourceName def getMonitorType(self): return self.datain['monitorType'] class SetAudioMonitorType(Baserequests): \"\"\"Set the", "recording is paused or not. *recordTimecode* type: String (optional) Time", "Baserequests.__init__(self) self.name = 'AddSceneItem' self.datain['itemId'] = None self.dataout['sceneName'] = sceneName", "__init__(self, source): Baserequests.__init__(self) self.name = 'GetBrowserSourceProperties' self.datain['source'] = None self.datain['is_local_file']", "String Name of the currently active scene. *scenes* type: Array<Scene>", "attenuation instead of amplitude/mul. :Returns: *name* type: String Source name.", "currently streaming). *rec_timecode* type: String (optional) Time elapsed since recording", "v25.0.8) :Arguments: *sourceName* type: String Source name. :Returns: *mediaState* type:", "with_transition class EnableStudioMode(Baserequests): \"\"\"Enables Studio Mode. \"\"\" def __init__(self): Baserequests.__init__(self)", "boolean Read text from the specified file. *log_mode* type: boolean", "= None self.datain['is_local_file'] = None self.datain['local_file'] = None self.datain['url'] =", "String Source name. :Returns: *mediaDuration* type: int The total length", "to a source :Arguments: *sourceName* type: String Source name *filterName*", "= gradient_dir self.dataout['gradient_opacity'] = gradient_opacity self.dataout['outline'] = outline self.dataout['outline_color'] =", "String Text Alignment (\"left\", \"center\", \"right\"). *bk_color* type: int Background", "None self.dataout['sceneName'] = sceneName def getTransitionName(self): return self.datain['transitionName'] def getTransitionDuration(self):", "source, volume, useDecibel=None): Baserequests.__init__(self) self.name = 'SetVolume' self.dataout['source'] = source", "media sources (vlc and media source) :Returns: *mediaSources* type: Array<Object>", "sources (as of OBS v25.0.8) Note: For some reason, for", "be any String, Numeric, or Boolean field. *stream.settings* type: Object", "the client *data* type: Object User-defined data \"\"\" def __init__(self,", "type: String Output name :Returns: *outputInfo* type: Output Output info", "when connecting to the streaming server. *stream.settings.username* type: String (optional)", "color. *extents* type: boolean (optional) Extents wrap. *extents_cx* type: int", "second Mic/Aux input source. *mic_3* type: String (optional) NAme of", "source or scene to be displayed (ignored for other projector", "getVisible(self): return self.datain['visible'] def getMuted(self): return self.datain['muted'] def getLocked(self): return", "Trigger Command Key (Mac) \"\"\" def __init__(self, keyId, keyModifiers): Baserequests.__init__(self)", "Baserequests.__init__(self) self.name = 'GetStreamSettings' self.datain['type'] = None self.datain['settings'] = None", "settings to disk. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'SaveStreamSettings'", "specified. :Arguments: *sourceName* type: String (optional) Source name. Note that,", "self.dataout['locked'] = locked self.dataout['bounds'] = bounds class ResetSceneItem(Baserequests): \"\"\"Reset a", "self.dataout['item'] = item self.dataout['fromScene'] = fromScene self.dataout['toScene'] = toScene def", "a list of available profiles. :Returns: *profiles* type: Array<Object> List", "OBSStats [OBS stats](#obsstats) \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStats'", "*volume* type: double Volume of the source. Between `0.0` and", "not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'SaveReplayBuffer' class", "stream. *settings.server* type: String (optional) The publish URL. *settings.key* type:", "None self.datain['item'] = None self.dataout['item'] = item self.dataout['fromScene'] = fromScene", "def getRecording(self): return self.datain['recording'] def getStreamTimecode(self): return self.datain['stream-timecode'] def getRecTimecode(self):", "`width` and `height` parameters to receive scaled pictures. Aspect ratio", "= drop_shadow self.dataout['font'] = font self.dataout['from_file'] = from_file self.dataout['log_mode'] =", "will occur when starting the stream. *stream.metadata* type: Object (optional)", "return an `error` if Studio Mode is not enabled. :Arguments:", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetVersion' self.datain['version'] = None", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'EnableStudioMode' class DisableStudioMode(Baserequests): \"\"\"Disables", "require some probing around). :Returns: *sourceName* type: String Source name", "(optional) Url. *css* type: String (optional) CSS to inject. *width*", "`buffering`, `paused`, `stopped`, `ended`, `error`, `unknown` \"\"\" def __init__(self): Baserequests.__init__(self)", "degrees around the point of alignment. *scale.x* type: double The", "type: String Name of the currently active scene collection. \"\"\"", "list of all available sources types :Returns: *types* type: Array<Object>", "\"\"\"Start recording. Will return an `error` if recording is already", "before scaling. *crop.left* type: int (optional) The new amount of", "getIsReplayBufferActive(self): return self.datain['isReplayBufferActive'] class StartStopReplayBuffer(Baserequests): \"\"\"Toggle the Replay Buffer on/off", "Indicates whether authentication is required. *challenge* type: String (optional) *salt*", "current recording status. :Returns: *isRecording* type: boolean Current recording status.", "*scale.x* type: double (optional) The new x scale of the", "getScaleType(self): return self.datain['scaleType'] def getFps(self): return self.datain['fps'] def getVideoFormat(self): return", "*height* type: double Scene item height (base source height multiplied", "sceneName self.dataout['sourceName'] = sourceName self.dataout['setVisible'] = setVisible def getItemId(self): return", "self.datain['local_file'] = None self.datain['url'] = None self.datain['css'] = None self.datain['width']", "String Name of the transition to use. *transitionDuration* type: int", "def __init__(self): Baserequests.__init__(self) self.name = 'GetStreamingStatus' self.datain['streaming'] = None self.datain['recording']", "type: String The type of streaming service configuration. Possible values:", "Indicates whether the source is muted. \"\"\" def __init__(self, source,", "getChatlog_lines(self): return self.datain['chatlog_lines'] def getColor(self): return self.datain['color'] def getExtents(self): return", "to the current filter settings. \"\"\" def __init__(self, sourceName, filterName,", "String Non-unique internal source type ID *types.*.displayName* type: String Display", "= 'GetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName'] = transitionName def getTransitionSettings(self):", "(optional) Type of the specified source. Useful for type-checking if", "self.datain['source'] def getAlign(self): return self.datain['align'] def getBk_color(self): return self.datain['bk_color'] def", "transitionSettings): Baserequests.__init__(self) self.name = 'SetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName'] =", "getMuted(self): return self.datain['muted'] class SetMute(Baserequests): \"\"\"Sets the mute status of", "self.datain['itemId'] = None self.dataout['sceneName'] = sceneName self.dataout['sourceName'] = sourceName self.dataout['setVisible']", "or 8=Bottom, or omit to center on that axis. *rotation*", "type: double The y position of the source from the", "name. Note that, since scenes are also sources, you can", "color. *color2* type: int Gradient bottom color. *custom_width* type: int", "'GetSceneTransitionOverride' self.datain['transitionName'] = None self.datain['transitionDuration'] = None self.dataout['sceneName'] = sceneName", "the scene item belongs to. Defaults to the current scene.", "specified source. Default response uses mul format, NOT SLIDER PERCENTAGE.", "path to the recording file (only present if currently recording).", "return self.datain['challenge'] def getSalt(self): return self.datain['salt'] class Authenticate(Baserequests): \"\"\"Attempt to", "GetSourceTypesList(Baserequests): \"\"\"Get a list of all available sources types :Returns:", "of the filter to remove \"\"\" def __init__(self, sourceName, filterName):", "monitor is -1). Encoded in Base64 using [Qt's geometry encoding](https://doc.qt.io/qt-5/qwidget.html#saveGeometry).", "type: int (optional) Screenshot height. Defaults to the source's base", "\"\"\"Returns the latest version of the plugin and the API.", "sources (as of OBS v25.0.8) Note: Due to processing/network delays,", "of a specific scene item. Unique on a scene by", "for retrocompatibility. *obs_websocket_version* type: String obs-websocket plugin version. *obs_studio_version* type:", "'GetSourceTypesList' self.datain['types'] = None def getTypes(self): return self.datain['types'] class GetVolume(Baserequests):", "for the streaming service. *save* type: boolean Persist the settings", "= useDecibel def getName(self): return self.datain['name'] def getVolume(self): return self.datain['volume']", "transition. *with_transition.name* type: String Name of the transition. *with_transition.duration* type:", "self.dataout['filterName'] = filterName self.dataout['filterType'] = filterType self.dataout['filterSettings'] = filterSettings class", "file extension. *compressionQuality* type: int (optional) Compression ratio between -1", "an error if recording is not active or not paused.", "of all media sources (vlc and media source) :Returns: *mediaSources*", "self.dataout['extents'] = extents self.dataout['extents_cx'] = extents_cx self.dataout['extents_cy'] = extents_cy self.dataout['file']", "Note: Controlling outputs is an experimental feature of obs-websocket. Some", "media position. \"\"\" def __init__(self, sourceName, timeOffset): Baserequests.__init__(self) self.name =", "of the source to which the filter belongs *filterName* type:", "of the item in degrees around the point of alignment.", "if using dB. *muted* type: boolean Indicates whether the source", "type: String Source name *img* type: String Image Data URI", "self.name = 'DuplicateSceneItem' self.datain['scene'] = None self.datain['item'] = None self.dataout['item']", "self.datain['streaming'] = None self.datain['recording'] = None self.datain['stream-timecode'] = None self.datain['rec-timecode']", "self.datain['rotation'] = None self.datain['scale'] = None self.datain['crop'] = None self.datain['visible']", "capture source. *mic_1* type: String (optional) Name of the first", "def __init__(self, transitionName, transitionSettings): Baserequests.__init__(self) self.name = 'SetTransitionSettings' self.datain['transitionSettings'] =", "String (optional) The password for the streaming service. *save* type:", "is called while a recording is in progress, the change", "self.datain['rotation'] def getScale(self): return self.datain['scale'] def getCrop(self): return self.datain['crop'] def", "*types.*.caps.canInteract* type: Boolean True if interaction with this sources of", "Baserequests.__init__(self) self.name = 'GetSourceFilters' self.datain['filters'] = None self.dataout['sourceName'] = sourceName", "of pixels cropped off the bottom of the source before", "Non-unique source internal type (a.k.a kind) *sources.*.type* type: String Source", "\"\"\"Pause the current recording. Returns an error if recording is", "Scene Item name (if this field is a string) or", "a specific scene item. Unique on a scene by scene", "field of `GetVersion`). If not specified, tries to guess based", "boolean (optional) Gradient enabled. *gradient_color* type: int (optional) Gradient color.", "__init__(self, sceneName=None): Baserequests.__init__(self) self.name = 'GetSceneItemList' self.datain['sceneName'] = None self.datain['sceneItems']", "Baserequests.__init__(self) self.name = 'GetRecordingFolder' self.datain['rec-folder'] = None def getRecFolder(self): return", "newer. :Arguments: *type* type: String (Optional) Type of projector: `Preview`", "= None self.datain['color'] = None self.datain['extents'] = None self.datain['extents_cx'] =", "def getTransitionDuration(self): return self.datain['transition-duration'] class GetTransitionPosition(Baserequests): \"\"\"Get the position of", "name. *mute* type: boolean Desired mute status. \"\"\" def __init__(self,", "self.name = 'GetSpecialSources' self.datain['desktop-1'] = None self.datain['desktop-2'] = None self.datain['mic-1']", "recording is in progress, the change won't be applied immediately", "for more information). \"\"\" def __init__(self, auth): Baserequests.__init__(self) self.name =", "self.name = 'GetSourceFilters' self.datain['filters'] = None self.dataout['sourceName'] = sourceName def", "self.datain['mediaSources'] class CreateSource(Baserequests): \"\"\"Create a source and add it as", "double Volume of the source. Between `0.0` and `20.0` if", "multiple successive T-Bar moves (e.g. : in an animation, or", "'OpenProjector' self.dataout['type'] = type self.dataout['monitor'] = monitor self.dataout['geometry'] = geometry", "type: String OBS Studio program version. *available_requests* type: String List", "= None self.datain['recordTimecode'] = None self.datain['recordingFilename'] = None def getIsRecording(self):", "SetCurrentProfile(Baserequests): \"\"\"Set the currently active profile. :Arguments: *profile_name* type: String", "getBk_opacity(self): return self.datain['bk_opacity'] def getChatlog(self): return self.datain['chatlog'] def getChatlog_lines(self): return", "specified scene. :Arguments: *scene_name* type: String Name of the scene", "of the created scene item \"\"\" def __init__(self, sceneName, sourceName,", "to the saved image file (if `saveToFilePath` was specified in", "vlc media sources (as of OBS v25.0.8) Note: For some", "= None def getMediaSources(self): return self.datain['mediaSources'] class CreateSource(Baserequests): \"\"\"Create a", "class GetSourceSettings(Baserequests): \"\"\"Get settings of the specified source :Arguments: *sourceName*", "\"\"\" def __init__(self, enable): Baserequests.__init__(self) self.name = 'SetHeartbeat' self.dataout['enable'] =", "projector types). \"\"\" def __init__(self, type, monitor, geometry, name): Baserequests.__init__(self)", "class GetTextGDIPlusProperties(Baserequests): \"\"\"Get the current properties of a Text GDI", "sourceName, monitorType): Baserequests.__init__(self) self.name = 'SetAudioMonitorType' self.dataout['sourceName'] = sourceName self.dataout['monitorType']", ":Arguments: *sourceName* type: String Source name. *sourceType* type: String (optional)", "Baserequests.__init__(self) self.name = 'ScrubMedia' self.dataout['sourceName'] = sourceName self.dataout['timeOffset'] = timeOffset", "String Name of the source to be added *setVisible* type:", "TriggerHotkeyByName(Baserequests): \"\"\"Executes hotkey routine, identified by hotkey unique name :Arguments:", "window (only if monitor is -1). Encoded in Base64 using", "the filter to reconfigure *filterSettings* type: Object New settings. These", "= scene_name class TransitionToProgram(Baserequests): \"\"\"Transitions the currently previewed scene to", "self.name = 'GetRecordingFolder' self.datain['rec-folder'] = None def getRecFolder(self): return self.datain['rec-folder']", "`rtmp_custom` or `rtmp_common`. *settings* type: Object The actual settings of", "Filter settings \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetSourceFilters'", "self.datain['offset'] = None self.dataout['source'] = source def getName(self): return self.datain['name']", "Boolean True if source of this type provide frames asynchronously", "\"\"\" def __init__(self, profile_name): Baserequests.__init__(self) self.name = 'SetCurrentProfile' self.dataout['profile-name'] =", "string \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetVersion' self.datain['version'] =", "right, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemCrop' self.dataout['item'] = item self.dataout['top']", "String (optional) file path. *url* type: String (optional) Url. *css*", "along with their settings properties are available from `GetSourceTypesList`. :Arguments:", "Outline size. *outline_opacity* type: int Outline opacity (0-100). *text* type:", "code needs to perform multiple successive T-Bar moves (e.g. :", "Style (unknown function). *gradient* type: boolean Gradient enabled. *gradient_color* type:", "getFilters(self): return self.datain['filters'] class GetSourceFilterInfo(Baserequests): \"\"\"List filters applied to a", "False entries can be ommitted *keyModifiers.shift* type: boolean Trigger Shift", "getOutline(self): return self.datain['outline'] def getText(self): return self.datain['text'] def getText_file(self): return", "`stopped`, `ended`, `error`, `unknown` \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name", "type to use. Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self,", "def getMic3(self): return self.datain['mic-3'] class GetSourceFilters(Baserequests): \"\"\"List filters applied to", "*height* type: int (optional) Height. *fps* type: int (optional) Framerate.", "\"\"\"Get the name of the currently previewed scene and its", "type: int (optional) Font text size. *font.style* type: String (optional)", "self.dataout['useDecibel'] = useDecibel class GetMute(Baserequests): \"\"\"Get the mute status of", "source self.dataout['color1'] = color1 self.dataout['color2'] = color2 self.dataout['custom_width'] = custom_width", "Item ID. \"\"\" def __init__(self, item, scene=None): Baserequests.__init__(self) self.name =", "Boolean True if sources of this type provide video *types.*.caps.hasAudio*", "SetSourceFilterSettings(Baserequests): \"\"\"Update settings of a filter :Arguments: *sourceName* type: String", "between 0.0 and 1.0. *release* type: boolean (optional) Whether or", "18:26:33.661372) # from .base_classes import Baserequests class GetVersion(Baserequests): \"\"\"Returns the", "use. Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self, sourceName, monitorType):", "SetSourceSettings(Baserequests): \"\"\"Set settings of the specified source. :Arguments: *sourceName* type:", "*sourceName* type: String (optional) Source name. Note that, since scenes", "self.datain['width'] def getHeight(self): return self.datain['height'] def getParentGroupName(self): return self.datain['parentGroupName'] def", "Source type capabilities *types.*.caps.isAsync* type: Boolean True if source of", "= word_wrap class GetBrowserSourceProperties(Baserequests): \"\"\"Get current properties for a Browser", "locked=None, bounds=None): Baserequests.__init__(self) self.name = 'SetSceneItemProperties' self.dataout['item'] = item self.dataout['scene-name']", "next media item in the playlist. Supports only vlc media", "play the source. `false` for play, `true` for pause. \"\"\"", "= None self.datain['parentGroupName'] = None self.datain['groupChildren'] = None self.dataout['item'] =", "the Replay Buffer is already active or if the \"Save", "won't be applied immediately and will be effective on the", "type: Object Updated transition settings \"\"\" def __init__(self, transitionName, transitionSettings):", "image type. *width* type: int (optional) Screenshot width. Defaults to", "*text_file* type: String File path. *word_wrap* type: boolean Word wrap.", "items in a scene. :Arguments: *sceneName* type: String (optional) Name", "Name of the filter to reorder *newIndex* type: Integer Desired", "*itemId* type: int Scene Item ID. *position.x* type: double The", "Source settings (varies between source types, may require some probing", "if no override is set. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self)", "None self.dataout['sourceName'] = sourceName def getMediaDuration(self): return self.datain['mediaDuration'] class GetMediaTime(Baserequests):", "settings of the stream. *settings.server* type: String (optional) The publish", "*sourceName* type: String Name of the source to be added", "the recording folder. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetRecordingFolder'", "__init__(self): Baserequests.__init__(self) self.name = 'EnableStudioMode' class DisableStudioMode(Baserequests): \"\"\"Disables Studio Mode.", "to a scene. :Arguments: *sourceName* type: String Source name. *sourceKind*", "information). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSceneList' self.datain['current-scene'] =", "since recording started (only present if currently recording). *preview_only* type:", "filename_formatting): Baserequests.__init__(self) self.name = 'SetFilenameFormatting' self.dataout['filename-formatting'] = filename_formatting class GetFilenameFormatting(Baserequests):", "or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int (optional) The new alignment of", "int Millisecond offset (positive or negative) to offset the current", "a user moving a T-Bar control in your User Interface),", "String Scene Item name. *x* type: double X coordinate. *y*", "__init__(self, filename_formatting): Baserequests.__init__(self) self.name = 'SetFilenameFormatting' self.dataout['filename-formatting'] = filename_formatting class", "active or if the \"Save Replay Buffer\" hotkey is not", "self.datain['itemId'] class GetSourcesList(Baserequests): \"\"\"List all sources available in the running", "(if the `item` field is an object) *item.id* type: int", "field. *stream.settings* type: Object (optional) Settings for the stream. *stream.settings.server*", "*settings.key* type: String (optional) The publish key. *settings.use_auth* type: boolean", "of the SceneItem in the scene. \"\"\" def __init__(self, sourceName,", "outline_opacity self.dataout['text'] = text self.dataout['valign'] = valign self.dataout['vertical'] = vertical", "\"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int Alignment of the", "'GetFilenameFormatting' self.datain['filename-formatting'] = None def getFilenameFormatting(self): return self.datain['filename-formatting'] class GetStats(Baserequests):", "__init__(self): Baserequests.__init__(self) self.name = 'GetFilenameFormatting' self.datain['filename-formatting'] = None def getFilenameFormatting(self):", "def getGradient_dir(self): return self.datain['gradient_dir'] def getGradient_opacity(self): return self.datain['gradient_opacity'] def getOutline(self):", "SetSceneItemRender(Baserequests): \"\"\"Show or hide a specified source item in a", "the item. *crop.top* type: int (optional) The new amount of", "top of the source before scaling. *crop.right* type: int The", "def __init__(self, sourceName, filterName): Baserequests.__init__(self) self.name = 'RemoveFilterFromSource' self.dataout['sourceName'] =", "self.datain['name'] def getSources(self): return self.datain['sources'] class SetPreviewScene(Baserequests): \"\"\"Set the active", "The point on the source that the item is manipulated", "`stopped`, `ended`, `error`, `unknown` \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "None self.datain['videoFormat'] = None self.datain['colorSpace'] = None self.datain['colorRange'] = None", "width of the bounding box. *bounds.y* type: double (optional) The", "file. *log_mode* type: boolean (optional) Chat log. *outline* type: boolean", "of the recording folder. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "the current scene. *item* type: String | Object Scene Item", "def getSourceType(self): return self.datain['sourceType'] def getSourceSettings(self): return self.datain['sourceSettings'] class SetSourceSettings(Baserequests):", "class GetMediaState(Baserequests): \"\"\"Get the current playing state of a media", "\"\"\"Get a list of all available sources types :Returns: *types*", "*isRecordingPaused* type: boolean Whether the recording is paused or not.", "false) \"\"\" def __init__(self, outputName, force=None): Baserequests.__init__(self) self.name = 'StopOutput'", "type: String Name of the currently active scene. *scenes* type:", "\"\"\"List of all transitions available in the frontend's dropdown menu.", "sending of the Heartbeat event :Arguments: *enable* type: boolean Starts/Stops", "String Scene Item name. *x_scale* type: double Width scale factor.", "(base source width multiplied by the horizontal scaling factor) *height*", "*recordingFilename* type: String (optional) Absolute path to the recording file", "def __init__(self, sceneName, sourceName, setVisible): Baserequests.__init__(self) self.name = 'AddSceneItem' self.datain['itemId']", "None self.datain['img'] = None self.datain['imageFile'] = None self.dataout['sourceName'] = sourceName", "type of the source. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\",", "type: String Name of the scene to create. \"\"\" def", "items in the requested scene. :Arguments: *scene* type: String (optional)", "the source to which the filter belongs *filterName* type: String", "scene. In other words, this is how you add a", "Object Transition settings (they can be partial) :Returns: *transitionSettings* type:", "source types along with their settings properties are available from", "= 'ToggleStudioMode' class GetTransitionList(Baserequests): \"\"\"List of all transitions available in", "since streaming started (only present if currently streaming). *rec_timecode* type:", "= None self.dataout['source'] = source def getSource(self): return self.datain['source'] def", "Text color. *extents* type: boolean Extents wrap. *extents_cx* type: int", "outputName, force=None): Baserequests.__init__(self) self.name = 'StopOutput' self.dataout['outputName'] = outputName self.dataout['force']", "is an object) *position.x* type: double (optional) The new x", "Item name. *itemId* type: int Scene Item ID. *position.x* type:", "New settings. These will be merged to the current filter", "by bound combination of keys. A single key combination might", "filterSettings class SetSourceFilterVisibility(Baserequests): \"\"\"Change the visibility/enabled state of a filter", "SetSceneItemProperties(Baserequests): \"\"\"Sets the scene specific properties of a source. Unspecified", "-*- coding: utf-8 -*- # THIS FILE WAS GENERATED BY", "= hotkeyName class TriggerHotkeyBySequence(Baserequests): \"\"\"Executes hotkey routine, identified by bound", "color1=None, color2=None, custom_width=None, drop_shadow=None, font=None, from_file=None, log_mode=None, outline=None, text=None, text_file=None,", "def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionPosition' self.datain['position'] = None def", "*transition_name* type: String The name of the transition. \"\"\" def", "String Source name *color1* type: int Gradient top color. *color2*", "*file* type: String File path name. *read_from_file* type: boolean Read", "getAlign(self): return self.datain['align'] def getBk_color(self): return self.datain['bk_color'] def getBk_opacity(self): return", "self.name = 'ReorderSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['newIndex']", "(depending on the current state of the replay buffer). \"\"\"", "return self.datain['transition-duration'] class GetTransitionPosition(Baserequests): \"\"\"Get the position of the current", "*item* type: String | Object Scene Item name (if this", "configured stream type does not match the given stream type,", "(optional) Special stream configuration. Please note: these won't be saved", "the source item. \"\"\" def __init__(self, item, top, bottom, left,", "scene item's source *sceneItems.*.sourceType* type: String Type of the scene", "*gradient_opacity* type: int (optional) Gradient opacity (0-100). *outline* type: boolean", "self.datain['transitionName'] = None self.datain['transitionDuration'] = None self.dataout['sceneName'] = sceneName def", "= None self.datain['width'] = None self.datain['height'] = None self.datain['fps'] =", "stream matches the given type (usually 'rtmp_custom' or 'rtmp_common'). If", "height=None): Baserequests.__init__(self) self.name = 'TakeSourceScreenshot' self.datain['sourceName'] = None self.datain['img'] =", "T-Bar gets released automatically after setting its new position (like", "value is not given. \"\"\" def __init__(self, sceneName, transitionName, transitionDuration):", "self.dataout['x-scale'] = x_scale self.dataout['y-scale'] = y_scale self.dataout['rotation'] = rotation self.dataout['scene-name']", "*keyModifiers.shift* type: boolean Trigger Shift Key *keyModifiers.alt* type: boolean Trigger", "self.dataout['gradient_color'] = gradient_color self.dataout['gradient_dir'] = gradient_dir self.dataout['gradient_opacity'] = gradient_opacity self.dataout['outline']", "locked. *bounds.type* type: String Type of bounding box. Can be", "embedPictureFormat=None, saveToFilePath=None, fileFormat=None, compressionQuality=None, width=None, height=None): Baserequests.__init__(self) self.name = 'TakeSourceScreenshot'", "\"\"\" Note: If the new name already exists as a", "rate of this request has also not been tested. :Arguments:", "collection. \"\"\" def __init__(self, sc_name): Baserequests.__init__(self) self.name = 'SetCurrentSceneCollection' self.dataout['sc-name']", "(optional) File path name. *read_from_file* type: boolean (optional) Read text", "to). :Arguments: *scene_name* type: String (optional) Name of the scene", "return an `error` if Studio Mode is not enabled. :Returns:", "list *scene_collections.*.sc_name* type: String Scene collection name \"\"\" def __init__(self):", "to the main output. Will return an `error` if Studio", "def __init__(self): Baserequests.__init__(self) self.name = 'GetSourceTypesList' self.datain['types'] = None def", "settings a set of settings incompatible with the actual source's", "of the source. *position.alignment* type: int (optional) The new alignment", "type: String Source name. :Returns: *timestamp* type: int The time", "String Text content to be displayed. *valign* type: String Text", "does not match the given stream type, all settings must", "__init__(self, auth): Baserequests.__init__(self) self.name = 'Authenticate' self.dataout['auth'] = auth class", "String The monitor type to use. Options: `none`, `monitorOnly`, `monitorAndOutput`.", "(canvas) width *baseHeight* type: int Base (canvas) height *outputWidth* type:", "valign self.dataout['vertical'] = vertical self.dataout['render'] = render class GetTextFreetype2Properties(Baserequests): \"\"\"Get", "Scene Item to duplicate from the source scene (required) *item.name*", "Note that, since scenes are also sources, you can also", "type: String Absolute path to the saved image file (if", "face. *font.flags* type: int Font text styling flag. `Bold=1, Italic=2,", "can specify `width` and `height` parameters to receive scaled pictures.", "Object Updated transition settings \"\"\" def __init__(self, transitionName, transitionSettings): Baserequests.__init__(self)", "'SetSceneItemTransform' self.dataout['item'] = item self.dataout['x-scale'] = x_scale self.dataout['y-scale'] = y_scale", "the item is manipulated from. The sum of 1=Left or", "item in *sourceName* type: String Name of the source to", "If not specified, tries to guess based on file extension.", "ensures the type of stream matches the given type (usually", "= None self.dataout['source'] = source def getName(self): return self.datain['name'] def", "New item ID *item.name* type: String New item name \"\"\"", "of source types *types.*.typeId* type: String Non-unique internal source type", "or an error will occur when starting the stream. *stream.metadata*", "None self.datain['isRecordingPaused'] = None self.datain['recordTimecode'] = None self.datain['recordingFilename'] = None", "The number of pixels cropped off the bottom of the", "= extents_cx self.dataout['extents_cy'] = extents_cy self.dataout['file'] = file self.dataout['read_from_file'] =", "return self.datain['baseHeight'] def getOutputWidth(self): return self.datain['outputWidth'] def getOutputHeight(self): return self.datain['outputHeight']", "\"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaState' self.datain['mediaState'] =", "*bk_color* type: int Background color. *bk_opacity* type: int Background opacity", "Base width (without scaling) of the source *sourceHeight* type: int", "of the current profile's scenes (See [GetCurrentScene](#getcurrentscene) for more information).", "not set to `true`. *stream.settings.password* type: String (optional) If authentication", "type provide frames asynchronously *types.*.caps.hasVideo* type: Boolean True if sources", "If -1 or omitted, opens a window. *geometry* type: String", "from_file self.dataout['log_mode'] = log_mode self.dataout['outline'] = outline self.dataout['text'] = text", "present if currently recording). \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "\"Save Replay Buffer\" hotkey. Will return an `error` if the", "transition if supported. :Returns: *transition_duration* type: int Duration of the", "class ReorderSceneItems(Baserequests): \"\"\"Changes the order of scene items in the", "(they can be partial) :Returns: *transitionSettings* type: Object Updated transition", "specified source :Arguments: *sourceName* type: String Source name. *sourceType* type:", "name *mediaSources.*.sourceKind* type: String Unique source internal type (a.k.a `ffmpeg_source`", "type: String Source name. *useDecibel* type: boolean (optional) Output volume", "or not) *type* type: String Filter type *name* type: String", "x-scale factor of the source. *scale.y* type: double The y-scale", "service about the streaming. May be any String, Numeric, or", "*stream.settings.key* type: String (optional) The publish key of the stream.", "\"\"\" def __init__(self, text): Baserequests.__init__(self) self.name = 'SendCaptions' self.dataout['text'] =", "the source *sourceHeight* type: int Base source (without scaling) of", "= extents self.dataout['extents_cx'] = extents_cx self.dataout['extents_cy'] = extents_cy self.dataout['file'] =", "(optional) Background opacity (0-100). *chatlog* type: boolean (optional) Chat log.", "the source to be added *setVisible* type: boolean Whether to", "fileFormat=None, compressionQuality=None, width=None, height=None): Baserequests.__init__(self) self.name = 'TakeSourceScreenshot' self.datain['sourceName'] =", "the sceneitem visible on creation or not. Default `true` :Returns:", "offset the current media position. \"\"\" def __init__(self, sourceName, timeOffset):", "150, \"style\": \"\" }` *font.face* type: String (optional) Font face.", "self.datain['filename-formatting'] class GetStats(Baserequests): \"\"\"Get OBS stats (almost the same info", "\"\"\" def __init__(self, type, monitor, geometry, name): Baserequests.__init__(self) self.name =", "Defaults to the source's base height. :Returns: *sourceName* type: String", "*sourceName* type: String Name of the source on which the", "size. *outline_opacity* type: int Outline opacity (0-100). *text* type: String", "the current scene. *item* type: String Scene Item name. *top*", "*geometry* type: String (Optional) Size and position of the projector", "response uses mul format, NOT SLIDER PERCENTAGE. :Arguments: *source* type:", "String How to move the filter around in the source's", "on which the filter is added *filterName* type: String Name", "are also sources, you can also provide a scene name.", "\"OBS_BOUNDS_NONE\". *bounds.alignment* type: int Alignment of the bounding box. *bounds.x*", "to `false`.* \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ReleaseTBar' class", "def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'RemoveSceneTransitionOverride' self.dataout['sceneName'] = sceneName", "= rotation self.dataout['scene-name'] = scene_name class SetSceneItemCrop(Baserequests): \"\"\"Sets the crop", "*keyModifiers.control* type: boolean Trigger Control (Ctrl) Key *keyModifiers.command* type: boolean", "getOffset(self): return self.datain['offset'] class GetSourceSettings(Baserequests): \"\"\"Get settings of the specified", "the source before scaling. *visible* type: bool (optional) The new", "bool If the source is visible. *muted* type: bool If", "type: String (Optional) Type of projector: `Preview` (default), `Source`, `Scene`,", "getWidth(self): return self.datain['width'] def getHeight(self): return self.datain['height'] def getParentGroupName(self): return", "\"\"\" def __init__(self, outputName, force=None): Baserequests.__init__(self) self.name = 'StopOutput' self.dataout['outputName']", "type: Object (optional) Source settings data. *setVisible* type: boolean (optional)", "Default settings of this source type *types.*.caps* type: Object Source", "String New source name. \"\"\" def __init__(self, sourceName, newName): Baserequests.__init__(self)", "to the currently active scene. *source* type: String Scene Item", "\"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int (optional) The new", "font self.dataout['gradient'] = gradient self.dataout['gradient_color'] = gradient_color self.dataout['gradient_dir'] = gradient_dir", "'GetVolume' self.datain['name'] = None self.datain['volume'] = None self.datain['muted'] = None", "Source name. *offset* type: int The desired audio sync offset", ":Returns: *sceneName* type: String Name of the requested (or current)", "*scene* type: String Name of the scene where the new", "type: boolean Persist the settings to disk. \"\"\" def __init__(self,", "desired profile. \"\"\" def __init__(self, profile_name): Baserequests.__init__(self) self.name = 'SetCurrentProfile'", "streaming server. Only present if `use_auth` is `true`. \"\"\" def", "is no current override and this value is not given.", "specified scene. :Arguments: *scene_name* type: String (optional) Name of the", "None self.datain['from_file'] = None self.datain['log_mode'] = None self.datain['outline'] = None", "displayed (ignored for other projector types). \"\"\" def __init__(self, type,", "int Base (canvas) height *outputWidth* type: int Output width *outputHeight*", "self.dataout['scene-name'] = scene_name def getName(self): return self.datain['name'] def getItemId(self): return", "Unspecified properties will remain unchanged. Coordinates are relative to the", "\"\"\"Set the currently active profile. :Arguments: *profile_name* type: String Name", "self.name = 'GetTextFreetype2Properties' self.datain['source'] = None self.datain['color1'] = None self.datain['color2']", "\"\"\" def __init__(self, sceneName, transitionName, transitionDuration): Baserequests.__init__(self) self.name = 'SetSceneTransitionOverride'", "(optional) Name of the scene the source item belongs to.", "*settings* type: Object Stream settings object. *settings.server* type: String The", "getOutline_color(self): return self.datain['outline_color'] def getOutline_size(self): return self.datain['outline_size'] def getOutline_opacity(self): return", "= None self.datain['locked'] = None self.datain['bounds'] = None self.datain['sourceWidth'] =", "= None self.datain['local_file'] = None self.datain['url'] = None self.datain['css'] =", "Name of the currently active transition. *transitions* type: Array<Object> List", "= right self.dataout['scene-name'] = scene_name class DeleteSceneItem(Baserequests): \"\"\"Deletes a scene", "return self.datain['gradient_opacity'] def getOutline(self): return self.datain['outline'] def getOutline_color(self): return self.datain['outline_color']", "sc_name class GetCurrentSceneCollection(Baserequests): \"\"\"Get the name of the current scene", "Baserequests.__init__(self) self.name = 'GetTransitionDuration' self.datain['transition-duration'] = None def getTransitionDuration(self): return", "height=None, fps=None, shutdown=None, render=None): Baserequests.__init__(self) self.name = 'SetBrowserSourceProperties' self.dataout['source'] =", "from .base_classes import Baserequests class GetVersion(Baserequests): \"\"\"Returns the latest version", "won't be saved to OBS' configuration. *stream.type* type: String (optional)", "extents self.dataout['extents_cx'] = extents_cx self.dataout['extents_cy'] = extents_cy self.dataout['file'] = file", "= 'PauseRecording' class ResumeRecording(Baserequests): \"\"\"Resume/unpause the current recording (if paused).", "is possible *types.*.caps.isComposite* type: Boolean True if sources of this", "specified source *filters.*.enabled* type: Boolean Filter status (enabled or not)", "def getScaleType(self): return self.datain['scaleType'] def getFps(self): return self.datain['fps'] def getVideoFormat(self):", "self.datain['source'] = None self.datain['is_local_file'] = None self.datain['local_file'] = None self.datain['url']", "filterName): Baserequests.__init__(self) self.name = 'RemoveFilterFromSource' self.dataout['sourceName'] = sourceName self.dataout['filterName'] =", "if the Replay Buffer is already active or if the", "of a media source. Supports ffmpeg and vlc media sources", "chatlog self.dataout['chatlog_lines'] = chatlog_lines self.dataout['color'] = color self.dataout['extents'] = extents", "Baserequests.__init__(self) self.name = 'SaveReplayBuffer' class SetCurrentSceneCollection(Baserequests): \"\"\"Change the active scene", "*text* type: String (optional) Text content to be displayed. *text_file*", "self.dataout['sourceKind'] = sourceKind self.dataout['sceneName'] = sceneName self.dataout['sourceSettings'] = sourceSettings self.dataout['setVisible']", "def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentTransition' self.datain['name'] = None self.datain['duration']", "parameters is specified. :Arguments: *sourceName* type: String (optional) Source name.", "the current properties of a Text Freetype 2 source. :Arguments:", "\"\"\"Get the current timestamp of media in milliseconds. Supports ffmpeg", "= 'SetSceneItemTransform' self.dataout['item'] = item self.dataout['x-scale'] = x_scale self.dataout['y-scale'] =", "content to be displayed. *valign* type: String (optional) Text vertical", "self.dataout['css'] = css self.dataout['width'] = width self.dataout['height'] = height self.dataout['fps']", "= None self.dataout['sourceName'] = sourceName def getMonitorType(self): return self.datain['monitorType'] class", "type: double The x-scale factor of the source. *scale.y* type:", "milliseconds. Supports ffmpeg and vlc media sources (as of OBS", "ReorderSceneItems(Baserequests): \"\"\"Changes the order of scene items in the requested", "shutdown=None, render=None): Baserequests.__init__(self) self.name = 'SetBrowserSourceProperties' self.dataout['source'] = source self.dataout['is_local_file']", "filterName, newIndex): Baserequests.__init__(self) self.name = 'ReorderSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName']", "self.dataout['outputName'] = outputName def getOutputInfo(self): return self.datain['outputInfo'] class StartOutput(Baserequests): \"\"\"", "sourceName, timestamp): Baserequests.__init__(self) self.name = 'SetMediaTime' self.dataout['sourceName'] = sourceName self.dataout['timestamp']", "on creation or not. Default `true` :Returns: *itemId* type: int", "`buffering`, `paused`, `stopped`, `ended`, `error`, `unknown` \"\"\" def __init__(self, sourceName):", "self.dataout['newName'] = newName class SetSyncOffset(Baserequests): \"\"\"Set the audio sync offset", "Filter status (enabled or not) *type* type: String Filter type", ":Arguments: *sceneName* type: String Name of the scene to create.", "request) *imageFile* type: String Absolute path to the saved image", "to. \"\"\" def __init__(self, scene_name): Baserequests.__init__(self) self.name = 'SetCurrentScene' self.dataout['scene-name']", "the stream. *settings.use_auth* type: boolean Indicates whether authentication should be", "Style (unknown function). *from_file* type: boolean Read text from the", "= sourceName class GetMediaDuration(Baserequests): \"\"\"Get the length of media in", "self.datain['mediaDuration'] class GetMediaTime(Baserequests): \"\"\"Get the current timestamp of media in", "type: Object Holds data for the font. Ex: `\"font\": {", "\"\"\" def __init__(self, sourceName, timestamp): Baserequests.__init__(self) self.name = 'SetMediaTime' self.dataout['sourceName']", "of a Text Freetype 2 source. :Arguments: *source* type: String", "self.dataout['toScene'] = toScene def getScene(self): return self.datain['scene'] def getItem(self): return", "TriggerHotkeyBySequence(Baserequests): \"\"\"Executes hotkey routine, identified by bound combination of keys.", "getExtents_cx(self): return self.datain['extents_cx'] def getExtents_cy(self): return self.datain['extents_cy'] def getFile(self): return", "Object (optional) Source settings data. *setVisible* type: boolean (optional) Set", "= None self.datain['font'] = None self.datain['gradient'] = None self.datain['gradient_color'] =", "of the second Desktop Audio capture source. *mic_1* type: String", "disk. This is basically the same as triggering the \"Save", "= 'StartOutput' self.dataout['outputName'] = outputName class StopOutput(Baserequests): \"\"\" Note: Controlling", "the filter to remove \"\"\" def __init__(self, sourceName, filterName): Baserequests.__init__(self)", "__init__(self): Baserequests.__init__(self) self.name = 'GetSourcesList' self.datain['sources'] = None def getSources(self):", "Alignment of the bounding box. *bounds.x* type: double Width of", "parameter set to `false`.* \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "Output name :Returns: *outputInfo* type: Output Output info \"\"\" def", "type: double The x position of the source from the", "Replay Buffer\" hotkey is not set in OBS' settings. Setting", "milliseconds of the transition if transition is not fixed. Defaults", "the second Desktop Audio capture source. *mic_1* type: String (optional)", "(optional) The new width of the bounding box. *bounds.y* type:", "def getCurrentTransition(self): return self.datain['current-transition'] def getTransitions(self): return self.datain['transitions'] class GetCurrentTransition(Baserequests):", "source item. Coordinates are relative to the item's parent (the", "of pixels cropped off the right of the source before", "sceneName): Baserequests.__init__(self) self.name = 'RemoveSceneTransitionOverride' self.dataout['sceneName'] = sceneName class GetSceneTransitionOverride(Baserequests):", "self.name = 'GetMute' self.datain['name'] = None self.datain['muted'] = None self.dataout['source']", "The new width of the bounding box. *bounds.y* type: double", "None self.datain['recordTimecode'] = None self.datain['recordingFilename'] = None def getIsRecording(self): return", "= sourceName self.dataout['timestamp'] = timestamp class ScrubMedia(Baserequests): \"\"\"Scrub media using", "a specified source. :Arguments: *source* type: String Source name. *offset*", "Style (unknown function). *gradient* type: boolean (optional) Gradient enabled. *gradient_color*", "The number of pixels cropped off the top of the", "String Display name of the source type *types.*.type* type: String", "The y-scale factor of the source. *crop.top* type: int The", "or so seconds that the media is playing, the total", "Source name. :Returns: *mediaState* type: String The media state of", "return self.datain['rec-timecode'] def getPreviewOnly(self): return self.datain['preview-only'] class StartStopStreaming(Baserequests): \"\"\"Toggle streaming", "= None def getIsRecording(self): return self.datain['isRecording'] def getIsRecordingPaused(self): return self.datain['isRecordingPaused']", "self.datain['outline_color'] def getOutline_size(self): return self.datain['outline_size'] def getOutline_opacity(self): return self.datain['outline_opacity'] def", "self.datain['itemId'] class DuplicateSceneItem(Baserequests): \"\"\"Duplicates a scene item. :Arguments: *fromScene* type:", "`challenge` and `salt` (see \"Authentication\" for more information). :Returns: *authRequired*", "= 'GetSyncOffset' self.datain['name'] = None self.datain['offset'] = None self.dataout['source'] =", "= None self.datain['transitionDuration'] = None self.dataout['sceneName'] = sceneName def getTransitionName(self):", "scene_name): Baserequests.__init__(self) self.name = 'SetCurrentScene' self.dataout['scene-name'] = scene_name class GetCurrentScene(Baserequests):", "specified in the `settings` object or an error will occur", "before scaling. *visible* type: bool (optional) The new visibility of", "def getImg(self): return self.datain['img'] def getImageFile(self): return self.datain['imageFile'] class ListOutputs(Baserequests):", "self.dataout['scene-name'] = scene_name class TransitionToProgram(Baserequests): \"\"\"Transitions the currently previewed scene", "def getIsRecording(self): return self.datain['isRecording'] def getIsRecordingPaused(self): return self.datain['isRecordingPaused'] def getRecordTimecode(self):", "= sceneName self.dataout['transitionName'] = transitionName self.dataout['transitionDuration'] = transitionDuration class RemoveSceneTransitionOverride(Baserequests):", "TakeSourceScreenshot request type) formatted as a comma-separated list string \"\"\"", "*stream.settings.server* type: String (optional) The publish URL. *stream.settings.key* type: String", "None self.datain['bk_opacity'] = None self.datain['chatlog'] = None self.datain['chatlog_lines'] = None", "item in a specified scene. :Arguments: *scene_name* type: String (optional)", "(unknown function). *gradient* type: boolean Gradient enabled. *gradient_color* type: int", "String The monitor type in use. Options: `none`, `monitorOnly`, `monitorAndOutput`.", "getFont(self): return self.datain['font'] def getGradient(self): return self.datain['gradient'] def getGradient_color(self): return", "a specific transition override. :Arguments: *sceneName* type: String Name of", "SetFilenameFormatting(Baserequests): \"\"\"Set the filename formatting string :Arguments: *filename_formatting* type: String", "(0-100). *text* type: String (optional) Text content to be displayed.", "of media in milliseconds.. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name", "scene items in the requested scene. :Arguments: *scene* type: String", "def getSceneItems(self): return self.datain['sceneItems'] class GetSceneItemProperties(Baserequests): \"\"\"Gets the scene specific", "saved. Can be in a format different from `pictureFormat`. Can", "volume. Must be between `0.0` and `20.0` for mul, and", "a T-Bar control in your User Interface), set `release` to", "belongs *filterName* type: String Name of the filter to reconfigure", "may require some probing around). \"\"\" def __init__(self, sourceName, sourceType=None):", "= None self.dataout['sourceName'] = sourceName self.dataout['sourceType'] = sourceType def getSourceName(self):", "bool If the source is muted. *locked* type: bool If", "The publish key. *settings.use_auth* type: boolean (optional) Indicates whether authentication", "Baserequests.__init__(self) self.name = 'TransitionToProgram' self.dataout['with-transition'] = with_transition class EnableStudioMode(Baserequests): \"\"\"Enables", "return self.datain['muted'] def getLocked(self): return self.datain['locked'] def getBounds(self): return self.datain['bounds']", "name. *is_local_file* type: boolean Indicates that a local file is", "the transition (in milliseconds). \"\"\" def __init__(self, duration): Baserequests.__init__(self) self.name", "type: String (optional) Name of the scene to reorder (defaults", "= setVisible def getItemId(self): return self.datain['itemId'] class GetSourcesList(Baserequests): \"\"\"List all", "key modifiers object. False entries can be ommitted *keyModifiers.shift* type:", "getExtents(self): return self.datain['extents'] def getExtents_cx(self): return self.datain['extents_cx'] def getExtents_cy(self): return", "*url* type: String Url. *css* type: String CSS to inject.", "type: double current transition position. This value will be between", "Width. *height* type: int Height. *fps* type: int Framerate. *shutdown*", "pause. \"\"\" def __init__(self, sourceName, playPause): Baserequests.__init__(self) self.name = 'PlayPauseMedia'", "any transition override on a scene. :Arguments: *sceneName* type: String", "*source* type: String Source name. \"\"\" def __init__(self, source): Baserequests.__init__(self)", "self.name = 'SaveStreamSettings' class SendCaptions(Baserequests): \"\"\"Send the provided text as", "= None self.datain['fps'] = None self.datain['shutdown'] = None self.dataout['source'] =", "sources. :Returns: *desktop_1* type: String (optional) Name of the first", "configuration. Please note: these won't be saved to OBS' configuration.", "type. Value is one of the following: \"input\", \"filter\", \"transition\",", "def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'NextMedia' self.dataout['sourceName'] = sourceName", "reorder (defaults to current). *items* type: Array<Scene> Ordered list of", "the active preview scene. Will return an `error` if Studio", "an `error` if streaming is not active. \"\"\" def __init__(self):", "*color* type: int Text color. *extents* type: boolean Extents wrap.", "of the source from the top. *position.alignment* type: int The", "to. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'RemoveSceneTransitionOverride' self.dataout['sceneName']", ":Returns: *streaming* type: boolean Current streaming status. *recording* type: boolean", "and 1.0. *release* type: boolean (optional) Whether or not the", "position of the top of the source item. *bottom* type:", "position, 'false' allows movement. *bounds.type* type: String (optional) The new", "fromScene self.dataout['toScene'] = toScene def getScene(self): return self.datain['scene'] def getItem(self):", "Text color. *extents* type: boolean (optional) Extents wrap. *extents_cx* type:", "*font.style* type: String (optional) Font Style (unknown function). *gradient* type:", "Setting this hotkey is mandatory, even when triggering saves only", "item rotation (in degrees). \"\"\" def __init__(self, item, x_scale, y_scale,", "the transition to use. *transitionDuration* type: int (Optional) Duration in", "The new alignment of the bounding box. (0-2, 4-6, 8-10)", "None self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName def getEnabled(self): return", "type: String Source name. :Returns: *mediaDuration* type: int The total", "source before scaling. *crop.left* type: int (optional) The new amount", "= newIndex class MoveSourceFilter(Baserequests): \"\"\"Move a filter in the chain", "type: String (optional) The publish URL. *settings.key* type: String (optional)", "type: String (optional) Name of the scene to get the", "boolean Always false. Retrocompatibility with OBSRemote. \"\"\" def __init__(self): Baserequests.__init__(self)", "return self.datain['timestamp'] class SetMediaTime(Baserequests): \"\"\"Set the timestamp of a media", "is already active. :Arguments: *stream* type: Object (optional) Special stream", "return self.datain['name'] def getSources(self): return self.datain['sources'] class SetPreviewScene(Baserequests): \"\"\"Set the", "self.name = 'StopMedia' self.dataout['sourceName'] = sourceName class NextMedia(Baserequests): \"\"\"Skip to", "(optional) The new x position of the source. *position.y* type:", "The new height of the bounding box. \"\"\" def __init__(self,", "is not set to `true`. \"\"\" def __init__(self, stream=None): Baserequests.__init__(self)", "profiles. :Returns: *profiles* type: Array<Object> List of available profiles. *profiles.*.profile_name*", "log. *chatlog_lines* type: int Chat log lines. *color* type: int", "point on the source that the item is manipulated from.", "None self.datain['settings'] = None def getType(self): return self.datain['type'] def getSettings(self):", "be choosen by the client *data* type: Object User-defined data", "int Font text styling flag. `Bold=1, Italic=2, Bold Italic=3, Underline=5,", "Source name. *timestamp* type: int Milliseconds to set the timestamp", "volume, useDecibel=None): Baserequests.__init__(self) self.name = 'SetVolume' self.dataout['source'] = source self.dataout['volume']", "source. :Arguments: *source* type: String Source name. *offset* type: int", "of the source before scaling. *crop.left* type: int (optional) The", "class SetSceneTransitionOverride(Baserequests): \"\"\"Set a scene to use a specific transition", "the recording file (only present if currently recording). \"\"\" def", "the following: \"input\", \"filter\", \"transition\" or \"other\" *types.*.defaultSettings* type: Object", "Object Source settings (varies between source types, may require some", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListProfiles' self.datain['profiles'] = None", "return self.datain['font'] def getFrom_file(self): return self.datain['from_file'] def getLog_mode(self): return self.datain['log_mode']", "sceneName, sourceName, setVisible): Baserequests.__init__(self) self.name = 'AddSceneItem' self.datain['itemId'] = None", "the right of the source before scaling. *crop.bottom* type: int", "the vertical scaling factor) *parentGroupName* type: String (optional) Name of", "type: String file path. *url* type: String Url. *css* type:", "\"\"\"Set the current properties of a Text Freetype 2 source.", "settings, save): Baserequests.__init__(self) self.name = 'SetStreamSettings' self.dataout['type'] = type self.dataout['settings']", "new alignment of the bounding box. (0-2, 4-6, 8-10) *bounds.x*", "String (optional) NAme of the third Mic/Aux input source. \"\"\"", "to disk. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'SaveStreamSettings' class", "new height of the bounding box. \"\"\" def __init__(self, item,", "(like the TakeSourceScreenshot request type) formatted as a comma-separated list", "The current state of media for that source. States: `none`,", "not enabled. :Arguments: *with_transition* type: Object (optional) Change the active", "None def getStats(self): return self.datain['stats'] class BroadcastCustomMessage(Baserequests): \"\"\"Broadcast custom message", "type: boolean Current streaming status. *recording* type: boolean Current recording", "Name of the source from which the specified filter is", "Item name. *x_scale* type: double Width scale factor. *y_scale* type:", "def __init__(self, rec_folder): Baserequests.__init__(self) self.name = 'SetRecordingFolder' self.dataout['rec-folder'] = rec_folder", "the streaming server. Ignored if `use_auth` is not set to", "item self.dataout['scene-name'] = scene_name def getName(self): return self.datain['name'] def getItemId(self):", "(Optional) Size and position of the projector window (only if", "= 'PreviousMedia' self.dataout['sourceName'] = sourceName class GetMediaDuration(Baserequests): \"\"\"Get the length", "the request) \"\"\" def __init__(self, sourceName=None, embedPictureFormat=None, saveToFilePath=None, fileFormat=None, compressionQuality=None,", "newIndex): Baserequests.__init__(self) self.name = 'ReorderSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName'] =", "*colorSpace* type: String Color space for YUV *colorRange* type: String", ":Arguments: *type* type: String The type of streaming service configuration,", "the bounding box. (0-2, 4-6, 8-10) *bounds.x* type: double (optional)", "= None self.datain['stream-timecode'] = None self.datain['rec-timecode'] = None self.datain['preview-only'] =", "\"\"\"Get the audio sync offset of a specified source. :Arguments:", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetReplayBufferStatus' self.datain['isReplayBufferActive'] = None", "type: Object (optional) Adds the given object parameters as encoded", "*outputs* type: Array<Output> Outputs list \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "offset (in nanoseconds). \"\"\" def __init__(self, source, offset): Baserequests.__init__(self) self.name", "AddSceneItem(Baserequests): \"\"\"Creates a scene item in a scene. In other", "to `true`. *stream.settings.password* type: String (optional) If authentication is enabled,", "*scenes* type: Array<Scene> Ordered list of the current profile's scenes", "or negative) to offset the current media position. \"\"\" def", "__init__(self, profile_name): Baserequests.__init__(self) self.name = 'SetCurrentProfile' self.dataout['profile-name'] = profile_name class", "\"\"\"Toggle recording on or off (depending on the current recording", "return self.datain['chatlog'] def getChatlog_lines(self): return self.datain['chatlog_lines'] def getColor(self): return self.datain['color']", "object) *position.x* type: double (optional) The new x position of", "Transition name *transitionSettings* type: Object Transition settings (they can be", "def getOutputHeight(self): return self.datain['outputHeight'] def getScaleType(self): return self.datain['scaleType'] def getFps(self):", "*type* type: String Filter type *name* type: String Filter name", "(unknown function). *from_file* type: boolean (optional) Read text from the", "__init__(self): Baserequests.__init__(self) self.name = 'DisableStudioMode' class ToggleStudioMode(Baserequests): \"\"\"Toggles Studio Mode", "*outline* type: boolean Outline. *outline_color* type: int Outline color. *outline_size*", "the current scene's name and source items. :Returns: *name* type:", ":Returns: *outputInfo* type: Output Output info \"\"\" def __init__(self, outputName):", "streaming. Will return an `error` if streaming is already active.", "None self.datain['width'] = None self.datain['height'] = None self.datain['fps'] = None", "`true`. \"\"\" def __init__(self, stream=None): Baserequests.__init__(self) self.name = 'StartStreaming' self.dataout['stream']", "properties for a Browser Source. :Arguments: *source* type: String Name", "def __init__(self, sourceName, sourceSettings, sourceType=None): Baserequests.__init__(self) self.name = 'SetSourceSettings' self.datain['sourceName']", "def getVideoFormat(self): return self.datain['videoFormat'] def getColorSpace(self): return self.datain['colorSpace'] def getColorRange(self):", "class StartRecording(Baserequests): \"\"\"Start recording. Will return an `error` if recording", "position, release=None): Baserequests.__init__(self) self.name = 'SetTBarPosition' self.dataout['position'] = position self.dataout['release']", "*y* type: double Y coordinate. \"\"\" def __init__(self, item, x,", "class GetPreviewScene(Baserequests): \"\"\"Get the name of the currently previewed scene", "type of streaming service configuration. Possible values: 'rtmp_custom' or 'rtmp_common'.", "Array of sources *mediaSources.*.sourceName* type: String Unique source name *mediaSources.*.sourceKind*", "due to uniqueness per scene *items.*.id* type: int (optional) Id", "the crop coordinates of the specified source item. :Arguments: *scene_name*", "Scene Item name. *render* type: boolean true = shown ;", "Gradient color. *gradient_dir* type: float (optional) Gradient direction. *gradient_opacity* type:", "item self.dataout['scene-name'] = scene_name self.dataout['position'] = position self.dataout['rotation'] = rotation", "Baserequests.__init__(self) self.name = 'DeleteSceneItem' self.dataout['item'] = item self.dataout['scene'] = scene", "(in nanoseconds). \"\"\" def __init__(self, source, offset): Baserequests.__init__(self) self.name =", "type: String Name of the currently active transition. *transitions* type:", "= None self.datain['recordingFilename'] = None def getIsRecording(self): return self.datain['isRecording'] def", "delete (required) *item.name* type: String Scene Item name (prefer `id`,", "will interpret dB values under -100.0 as Inf. Note: The", "all transitions available in the frontend's dropdown menu. :Returns: *current_transition*", "info as provided in OBS' stats window) :Returns: *stats* type:", "getType(self): return self.datain['type'] def getSettings(self): return self.datain['settings'] class SaveStreamSettings(Baserequests): \"\"\"Save", "right of the source item. \"\"\" def __init__(self, item, top,", "based on file extension. *compressionQuality* type: int (optional) Compression ratio", "Read text from the specified file. *log_mode* type: boolean (optional)", "to inject. *width* type: int Width. *height* type: int Height.", "String Type of the specified source *sourceSettings* type: Object Updated", "Adds the given object parameters as encoded query string parameters", "Object New settings. These will be merged to the current", "String Name of the current overriding transition. Empty string if", "of the scene to create the item in. Defaults to", "The name of the active preview scene. *sources* type: Array<SceneItem>", "\"\"\" def __init__(self, duration): Baserequests.__init__(self) self.name = 'SetTransitionDuration' self.dataout['duration'] =", "def __init__(self): Baserequests.__init__(self) self.name = 'StopReplayBuffer' class SaveReplayBuffer(Baserequests): \"\"\"Flush and", "self.datain['rec-folder'] class GetReplayBufferStatus(Baserequests): \"\"\"Get the status of the OBS replay", "specific properties of the specified source item. Coordinates are relative", "\"\"\" def __init__(self, item, scene=None): Baserequests.__init__(self) self.name = 'DeleteSceneItem' self.dataout['item']", "of settings incompatible with the actual source's type. *sourceSettings* type:", "or play the source. `false` for play, `true` for pause.", "sourceName def getTimestamp(self): return self.datain['timestamp'] class SetMediaTime(Baserequests): \"\"\"Set the timestamp", "self.dataout['timeOffset'] = timeOffset class GetMediaState(Baserequests): \"\"\"Get the current playing state", "*sourceType* type: String (optional) Type of the specified source. Useful", "self.datain['sourceWidth'] def getSourceHeight(self): return self.datain['sourceHeight'] def getWidth(self): return self.datain['width'] def", "*crop.right* type: int (optional) The new amount of pixels cropped", "class StopOutput(Baserequests): \"\"\" Note: Controlling outputs is an experimental feature", "self.name = 'SetSceneItemPosition' self.dataout['item'] = item self.dataout['x'] = x self.dataout['y']", "interaction with this sources of this type is possible *types.*.caps.isComposite*", "off the top of the source before scaling. *crop.right* type:", "If authentication is enabled, the username for the streaming server.", "'SetSyncOffset' self.dataout['source'] = source self.dataout['offset'] = offset class GetSyncOffset(Baserequests): \"\"\"Get", "a filter in the chain (absolute index positioning) :Arguments: *sourceName*", "the active transition. *with_transition.name* type: String Name of the transition.", "'GetStreamingStatus' self.datain['streaming'] = None self.datain['recording'] = None self.datain['stream-timecode'] = None", "of OBS v25.0.8) :Arguments: *sourceName* type: String Source name. :Returns:", "path. *url* type: String Url. *css* type: String CSS to", "SetAudioMonitorType(Baserequests): \"\"\"Set the audio monitoring type of the specified source.", "pixels cropped off the right of the source before scaling.", "might trigger multiple hotkey routines depending on user settings :Arguments:", "__init__(self): Baserequests.__init__(self) self.name = 'GetCurrentScene' self.datain['name'] = None self.datain['sources'] =", "source to. *sourceSettings* type: Object (optional) Source settings data. *setVisible*", "Duration in milliseconds of the transition if transition is not", "self.datain['current-transition'] = None self.datain['transitions'] = None def getCurrentTransition(self): return self.datain['current-transition']", "client if authentication is required. If so, returns authentication parameters", "class GetStreamingStatus(Baserequests): \"\"\"Get current streaming and recording status. :Returns: *streaming*", "Name of the scene to reorder (defaults to current). *items*", "the saved image file (if `saveToFilePath` was specified in the", "to reconfigure *filterSettings* type: Object New settings. These will be", "Outline. *outline_color* type: int (optional) Outline color. *outline_size* type: int", "a recording is in progress, the change won't be applied", "def getPreviewOnly(self): return self.datain['preview-only'] class StartStopStreaming(Baserequests): \"\"\"Toggle streaming on or", "switch to. *transitionName* type: String Name of the transition to", "self.name = 'SetSceneItemTransform' self.dataout['item'] = item self.dataout['x-scale'] = x_scale self.dataout['y-scale']", "to processing/network delays, this request is not perfect. The processing", "def __init__(self, scene_name): Baserequests.__init__(self) self.name = 'SetCurrentScene' self.dataout['scene-name'] = scene_name", "self.datain['shutdown'] class SetBrowserSourceProperties(Baserequests): \"\"\"Set current properties for a Browser Source.", "int Height. *fps* type: int Framerate. *shutdown* type: boolean Indicates", "self.name = 'GetVolume' self.datain['name'] = None self.datain['volume'] = None self.datain['muted']", "*outline* type: boolean (optional) Outline. *text* type: String (optional) Text", "int (optional) Extents cy. *file* type: String (optional) File path", "active transition. *with_transition.name* type: String Name of the transition. *with_transition.duration*", "int Output width *outputHeight* type: int Output height *scaleType* type:", "boolean (optional) Interperet `volume` data as decibels instead of amplitude/mul.", "transitionName, transitionSettings): Baserequests.__init__(self) self.name = 'SetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName']", "`monitorAndOutput`. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetAudioMonitorType' self.datain['monitorType']", "def getRotation(self): return self.datain['rotation'] def getScale(self): return self.datain['scale'] def getCrop(self):", "\"\"\"Toggle streaming on or off (depending on the current stream", "Italic=3, Underline=5, Strikeout=8` *font.size* type: int Font text size. *font.style*", "moving it). *YOU MUST CALL THIS if you called `SetTBarPosition`", "a scene item. Sufficiently unique if no scene items share", "self.datain['available-requests'] = None self.datain['supported-image-export-formats'] = None def getVersion(self): return self.datain['version']", "disk. \"\"\" def __init__(self, type, settings, save): Baserequests.__init__(self) self.name =", "self.dataout['item'] = item self.dataout['top'] = top self.dataout['bottom'] = bottom self.dataout['left']", "to guess based on file extension. *compressionQuality* type: int (optional)", "name. :Returns: *mediaDuration* type: int The total length of media", "streaming and recording status. :Returns: *streaming* type: boolean Current streaming", "__init__(self): Baserequests.__init__(self) self.name = 'StopStreaming' class SetStreamSettings(Baserequests): \"\"\"Sets one or", "switching scenes. Defaults to the active transition. *with_transition.name* type: String", "None self.datain['challenge'] = None self.datain['salt'] = None def getAuthRequired(self): return", "to the streaming server. *stream.settings.username* type: String (optional) If authentication", "int Text color. *extents* type: boolean Extents wrap. *extents_cx* type:", "getBounds(self): return self.datain['bounds'] def getSourceWidth(self): return self.datain['sourceWidth'] def getSourceHeight(self): return", "self.name = 'SetSourceFilterSettings' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterSettings']", "\"\"\"Gets the scene specific properties of the specified source item.", "String (optional) The new bounds type of the source. Can", "object). *item.name* type: String (optional) Scene Item name (if the", "alignment. *scale.x* type: double The x-scale factor of the source.", "*sourceName* type: String Source name. *timestamp* type: int Milliseconds to", "__init__(self, sceneName, transitionName, transitionDuration): Baserequests.__init__(self) self.name = 'SetSceneTransitionOverride' self.dataout['sceneName'] =", "the `item` field is an object) *item.id* type: int (optional)", "# THIS FILE WAS GENERATED BY generate_classes.py - DO NOT", "of the specified source item. Coordinates are relative to the", "self.name = 'GetCurrentScene' self.datain['name'] = None self.datain['sources'] = None def", "type should not be fully duplicated *types.*.caps.doNotSelfMonitor* type: Boolean True", "type: String (optional) Font face. *font.flags* type: int (optional) Font", "match the given stream type, all settings must be specified", "SetStreamSettings(Baserequests): \"\"\"Sets one or more attributes of the current streaming", "PERCENTAGE. :Arguments: *source* type: String Source name. *volume* type: double", "required. If so, returns authentication parameters `challenge` and `salt` (see", "Gradient color. *gradient_dir* type: float Gradient direction. *gradient_opacity* type: int", "String (optional) Time elapsed since recording started (only present if", "None def getOutputs(self): return self.datain['outputs'] class GetOutputInfo(Baserequests): \"\"\"Get information about", "self.dataout['newIndex'] = newIndex class MoveSourceFilter(Baserequests): \"\"\"Move a filter in the", "Gradient top color. *color2* type: int Gradient bottom color. *custom_width*", "Will return an `error` if recording is not active. \"\"\"", "type: String Filename formatting string to set. \"\"\" def __init__(self,", "= None self.dataout['sceneName'] = sceneName self.dataout['sourceName'] = sourceName self.dataout['setVisible'] =", "self.datain['outline_color'] = None self.datain['outline_size'] = None self.datain['outline_opacity'] = None self.datain['text']", "amount of pixels cropped off the top of the source", "Inf. Note: The OBS volume sliders only reach a maximum", "sourceType=None): Baserequests.__init__(self) self.name = 'GetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType'] =", "scene collection. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentSceneCollection' self.datain['sc-name']", "to. Defaults to the currently active scene. *source* type: String", "def getOffset(self): return self.datain['offset'] class GetSourceSettings(Baserequests): \"\"\"Get settings of the", "merged to the current filter settings. \"\"\" def __init__(self, sourceName,", "of the following: \"input\", \"filter\", \"transition\", \"scene\" or \"unknown\" \"\"\"", "scene class SetSceneTransitionOverride(Baserequests): \"\"\"Set a scene to use a specific", "*sourceName* type: String Source name. :Returns: *audioActive* type: boolean Audio", "*source* type: String Source name. *offset* type: int The desired", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'DisableStudioMode' class ToggleStudioMode(Baserequests): \"\"\"Toggles", "type: Array<Object> Array of sources *mediaSources.*.sourceName* type: String Unique source", "type: String Source name. *newName* type: String New source name.", "self.datain['color1'] def getColor2(self): return self.datain['color2'] def getCustom_width(self): return self.datain['custom_width'] def", "gradient=None, gradient_color=None, gradient_dir=None, gradient_opacity=None, outline=None, outline_color=None, outline_size=None, outline_opacity=None, text=None, valign=None,", "Browser Source. :Arguments: *source* type: String Source name. :Returns: *source*", "= scene class AddSceneItem(Baserequests): \"\"\"Creates a scene item in a", "type: int (optional) Extents cx. *extents_cy* type: int (optional) Extents", "provided in OBS' stats window) :Returns: *stats* type: OBSStats [OBS", "frontend's dropdown menu. :Returns: *current_transition* type: String Name of the", "*x* type: double X coordinate. *y* type: double Y coordinate.", "Mode is not enabled. :Arguments: *scene_name* type: String The name", "self.datain['isReplayBufferActive'] = None def getIsReplayBufferActive(self): return self.datain['isReplayBufferActive'] class StartStopReplayBuffer(Baserequests): \"\"\"Toggle", "= 'SetSourceName' self.dataout['sourceName'] = sourceName self.dataout['newName'] = newName class SetSyncOffset(Baserequests):", "GetMediaDuration(Baserequests): \"\"\"Get the length of media in milliseconds. Supports ffmpeg", "scene_name class SetSceneItemTransform(Baserequests): \"\"\"Set the transform of the specified source", "type: String Scaling method used if output size differs from", "the recording is paused or not. *recordTimecode* type: String (optional)", "active scene is used. *embedPictureFormat* type: String (optional) Format of", "source internal type (a.k.a `ffmpeg_source` or `vlc_source`) *mediaSources.*.mediaState* type: String", ":Arguments: *source* type: String Source name. *color1* type: int (optional)", "Baserequests.__init__(self) self.name = 'StartStopStreaming' class StartStreaming(Baserequests): \"\"\"Start streaming. Will return", "'SetSceneItemPosition' self.dataout['item'] = item self.dataout['x'] = x self.dataout['y'] = y", "*item* type: Object New item info *item.id* type: int New", "Chat log. *outline* type: boolean (optional) Outline. *text* type: String", "decibels of attenuation instead of amplitude/mul. :Returns: *name* type: String", "type self.dataout['monitor'] = monitor self.dataout['geometry'] = geometry self.dataout['name'] = name", "*outputName* type: String Output name \"\"\" def __init__(self, outputName): Baserequests.__init__(self)", "getName(self): return self.datain['name'] def getVolume(self): return self.datain['volume'] def getMuted(self): return", "Persist the settings to disk. \"\"\" def __init__(self, type, settings,", "self.name = 'GetPreviewScene' self.datain['name'] = None self.datain['sources'] = None def", "*preview_only* type: boolean Always false. Retrocompatibility with OBSRemote. \"\"\" def", "None self.dataout['sourceName'] = sourceName self.dataout['sourceSettings'] = sourceSettings self.dataout['sourceType'] = sourceType", "Source name. *sourceKind* type: String Source kind, Eg. `vlc_source`. *sceneName*", "hotkey (e.g. \"ReplayBuffer.Save\") \"\"\" def __init__(self, hotkeyName): Baserequests.__init__(self) self.name =", "sliders only reach a maximum of 1.0mul/0.0dB, however OBS actually", "be applied immediately and will be effective on the next", "the list of scene items from. Defaults to the current", "Array of source types *types.*.typeId* type: String Non-unique internal source", "def getColor2(self): return self.datain['color2'] def getCustom_width(self): return self.datain['custom_width'] def getDrop_shadow(self):", "single key combination might trigger multiple hotkey routines depending on", "triggering saves only through obs-websocket. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "*transitionName* type: String Name of the transition to use. *transitionDuration*", "hotkey is mandatory, even when triggering saves only through obs-websocket.", "is set. *transitionDuration* type: int Transition duration. `-1` if no", "started (only present if currently recording). *recordingFilename* type: String (optional)", "Current recording status. *isRecordingPaused* type: boolean Whether the recording is", "formatting string :Arguments: *filename_formatting* type: String Filename formatting string to", "(enabled or not) *filters.*.type* type: String Filter type *filters.*.name* type:", "self.dataout['sourceName'] = sourceName self.dataout['playPause'] = playPause class RestartMedia(Baserequests): \"\"\"Restart a", "def __init__(self): Baserequests.__init__(self) self.name = 'DisableStudioMode' class ToggleStudioMode(Baserequests): \"\"\"Toggles Studio", "'false' allows movement. *bounds.type* type: String (optional) The new bounds", "Baserequests.__init__(self) self.name = 'GetSourceTypesList' self.datain['types'] = None def getTypes(self): return", "def getSalt(self): return self.datain['salt'] class Authenticate(Baserequests): \"\"\"Attempt to authenticate the", "media source (as of OBS v25.0.8) :Arguments: *sourceName* type: String", "audio sync offset (in nanoseconds). \"\"\" def __init__(self, source): Baserequests.__init__(self)", "playing, the total duration can be off by upwards of", "GetMediaTime(Baserequests): \"\"\"Get the current timestamp of media in milliseconds. Supports", "item in degrees around the point of alignment. *scale.x* type:", "name. *render* type: boolean true = shown ; false =", "source. Useful for type-checking to avoid settings a set of", "type: int Pixel position of the bottom of the source", "= item self.dataout['top'] = top self.dataout['bottom'] = bottom self.dataout['left'] =", "already active. :Arguments: *stream* type: Object (optional) Special stream configuration.", "None self.dataout['outputName'] = outputName def getOutputInfo(self): return self.datain['outputInfo'] class StartOutput(Baserequests):", "String The name of the active preview scene. *sources* type:", "*outline_size* type: int (optional) Outline size. *outline_opacity* type: int (optional)", "self.datain['drop_shadow'] = None self.datain['font'] = None self.datain['from_file'] = None self.datain['log_mode']", "String Name of the scene item's source *sceneItems.*.sourceType* type: String", "specific scene item. Unique on a scene by scene basis.", "duration. `-1` if no override is set. \"\"\" def __init__(self,", "(optional) Transition duration (in milliseconds). \"\"\" def __init__(self, with_transition=None): Baserequests.__init__(self)", "sourceSettings self.dataout['sourceType'] = sourceType def getSourceName(self): return self.datain['sourceName'] def getSourceType(self):", "= item self.dataout['x'] = x self.dataout['y'] = y self.dataout['scene-name'] =", "= 'GetMediaTime' self.datain['timestamp'] = None self.dataout['sourceName'] = sourceName def getTimestamp(self):", "Value is one of the following: \"input\", \"filter\", \"transition\", \"scene\"", "(optional) The publish key of the stream. *stream.settings.use_auth* type: boolean", "DO NOT EDIT # # (Generated on 2020-12-20 18:26:33.661372) #", "requested (or current) scene *sceneItems* type: Array<Object> Array of scene", "and media source) :Returns: *mediaSources* type: Array<Object> Array of sources", "boolean Outline. *outline_color* type: int Outline color. *outline_size* type: int", "\"\"\"Create a source and add it as a sceneitem to", "None self.dataout['source'] = source def getName(self): return self.datain['name'] def getOffset(self):", "or `vlc_source`) *mediaSources.*.mediaState* type: String The current state of media", "\"\"\" def __init__(self, outputName): Baserequests.__init__(self) self.name = 'GetOutputInfo' self.datain['outputInfo'] =", "def __init__(self): Baserequests.__init__(self) self.name = 'GetStudioModeStatus' self.datain['studio-mode'] = None def", "self.dataout['sceneName'] = sceneName def getTransitionName(self): return self.datain['transitionName'] def getTransitionDuration(self): return", "the current streaming server settings. Any options not passed will", "Numerical ID of the created scene item \"\"\" def __init__(self,", "the source scene (required) *item.name* type: String Scene Item name", "scene to switch to. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name", "vertical self.dataout['render'] = render class GetTextFreetype2Properties(Baserequests): \"\"\"Get the current properties", ":Arguments: *sourceName* type: String Name of the source on which", "Baserequests.__init__(self) self.name = 'SetSourceName' self.dataout['sourceName'] = sourceName self.dataout['newName'] = newName", "to be choosen by the client *data* type: Object User-defined", "that use image export (like the TakeSourceScreenshot request type) formatted", "name. *itemId* type: int Scene Item ID. *position.x* type: double", "return an `error` if streaming is not active. \"\"\" def", ":Returns: *version* type: double OBSRemote compatible API version. Fixed to", "Vertical text enabled. *render* type: boolean (optional) Visibility of the", "current position, 'false' allows movement. *bounds.type* type: String (optional) The", "Baserequests.__init__(self) self.name = 'StartStopRecording' class StartRecording(Baserequests): \"\"\"Start recording. Will return", "self.name = 'StopStreaming' class SetStreamSettings(Baserequests): \"\"\"Sets one or more attributes", "None self.datain['url'] = None self.datain['css'] = None self.datain['width'] = None", "= None self.datain['shutdown'] = None self.dataout['source'] = source def getSource(self):", "of the currently active transition. *transitions* type: Array<Object> List of", "a specified source. :Arguments: *source* type: String Source name. *mute*", "self.name = 'SendCaptions' self.dataout['text'] = text class GetStudioModeStatus(Baserequests): \"\"\"Indicates if", "paused or not. *recordTimecode* type: String (optional) Time elapsed since", "required. Returns the full settings of the stream (the same", "factor) *parentGroupName* type: String (optional) Name of the item's parent", ":Arguments: *source* type: String Source name. *mute* type: boolean Desired", "or `image_source` *sceneItems.*.sourceName* type: String Name of the scene item's", "new y scale of the item. *crop.top* type: int (optional)", "return self.datain['outline'] def getOutline_color(self): return self.datain['outline_color'] def getOutline_size(self): return self.datain['outline_size']", "clockwise rotation of the item in degrees around the point", "(depending on the current recording state). \"\"\" def __init__(self): Baserequests.__init__(self)", "= None self.datain['outputHeight'] = None self.datain['scaleType'] = None self.datain['fps'] =", "(as of OBS v25.0.8) :Arguments: *sourceName* type: String Source name.", "of the scene the source item belongs to. Defaults to", "type: String Scene Item name (prefer `id`, including both is", "type: int (optional) Chat log lines. *color* type: int (optional)", "*duration* type: int Desired duration of the transition (in milliseconds).", "int Alignment of the bounding box. *bounds.x* type: double Width", "(enabled or not) *type* type: String Filter type *name* type:", "depending on user settings :Arguments: *keyId* type: String Main key", ":Returns: *filters* type: Array<Object> List of filters for the specified", "type: String Source name. *offset* type: int The desired audio", "specified source. Useful for type-checking to avoid settings a set", "values: 'rtmp_custom' or 'rtmp_common'. *settings* type: Object Stream settings object.", "by the vertical scaling factor) *parentGroupName* type: String (optional) Name", "'ReorderSceneItems' self.dataout['items'] = items self.dataout['scene'] = scene class SetSceneTransitionOverride(Baserequests): \"\"\"Set", "of the source. 'true' keeps it in its current position,", "self.dataout['filterName'] = filterName class ReorderSourceFilter(Baserequests): \"\"\"Move a filter in the", "item. *crop.top* type: int (optional) The new amount of pixels", "when connecting to the streaming server. *settings.username* type: String The", "milliseconds). \"\"\" def __init__(self, with_transition=None): Baserequests.__init__(self) self.name = 'TransitionToProgram' self.dataout['with-transition']", "length of media in milliseconds.. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self)", "sourceName, playPause): Baserequests.__init__(self) self.name = 'PlayPauseMedia' self.dataout['sourceName'] = sourceName self.dataout['playPause']", "timeOffset class GetMediaState(Baserequests): \"\"\"Get the current playing state of a", "getSalt(self): return self.datain['salt'] class Authenticate(Baserequests): \"\"\"Attempt to authenticate the client", "OBS' stats window) :Returns: *stats* type: OBSStats [OBS stats](#obsstats) \"\"\"", "= None self.datain['outline_color'] = None self.datain['outline_size'] = None self.datain['outline_opacity'] =", "self.dataout['source'] = source self.dataout['is_local_file'] = is_local_file self.dataout['local_file'] = local_file self.dataout['url']", "= 'SetStreamSettings' self.dataout['type'] = type self.dataout['settings'] = settings self.dataout['save'] =", "*compressionQuality* type: int (optional) Compression ratio between -1 and 100", "name. If not provided, the currently active scene is used.", "-1 or omitted, opens a window. *geometry* type: String (Optional)", "(optional) Framerate. *shutdown* type: boolean (optional) Indicates whether the source", "return self.datain['width'] def getHeight(self): return self.datain['height'] def getFps(self): return self.datain['fps']", "type: Object The actual settings of the stream. *settings.server* type:", "there is no current override and this value is not", "Object (optional) Special stream configuration. Please note: these won't be", "def getChatlog(self): return self.datain['chatlog'] def getChatlog_lines(self): return self.datain['chatlog_lines'] def getColor(self):", "\"\"\" def __init__(self, hotkeyName): Baserequests.__init__(self) self.name = 'TriggerHotkeyByName' self.dataout['hotkeyName'] =", "settings \"\"\" def __init__(self, sourceName, filterName, filterType, filterSettings): Baserequests.__init__(self) self.name", "*position.y* type: double The y position of the source from", "def getMuted(self): return self.datain['muted'] class SetMute(Baserequests): \"\"\"Sets the mute status", "= sourceName self.dataout['filterName'] = filterName class ReorderSourceFilter(Baserequests): \"\"\"Move a filter", "source, useDecibel=None): Baserequests.__init__(self) self.name = 'GetVolume' self.datain['name'] = None self.datain['volume']", "`OBS_KEY_A` for key \"A\"). Available identifiers [here](https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h) *keyModifiers* type: Object", "scenes are also sources, you can also provide a scene", "should be shutdown when not visible. \"\"\" def __init__(self, source):", "None self.datain['imageFile'] = None self.dataout['sourceName'] = sourceName self.dataout['embedPictureFormat'] = embedPictureFormat", "type: int The total length of media in milliseconds.. \"\"\"", "source. *crop.top* type: int The number of pixels cropped off", "status. \"\"\" def __init__(self, source, mute): Baserequests.__init__(self) self.name = 'SetMute'", "sources available in the running OBS instance :Returns: *sources* type:", "(optional) Gradient bottom color. *custom_width* type: int (optional) Custom width", "def getTypes(self): return self.datain['types'] class GetVolume(Baserequests): \"\"\"Get the volume of", "self.dataout['monitor'] = monitor self.dataout['geometry'] = geometry self.dataout['name'] = name class", "= 'SetFilenameFormatting' self.dataout['filename-formatting'] = filename_formatting class GetFilenameFormatting(Baserequests): \"\"\"Get the filename", "if streaming is already active. :Arguments: *stream* type: Object (optional)", "= width self.dataout['height'] = height def getSourceName(self): return self.datain['sourceName'] def", "type: String The publish key of the stream. *settings.use_auth* type:", "Object Scene Item name (if this field is a string)", "if interaction with this sources of this type is possible", "source types, may require some probing around). :Returns: *sourceName* type:", "source. :Arguments: *sourceName* type: String Source name. :Returns: *monitorType* type:", "item name \"\"\" def __init__(self, item, fromScene=None, toScene=None): Baserequests.__init__(self) self.name", "return self.datain['streaming'] def getRecording(self): return self.datain['recording'] def getStreamTimecode(self): return self.datain['stream-timecode']", "scene (required) *item.name* type: String Scene Item name (prefer `id`,", "2=Right, and 4=Top or 8=Bottom, or omit to center on", "under -100.0 as Inf. Note: The OBS volume sliders only", "of the source before scaling. *crop.right* type: int The number", "(optional) The new y position of the source. *position.alignment* type:", "Baserequests.__init__(self) self.name = 'GetCurrentScene' self.datain['name'] = None self.datain['sources'] = None", "*sourceName* type: String Source name *filterName* type: String Source filter", "self.dataout['realm'] = realm self.dataout['data'] = data class GetVideoInfo(Baserequests): \"\"\"Get basic", "*items.*.name* type: String (optional) Name of a scene item. Sufficiently", "bounding box. *bounds.y* type: double Height of the bounding box.", "name \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListProfiles' self.datain['profiles'] =", "messages \"\"\" def __init__(self, enable): Baserequests.__init__(self) self.name = 'SetHeartbeat' self.dataout['enable']", "'GetAudioActive' self.datain['audioActive'] = None self.dataout['sourceName'] = sourceName def getAudioActive(self): return", "item. *left* type: int Pixel position of the left of", "type: String Text content to be displayed. *valign* type: String", "(if this item is a group) \"\"\" def __init__(self, item,", "scene scene. :Arguments: *sceneName* type: String Name of the scene", "the source. *position.alignment* type: int (optional) The new alignment of", "the specified source *sourceSettings* type: Object Updated source settings \"\"\"", "= 'SetMediaTime' self.dataout['sourceName'] = sourceName self.dataout['timestamp'] = timestamp class ScrubMedia(Baserequests):", "'SetSceneItemCrop' self.dataout['item'] = item self.dataout['top'] = top self.dataout['bottom'] = bottom", "(optional) Vertical text enabled. *render* type: boolean (optional) Visibility of", "in OBS' stats window) :Returns: *stats* type: OBSStats [OBS stats](#obsstats)", "scene item. Unique on a scene by scene basis. *items.*.name*", "rotation, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemTransform' self.dataout['item'] = item self.dataout['x-scale']", "double X coordinate. *y* type: double Y coordinate. \"\"\" def", "Source name *sourceType* type: String Type of the specified source", ":Returns: *studio_mode* type: boolean Indicates if Studio Mode is enabled.", "preview. \"\"\" def __init__(self, scene_name): Baserequests.__init__(self) self.name = 'SetPreviewScene' self.dataout['scene-name']", "scaling factor) *height* type: double Scene item height (base source", "new x scale of the item. *scale.y* type: double (optional)", "= None def getTransitionDuration(self): return self.datain['transition-duration'] class GetTransitionPosition(Baserequests): \"\"\"Get the", "a feedback loop if it's audio is monitored and shouldn't", "type: String Name of the filter to reconfigure *filterSettings* type:", "create the scene item in *sourceName* type: String Name of", "def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'GetSceneTransitionOverride' self.datain['transitionName'] = None", "bottom of the source before scaling. *crop.left* type: int The", "return self.datain['position'] class GetTransitionSettings(Baserequests): \"\"\"Get the current settings of a", "specified source item. Coordinates are relative to the item's parent", "the top of the source before scaling. *crop.bottom* type: int", "source. *mic_3* type: String (optional) NAme of the third Mic/Aux", "transition. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionList' self.datain['current-transition'] =", "for other projector types). \"\"\" def __init__(self, type, monitor, geometry,", "the source is muted. \"\"\" def __init__(self, source, useDecibel=None): Baserequests.__init__(self)", "= None self.datain['file'] = None self.datain['read_from_file'] = None self.datain['font'] =", "using [Qt's geometry encoding](https://doc.qt.io/qt-5/qwidget.html#saveGeometry). Corresponds to OBS's saved projectors. *name*", "None self.datain['crop'] = None self.datain['visible'] = None self.datain['muted'] = None", "of sources *mediaSources.*.sourceName* type: String Unique source name *mediaSources.*.sourceKind* type:", "source, render, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemRender' self.dataout['source'] = source", "of the source item. *left* type: int Pixel position of", "__init__(self): Baserequests.__init__(self) self.name = 'GetStreamSettings' self.datain['type'] = None self.datain['settings'] =", "of the top of the source item. *bottom* type: int", "not been tested. :Arguments: *sourceName* type: String Source name. *timeOffset*", "to set. \"\"\" def __init__(self, filename_formatting): Baserequests.__init__(self) self.name = 'SetFilenameFormatting'", "= vertical self.dataout['render'] = render class GetTextFreetype2Properties(Baserequests): \"\"\"Get the current", "of the bottom of the source item. *left* type: int", "third Mic/Aux input source. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "information). :Returns: *authRequired* type: boolean Indicates whether authentication is required.", "self.datain['isRecording'] = None self.datain['isRecordingPaused'] = None self.datain['recordTimecode'] = None self.datain['recordingFilename']", "Name of the scene to switch to. *transitionName* type: String", "item. Unique on a scene by scene basis. *items.*.name* type:", "(Optional) Type of projector: `Preview` (default), `Source`, `Scene`, `StudioProgram`, or", "instead of amplitude/mul. \"\"\" def __init__(self, source, volume, useDecibel=None): Baserequests.__init__(self)", "of the scene item's source. Either `input`, `group`, or `scene`", "= None self.dataout['item'] = item self.dataout['fromScene'] = fromScene self.dataout['toScene'] =", "source types, may require some probing around). \"\"\" def __init__(self,", "name *filters.*.settings* type: Object Filter settings \"\"\" def __init__(self, sourceName):", "= read_from_file self.dataout['font'] = font self.dataout['gradient'] = gradient self.dataout['gradient_color'] =", "not paused. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ResumeRecording' class", ":Arguments: *sourceName* type: String Source name. :Returns: *timestamp* type: int", "when not visible. *render* type: boolean (optional) Visibility of the", "type: String The media state of the provided source. States:", "sourceName, setVisible): Baserequests.__init__(self) self.name = 'AddSceneItem' self.datain['itemId'] = None self.dataout['sceneName']", "a Browser Source. :Arguments: *source* type: String Source name. :Returns:", "the current scene. *toScene* type: String (optional) Name of the", "Text Alignment (\"left\", \"center\", \"right\"). *bk_color* type: int (optional) Background", "specified source. :Arguments: *source* type: String Source name. *offset* type:", "Trigger Alt Key *keyModifiers.control* type: boolean Trigger Control (Ctrl) Key", "the active transition before switching scenes. Defaults to the active", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'SaveReplayBuffer' class SetCurrentSceneCollection(Baserequests): \"\"\"Change", "type: String List of available request types, formatted as a", "size differs from base size *fps* type: double Frames rendered", "new amount of pixels cropped off the top of the", "(only present if currently recording). \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "the running OBS instance :Returns: *sources* type: Array<Object> Array of", "of OBS v25.0.8) :Arguments: *sourceName* type: String Source name. *timestamp*", "scaled pictures. Aspect ratio is preserved if only one of", "def __init__(self): Baserequests.__init__(self) self.name = 'ResumeRecording' class SetRecordingFolder(Baserequests): \"\"\" Please", "chatlog_lines=None, color=None, extents=None, extents_cx=None, extents_cy=None, file=None, read_from_file=None, font=None, gradient=None, gradient_color=None,", "`settings` object or an error will occur when starting the", "current scene. *toScene* type: String (optional) Name of the scene", "= height self.dataout['fps'] = fps self.dataout['shutdown'] = shutdown self.dataout['render'] =", "<filename>obswebsocket/requests.py<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- # THIS", "self.name = 'ReorderSceneItems' self.dataout['items'] = items self.dataout['scene'] = scene class", "A single key combination might trigger multiple hotkey routines depending", "sourceName class NextMedia(Baserequests): \"\"\"Skip to the next media item in", "Array of scene items *sceneItems.*.itemId* type: int Unique item id", "horizontal scaling factor) *height* type: double Scene item height (base", "filterName): Baserequests.__init__(self) self.name = 'GetSourceFilterInfo' self.datain['enabled'] = None self.datain['type'] =", "and `20.0` for mul, and under 26.0 for dB. OBS", "present if `use_auth` is `true`. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "the currently selected transition if supported. :Arguments: *duration* type: int", "been tested. :Arguments: *sourceName* type: String Source name. *timeOffset* type:", "probing around). :Returns: *sourceName* type: String Source name *sourceType* type:", "\"\"\"Switch to the specified scene. :Arguments: *scene_name* type: String Name", "self.dataout['sourceName'] = sourceName self.dataout['timeOffset'] = timeOffset class GetMediaState(Baserequests): \"\"\"Get the", "(e.g. `OBS_KEY_A` for key \"A\"). Available identifiers [here](https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h) *keyModifiers* type:", "types *types.*.typeId* type: String Non-unique internal source type ID *types.*.displayName*", "(optional) The publish key. *settings.use_auth* type: boolean (optional) Indicates whether", "of the scene to create the scene item in *sourceName*", "is an object) \"\"\" def __init__(self, item, scene_name=None): Baserequests.__init__(self) self.name", "connected WebSocket clients :Arguments: *realm* type: String Identifier to be", "getStreaming(self): return self.datain['streaming'] def getRecording(self): return self.datain['recording'] def getStreamTimecode(self): return", "the stream. *stream.metadata* type: Object (optional) Adds the given object", "class GetSourceTypesList(Baserequests): \"\"\"Get a list of all available sources types", "*newIndex* type: Integer Desired position of the filter in the", "the source from the left. *position.y* type: double The y", "data as decibels instead of amplitude/mul. \"\"\" def __init__(self, source,", "desired audio sync offset (in nanoseconds). \"\"\" def __init__(self, source,", "def __init__(self): Baserequests.__init__(self) self.name = 'PauseRecording' class ResumeRecording(Baserequests): \"\"\"Resume/unpause the", "= None self.datain['rotation'] = None self.datain['scale'] = None self.datain['crop'] =", "def getCss(self): return self.datain['css'] def getWidth(self): return self.datain['width'] def getHeight(self):", "= bk_opacity self.dataout['chatlog'] = chatlog self.dataout['chatlog_lines'] = chatlog_lines self.dataout['color'] =", "*sc_name* type: String Name of the desired scene collection. \"\"\"", "self.name = 'StartReplayBuffer' class StopReplayBuffer(Baserequests): \"\"\"Stop recording into the Replay", "(in degrees). \"\"\" def __init__(self, item, x_scale, y_scale, rotation, scene_name=None):", "value supported by Qt's Image module) *saveToFilePath* type: String (optional)", "no override is set. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name", "the scene where the new item was created *item* type:", "duration of the transition (in milliseconds). \"\"\" def __init__(self, duration):", "self.name = 'StartStopStreaming' class StartStreaming(Baserequests): \"\"\"Start streaming. Will return an", "(optional) Interperet `volume` data as decibels instead of amplitude/mul. \"\"\"", "def __init__(self, source, color1=None, color2=None, custom_width=None, drop_shadow=None, font=None, from_file=None, log_mode=None,", "compressionQuality=None, width=None, height=None): Baserequests.__init__(self) self.name = 'TakeSourceScreenshot' self.datain['sourceName'] = None", "Source. :Arguments: *source* type: String Source name. :Returns: *source* type:", "(optional) Outline color. *outline_size* type: int (optional) Outline size. *outline_opacity*", "the filter to reorder *movementType* type: String How to move", "self.datain['name'] def getVolume(self): return self.datain['volume'] def getMuted(self): return self.datain['muted'] class", "return self.datain['muted'] class SetVolume(Baserequests): \"\"\"Set the volume of the specified", "window) :Returns: *stats* type: OBSStats [OBS stats](#obsstats) \"\"\" def __init__(self):", "None self.dataout['sceneName'] = sceneName self.dataout['sourceName'] = sourceName self.dataout['setVisible'] = setVisible", "active scene. *scenes* type: Array<Scene> Ordered list of the current", "of the scene to switch to. \"\"\" def __init__(self, sceneName):", "__init__(self): Baserequests.__init__(self) self.name = 'PauseRecording' class ResumeRecording(Baserequests): \"\"\"Resume/unpause the current", "self.dataout['mute'] = mute class ToggleMute(Baserequests): \"\"\"Inverts the mute status of", "source. :Arguments: *source* type: String Source name. \"\"\" def __init__(self,", "text self.dataout['text_file'] = text_file self.dataout['word_wrap'] = word_wrap class GetBrowserSourceProperties(Baserequests): \"\"\"Get", "self.datain['studio-mode'] class GetPreviewScene(Baserequests): \"\"\"Get the name of the currently previewed", "= None def getTypes(self): return self.datain['types'] class GetVolume(Baserequests): \"\"\"Get the", "double The y-scale factor of the source. *crop.top* type: int", "Filter type *name* type: String Filter name *settings* type: Object", "Mode is not enabled. :Arguments: *with_transition* type: Object (optional) Change", "getScene(self): return self.datain['scene'] def getItem(self): return self.datain['item'] class SetCurrentScene(Baserequests): \"\"\"Switch", "name *img* type: String Image Data URI (if `embedPictureFormat` was", "self.name = 'PreviousMedia' self.dataout['sourceName'] = sourceName class GetMediaDuration(Baserequests): \"\"\"Get the", "1.0. Note: Transition returns 1.0 when not active. \"\"\" def", "from the source scene (required) *item.name* type: String Scene Item", "scene=None): Baserequests.__init__(self) self.name = 'ReorderSceneItems' self.dataout['items'] = items self.dataout['scene'] =", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetRecordingFolder' self.datain['rec-folder'] = None", "source that the item is manipulated from. The sum of", "int (optional) Screenshot height. Defaults to the source's base height.", "*gradient_dir* type: float Gradient direction. *gradient_opacity* type: int Gradient opacity", "alignment of the source. *rotation* type: double (optional) The new", "= save class GetStreamSettings(Baserequests): \"\"\"Get the current streaming server settings.", "def getStats(self): return self.datain['stats'] class BroadcastCustomMessage(Baserequests): \"\"\"Broadcast custom message to", "or more sub-sources *types.*.caps.doNotDuplicate* type: Boolean True if sources of", "of attenuation instead of amplitude/mul. :Returns: *name* type: String Source", "self.dataout['rec-folder'] = rec_folder class GetRecordingFolder(Baserequests): \"\"\"Get the path of the", "new alignment of the source. *rotation* type: double (optional) The", "None def getBaseWidth(self): return self.datain['baseWidth'] def getBaseHeight(self): return self.datain['baseHeight'] def", "shutdown when not visible. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name", "type: int Base width (without scaling) of the source *sourceHeight*", "StartStopReplayBuffer(Baserequests): \"\"\"Toggle the Replay Buffer on/off (depending on the current", "CALL THIS if you called `SetTBarPosition` with the `release` parameter", "type: String Unique source name *mediaSources.*.sourceKind* type: String Unique source", "type: String Source name. *volume* type: double Desired volume. Must", "connecting to the streaming server. *settings.username* type: String (optional) The", "filter to reorder *movementType* type: String How to move the", "image with. -1 is automatic, 1 is smallest file/most compression,", "__init__(self): Baserequests.__init__(self) self.name = 'StartStopRecording' class StartRecording(Baserequests): \"\"\"Start recording. Will", "class GetSceneItemList(Baserequests): \"\"\"Get a list of all scene items in", "class GetTransitionList(Baserequests): \"\"\"List of all transitions available in the frontend's", "self.datain['img'] = None self.datain['imageFile'] = None self.dataout['sourceName'] = sourceName self.dataout['embedPictureFormat']", "be fully duplicated *types.*.caps.doNotSelfMonitor* type: Boolean True if sources of", "to OBS may not function properly when they are controlled", "self.dataout['crop'] = crop self.dataout['visible'] = visible self.dataout['locked'] = locked self.dataout['bounds']", "self.name = 'GetSyncOffset' self.datain['name'] = None self.datain['offset'] = None self.dataout['source']", "def getColor(self): return self.datain['color'] def getExtents(self): return self.datain['extents'] def getExtents_cx(self):", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ResumeRecording' class SetRecordingFolder(Baserequests): \"\"\"", "= 'SetAudioMonitorType' self.dataout['sourceName'] = sourceName self.dataout['monitorType'] = monitorType class TakeSourceScreenshot(Baserequests):", "getTransitionDuration(self): return self.datain['transition-duration'] class GetTransitionPosition(Baserequests): \"\"\"Get the position of the", "source before scaling. *crop.bottom* type: int The number of pixels", "type: boolean Trigger Shift Key *keyModifiers.alt* type: boolean Trigger Alt", "self.datain['videoFormat'] = None self.datain['colorSpace'] = None self.datain['colorRange'] = None def", "the streaming server. *stream.settings.username* type: String (optional) If authentication is", "position (like a user releasing their mouse button after moving", "The number of pixels cropped off the right of the", "image file (if `saveToFilePath` was specified in the request) \"\"\"", "*source* type: String Source name. *is_local_file* type: boolean Indicates that", "list of sources. Will return an `error` if Studio Mode", "def __init__(self, sourceName, playPause): Baserequests.__init__(self) self.name = 'PlayPauseMedia' self.dataout['sourceName'] =", "class AddSceneItem(Baserequests): \"\"\"Creates a scene item in a scene. In", "of the second Mic/Aux input source. *mic_3* type: String (optional)", "*muted* type: bool If the source is muted. *locked* type:", "`error` if streaming is not active. \"\"\" def __init__(self): Baserequests.__init__(self)", "source *sourceSettings* type: Object Source settings (varies between source types,", "getName(self): return self.datain['name'] def getItemId(self): return self.datain['itemId'] def getPosition(self): return", "source. *rotation* type: double (optional) The new clockwise rotation of", "item in the playlist. Supports only vlc media source (as", "Available identifiers [here](https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h) *keyModifiers* type: Object (Optional) Optional key modifiers", "'SetPreviewScene' self.dataout['scene-name'] = scene_name class TransitionToProgram(Baserequests): \"\"\"Transitions the currently previewed", "None self.datain['recordingFilename'] = None def getIsRecording(self): return self.datain['isRecording'] def getIsRecordingPaused(self):", "top. *position.alignment* type: int The point on the source that", "override is set. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name =", "in the request) *imageFile* type: String Absolute path to the", "and 4=Top or 8=Bottom, or omit to center on that", "media sources (as of OBS v25.0.8) Note: Due to processing/network", "stream=None): Baserequests.__init__(self) self.name = 'StartStreaming' self.dataout['stream'] = stream class StopStreaming(Baserequests):", "Height scale factor. *rotation* type: double Source item rotation (in", "return self.datain['outline_opacity'] def getText(self): return self.datain['text'] def getValign(self): return self.datain['valign']", "String Source name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name =", "*color1* type: int (optional) Gradient top color. *color2* type: int", "it is an object). *item.name* type: String (optional) Scene Item", "Boolean True if sources of this type provide audio *types.*.caps.canInteract*", "Full file path (file extension included) where the captured image", "*vertical* type: boolean Vertical text enabled. \"\"\" def __init__(self, source):", "new amount of pixels cropped off the right of the", "self.name = 'SetSceneTransitionOverride' self.dataout['sceneName'] = sceneName self.dataout['transitionName'] = transitionName self.dataout['transitionDuration']", "None self.datain['colorSpace'] = None self.datain['colorRange'] = None def getBaseWidth(self): return", "self.dataout['sourceName'] = sourceName class GetMediaDuration(Baserequests): \"\"\"Get the length of media", "class GetRecordingFolder(Baserequests): \"\"\"Get the path of the current recording folder.", "to the streaming server. *settings.username* type: String (optional) The username", "type. *width* type: int (optional) Screenshot width. Defaults to the", "size. *font.style* type: String (optional) Font Style (unknown function). *gradient*", ":Returns: *isReplayBufferActive* type: boolean Current recording status. \"\"\" def __init__(self):", "file=None, read_from_file=None, font=None, gradient=None, gradient_color=None, gradient_dir=None, gradient_opacity=None, outline=None, outline_color=None, outline_size=None,", "scene=None): Baserequests.__init__(self) self.name = 'DeleteSceneItem' self.dataout['item'] = item self.dataout['scene'] =", "`saveToFilePath` was specified in the request) \"\"\" def __init__(self, sourceName=None,", "'GetMediaSourcesList' self.datain['mediaSources'] = None def getMediaSources(self): return self.datain['mediaSources'] class CreateSource(Baserequests):", "\"\"\" def __init__(self, source, volume, useDecibel=None): Baserequests.__init__(self) self.name = 'SetVolume'", "item's source *sceneItems.*.sourceType* type: String Type of the scene item's", "__init__(self, item, scene_name=None): Baserequests.__init__(self) self.name = 'ResetSceneItem' self.dataout['item'] = item", "\"\"\" def __init__(self, sourceName, filterName, newIndex): Baserequests.__init__(self) self.name = 'ReorderSourceFilter'", "self.dataout['sourceName'] = sourceName self.dataout['sourceKind'] = sourceKind self.dataout['sceneName'] = sceneName self.dataout['sourceSettings']", "the RTMP service about the streaming. May be any String,", "*from_file* type: boolean (optional) Read text from the specified file.", "__init__(self): Baserequests.__init__(self) self.name = 'StopRecording' class PauseRecording(Baserequests): \"\"\"Pause the current", "Source name. :Returns: *timestamp* type: int The time in milliseconds", "self.datain['log_mode'] def getOutline(self): return self.datain['outline'] def getText(self): return self.datain['text'] def", "type: boolean Gradient enabled. *gradient_color* type: int Gradient color. *gradient_dir*", "a scene item. :Arguments: *scene* type: String (optional) Name of", "override is set. *transitionDuration* type: int Transition duration. `-1` if", "self.name = 'SetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName'] = transitionName self.dataout['transitionSettings']", "\"ReplayBuffer.Save\") \"\"\" def __init__(self, hotkeyName): Baserequests.__init__(self) self.name = 'TriggerHotkeyByName' self.dataout['hotkeyName']", "given type (usually 'rtmp_custom' or 'rtmp_common'). If the currently configured", "(if paused). Returns an error if recording is not active", "\"\"\"Executes hotkey routine, identified by bound combination of keys. A", "None def getStudioMode(self): return self.datain['studio-mode'] class GetPreviewScene(Baserequests): \"\"\"Get the name", "\"\"\"Tells the client if authentication is required. If so, returns", "'SetSceneItemProperties' self.dataout['item'] = item self.dataout['scene-name'] = scene_name self.dataout['position'] = position", "Name of the source to be added *setVisible* type: boolean", "type: double Scene item width (base source width multiplied by", "self.dataout['height'] = height def getSourceName(self): return self.datain['sourceName'] def getImg(self): return", "type: String Response to the auth challenge (see \"Authentication\" for", "a projector window or create a projector on a monitor.", "used when connecting to the streaming server. *settings.username* type: String", "self.datain['sourceSettings'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceSettings'] = sourceSettings self.dataout['sourceType']", "self.dataout['setVisible'] = setVisible def getItemId(self): return self.datain['itemId'] class GetSourcesList(Baserequests): \"\"\"List", "return self.datain['outline_size'] def getOutline_opacity(self): return self.datain['outline_opacity'] def getText(self): return self.datain['text']", "'TriggerHotkeyBySequence' self.dataout['keyId'] = keyId self.dataout['keyModifiers'] = keyModifiers class PlayPauseMedia(Baserequests): \"\"\"Pause", "if `use_auth` is not set to `true`. \"\"\" def __init__(self,", "Id preferred due to uniqueness per scene *items.*.id* type: int", "combination of keys. A single key combination might trigger multiple", "Custom width (0 to disable). *drop_shadow* type: boolean (optional) Drop", "the visibility/enabled state of a filter :Arguments: *sourceName* type: String", "(depending on the current stream state). \"\"\" def __init__(self): Baserequests.__init__(self)", "v25.0.8) Note: For some reason, for the first 5 or", "class ToggleMute(Baserequests): \"\"\"Inverts the mute status of a specified source.", "1 is smallest file/most compression, 100 is largest file/least compression.", "if sources of this type composite one or more sub-sources", "(optional) Gradient opacity (0-100). *outline* type: boolean (optional) Outline. *outline_color*", "identifier (e.g. `OBS_KEY_A` for key \"A\"). Available identifiers [here](https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h) *keyModifiers*", "= monitor self.dataout['geometry'] = geometry self.dataout['name'] = name class TriggerHotkeyByName(Baserequests):", "(if the `item` field is an object) \"\"\" def __init__(self,", "active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionPosition' self.datain['position'] =", "type: String Name of the desired scene collection. \"\"\" def", "latest version of the plugin and the API. :Returns: *version*", "sourceName): Baserequests.__init__(self) self.name = 'GetMediaDuration' self.datain['mediaDuration'] = None self.dataout['sourceName'] =", "not set in OBS' settings. Setting this hotkey is mandatory,", "self.name = 'GetStreamingStatus' self.datain['streaming'] = None self.datain['recording'] = None self.datain['stream-timecode']", "= compressionQuality self.dataout['width'] = width self.dataout['height'] = height def getSourceName(self):", "def __init__(self, scene_name): Baserequests.__init__(self) self.name = 'SetPreviewScene' self.dataout['scene-name'] = scene_name", "self.name = 'ListOutputs' self.datain['outputs'] = None def getOutputs(self): return self.datain['outputs']", "source is muted. \"\"\" def __init__(self, source, useDecibel=None): Baserequests.__init__(self) self.name", "self.dataout['source'] = source self.dataout['useDecibel'] = useDecibel def getName(self): return self.datain['name']", "AddFilterToSource(Baserequests): \"\"\"Add a new filter to a source. Available source", "transition. :Returns: *position* type: double current transition position. This value", "name. *sourceType* type: String (optional) Type of the specified source.", "= 'Authenticate' self.dataout['auth'] = auth class SetHeartbeat(Baserequests): \"\"\"Enable/disable sending of", "self.datain['gradient_dir'] def getGradient_opacity(self): return self.datain['gradient_opacity'] def getOutline(self): return self.datain['outline'] def", "Drop shadow. *font* type: Object (optional) Holds data for the", "\"\"\"Skip to the next media item in the playlist. Supports", "the currently previewed scene and its list of sources. Will", "to a source :Arguments: *sourceName* type: String Source name :Returns:", "(optional) The username for the streaming service. *settings.password* type: String", "*playPause* type: boolean Whether to pause or play the source.", "the previous media item in the playlist. Supports only vlc", "self.datain['authRequired'] def getChallenge(self): return self.datain['challenge'] def getSalt(self): return self.datain['salt'] class", "*obs_websocket_version* type: String obs-websocket plugin version. *obs_studio_version* type: String OBS", "path of the current recording folder. :Returns: *rec_folder* type: String", "self.dataout['compressionQuality'] = compressionQuality self.dataout['width'] = width self.dataout['height'] = height def", "self.datain['transitions'] = None def getCurrentTransition(self): return self.datain['current-transition'] def getTransitions(self): return", "Style (unknown function). *from_file* type: boolean (optional) Read text from", "streaming server settings. Any options not passed will remain unchanged.", "Supports ffmpeg and vlc media sources (as of OBS v25.0.8)", "GDI Plus source. :Arguments: *source* type: String Source name. :Returns:", "boolean Outline. *text* type: String Text content to be displayed.", "in this way. :Arguments: *outputName* type: String Output name *force*", "Name of the scene where the new item was created", "`height` parameters to receive scaled pictures. Aspect ratio is preserved", "= gradient self.dataout['gradient_color'] = gradient_color self.dataout['gradient_dir'] = gradient_dir self.dataout['gradient_opacity'] =", "type: int (optional) Height. *fps* type: int (optional) Framerate. *shutdown*", "a media source. Supports ffmpeg and vlc media sources (as", "self.datain['bounds'] = None self.datain['sourceWidth'] = None self.datain['sourceHeight'] = None self.datain['width']", "factor of the source. *crop.top* type: int The number of", "plugins which add outputs to OBS may not function properly", "timestamp): Baserequests.__init__(self) self.name = 'SetMediaTime' self.dataout['sourceName'] = sourceName self.dataout['timestamp'] =", "filter name *filterEnabled* type: Boolean New filter state \"\"\" def", "routine, identified by bound combination of keys. A single key", "self.datain['muted'] = None self.dataout['source'] = source def getName(self): return self.datain['name']", "to the source's base width. *height* type: int (optional) Screenshot", "self.dataout['sourceName'] = sourceName class NextMedia(Baserequests): \"\"\"Skip to the next media", "settings (they can be partial) :Returns: *transitionSettings* type: Object Updated", "to write the image with. -1 is automatic, 1 is", "the start of the media. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self)", "name. :Returns: *monitorType* type: String The monitor type in use.", "*transitions.*.name* type: String Name of the transition. \"\"\" def __init__(self):", "source *sourceSettings* type: Object Updated source settings \"\"\" def __init__(self,", "bottom self.dataout['left'] = left self.dataout['right'] = right self.dataout['scene-name'] = scene_name", "streaming on or off (depending on the current stream state).", "flag. `Bold=1, Italic=2, Bold Italic=3, Underline=5, Strikeout=8` *font.size* type: int", "and save the contents of the Replay Buffer to disk.", "Baserequests.__init__(self) self.name = 'RemoveSceneTransitionOverride' self.dataout['sceneName'] = sceneName class GetSceneTransitionOverride(Baserequests): \"\"\"Get", "name. *x* type: double X coordinate. *y* type: double Y", "displayed. *text_file* type: String (optional) File path. *word_wrap* type: boolean", "scene. *item* type: Object Scene item to delete (required) *item.name*", "return self.datain['text'] def getValign(self): return self.datain['valign'] def getVertical(self): return self.datain['vertical']", "way. :Arguments: *outputName* type: String Output name *force* type: boolean", "coordinates of a specified source item. :Arguments: *scene_name* type: String", "*name* type: String The name of the active preview scene.", "GetTransitionPosition(Baserequests): \"\"\"Get the position of the current transition. :Returns: *position*", "source :Arguments: *sourceName* type: String Name of the source from", "source. *align* type: String (optional) Text Alignment (\"left\", \"center\", \"right\").", "(optional) File path. *word_wrap* type: boolean (optional) Word wrap. \"\"\"", "filterName, filterEnabled): Baserequests.__init__(self) self.name = 'SetSourceFilterVisibility' self.dataout['sourceName'] = sourceName self.dataout['filterName']", "state \"\"\" def __init__(self, sourceName, filterName, filterEnabled): Baserequests.__init__(self) self.name =", ":Arguments: *sourceName* type: String Source name :Returns: *filters* type: Array<Object>", "selected transition in the frontend's dropdown menu. :Returns: *name* type:", "def __init__(self, source): Baserequests.__init__(self) self.name = 'GetSyncOffset' self.datain['name'] = None", "transition_name class SetTransitionDuration(Baserequests): \"\"\"Set the duration of the currently selected", "self.name = 'SetSceneItemRender' self.dataout['source'] = source self.dataout['render'] = render self.dataout['scene-name']", "int The number of pixels cropped off the top of", "= color2 self.dataout['custom_width'] = custom_width self.dataout['drop_shadow'] = drop_shadow self.dataout['font'] =", "bk_color=None, bk_opacity=None, chatlog=None, chatlog_lines=None, color=None, extents=None, extents_cx=None, extents_cy=None, file=None, read_from_file=None,", "scene item. \"\"\" def __init__(self, source, is_local_file=None, local_file=None, url=None, css=None,", "`ReleaseTBar` later once the animation/interaction is over. :Arguments: *position* type:", "true = shown ; false = hidden \"\"\" def __init__(self,", "self.dataout['outputName'] = outputName class StopOutput(Baserequests): \"\"\" Note: Controlling outputs is", "of the specified source. Useful for type-checking to avoid settings", "RemoveFilterFromSource(Baserequests): \"\"\"Remove a filter from a source :Arguments: *sourceName* type:", "for the stream. *stream.settings.server* type: String (optional) The publish URL.", "\"\"\"Add a new filter to a source. Available source types", "def getFilters(self): return self.datain['filters'] class GetSourceFilterInfo(Baserequests): \"\"\"List filters applied to", "def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'StopMedia' self.dataout['sourceName'] = sourceName", "supports larger values. *useDecibel* type: boolean (optional) Interperet `volume` data", "double (optional) The new width of the bounding box. *bounds.y*", "encoded picture. Can be \"png\", \"jpg\", \"jpeg\" or \"bmp\" (or", "50ms. :Arguments: *sourceName* type: String Source name. :Returns: *mediaDuration* type:", "the current scene's source items. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "streaming service. *settings.password* type: String (optional) The password for the", "pass data to the RTMP service about the streaming. May", "the duration of the currently selected transition if supported. :Returns:", "int ID of the SceneItem in the scene. \"\"\" def", "button after moving it). *YOU MUST CALL THIS if you", "type of the specified source. :Arguments: *sourceName* type: String Source", "\"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaDuration' self.datain['mediaDuration'] =", "type: Object (optional) Special stream configuration. Please note: these won't", "return self.datain['type'] def getSettings(self): return self.datain['settings'] class SaveStreamSettings(Baserequests): \"\"\"Save the", "bottom color. *custom_width* type: int (optional) Custom width (0 to", "self.dataout['filterName'] = filterName def getEnabled(self): return self.datain['enabled'] def getType(self): return", "of the filter to reconfigure *filterSettings* type: Object New settings.", "\"\"\"Get the name of the current profile. :Returns: *profile_name* type:", "int (optional) Compression ratio between -1 and 100 to write", "String The type of streaming service configuration, usually `rtmp_custom` or", "*log_mode* type: boolean (optional) Chat log. *outline* type: boolean (optional)", "self.datain['item'] = None self.dataout['item'] = item self.dataout['fromScene'] = fromScene self.dataout['toScene']", "scene. *source* type: String Scene Item name. *render* type: boolean", "self.name = 'StartOutput' self.dataout['outputName'] = outputName class StopOutput(Baserequests): \"\"\" Note:", "None self.datain['extents_cy'] = None self.datain['file'] = None self.datain['read_from_file'] = None", "the first Desktop Audio capture source. *desktop_2* type: String (optional)", "`error`, `unknown` \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaState'", "sync offset of a specified source. :Arguments: *source* type: String", "that source. States: `none`, `playing`, `opening`, `buffering`, `paused`, `stopped`, `ended`,", "(optional) Outline. *outline_color* type: int (optional) Outline color. *outline_size* type:", "self.datain['img'] def getImageFile(self): return self.datain['imageFile'] class ListOutputs(Baserequests): \"\"\"List existing outputs", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopRecording' class StartRecording(Baserequests): \"\"\"Start", "ScrubMedia(Baserequests): \"\"\"Scrub media using a supplied offset. Supports ffmpeg and", "type: String Source name. *mute* type: boolean Desired mute status.", "self.datain['fps'] def getVideoFormat(self): return self.datain['videoFormat'] def getColorSpace(self): return self.datain['colorSpace'] def", "SetTextFreetype2Properties(Baserequests): \"\"\"Set the current properties of a Text Freetype 2", "def getDesktop1(self): return self.datain['desktop-1'] def getDesktop2(self): return self.datain['desktop-2'] def getMic1(self):", "def getName(self): return self.datain['name'] def getSources(self): return self.datain['sources'] class SetPreviewScene(Baserequests):", "self.dataout['render'] = render class GetTextFreetype2Properties(Baserequests): \"\"\"Get the current properties of", "in degrees. *scale.x* type: double (optional) The new x scale", "Baserequests.__init__(self) self.name = 'DisableStudioMode' class ToggleStudioMode(Baserequests): \"\"\"Toggles Studio Mode (depending", "streaming started (only present if currently streaming). *rec_timecode* type: String", "String (optional) *salt* type: String (optional) \"\"\" def __init__(self): Baserequests.__init__(self)", "the source item. *right* type: int Pixel position of the", "specified. Clients can specify `width` and `height` parameters to receive", "getMuted(self): return self.datain['muted'] def getLocked(self): return self.datain['locked'] def getBounds(self): return", "self.datain['width'] = None self.datain['height'] = None self.datain['fps'] = None self.datain['shutdown']", "'ListSceneCollections' self.datain['scene-collections'] = None def getSceneCollections(self): return self.datain['scene-collections'] class GetSceneItemList(Baserequests):", "'true' keeps it in its current position, 'false' allows movement.", "__init__(self, sourceName, playPause): Baserequests.__init__(self) self.name = 'PlayPauseMedia' self.dataout['sourceName'] = sourceName", "NOT SLIDER PERCENTAGE. :Arguments: *source* type: String Source name. *volume*", "self.datain['type'] def getSettings(self): return self.datain['settings'] class SaveStreamSettings(Baserequests): \"\"\"Save the current", "the filter around in the source's filter chain. Either \"up\",", "the change won't be applied immediately and will be effective", "if Studio Mode is not enabled. :Arguments: *with_transition* type: Object", "= None self.datain['drop_shadow'] = None self.datain['font'] = None self.datain['from_file'] =", "new bounds type of the source. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\",", "String Source name. *offset* type: int The audio sync offset", "probing around). \"\"\" def __init__(self, sourceName, sourceType=None): Baserequests.__init__(self) self.name =", "scaling. *crop.bottom* type: int (optional) The new amount of pixels", "String Transition name *transitionSettings* type: Object Transition settings (they can", "None def getMediaSources(self): return self.datain['mediaSources'] class CreateSource(Baserequests): \"\"\"Create a source", "used when connecting to the streaming server. *stream.settings.username* type: String", "type: int Height. *fps* type: int Framerate. *shutdown* type: boolean", "type: Object Filter settings \"\"\" def __init__(self, sourceName, filterName, filterType,", "current streaming server settings. Any options not passed will remain", "the scene to switch to. *transitionName* type: String Name of", "of the current profile. :Returns: *profile_name* type: String Name of", "is -1). Encoded in Base64 using [Qt's geometry encoding](https://doc.qt.io/qt-5/qwidget.html#saveGeometry). Corresponds", "scene. Will return an `error` if Studio Mode is not", "internal source type ID *types.*.displayName* type: String Display name of", "Replay Buffer on/off (depending on the current state of the", "file path. *url* type: String Url. *css* type: String CSS", "String Filter name *settings* type: Object Filter settings \"\"\" def", "(optional) Output volume in decibels of attenuation instead of amplitude/mul.", "self.datain['extents_cy'] = None self.datain['file'] = None self.datain['read_from_file'] = None self.datain['font']", "def __init__(self, item, scene=None): Baserequests.__init__(self) self.name = 'DeleteSceneItem' self.dataout['item'] =", "of scene items from. Defaults to the current scene if", "self.dataout['font'] = font self.dataout['gradient'] = gradient self.dataout['gradient_color'] = gradient_color self.dataout['gradient_dir']", "= None self.datain['itemId'] = None self.datain['position'] = None self.datain['rotation'] =", "return self.datain['transitionSettings'] class ReleaseTBar(Baserequests): \"\"\"Release the T-Bar (like a user", "self.datain['profile-name'] class ListProfiles(Baserequests): \"\"\"Get a list of available profiles. :Returns:", "Source name. *align* type: String Text Alignment (\"left\", \"center\", \"right\").", "GetStudioModeStatus(Baserequests): \"\"\"Indicates if Studio Mode is currently enabled. :Returns: *studio_mode*", "self.name = 'GetFilenameFormatting' self.datain['filename-formatting'] = None def getFilenameFormatting(self): return self.datain['filename-formatting']", "for the streaming server. Ignored if `use_auth` is not set", "scaling) of the source *sourceHeight* type: int Base source (without", "existing outputs :Returns: *outputs* type: Array<Output> Outputs list \"\"\" def", "the specified source. :Arguments: *sourceName* type: String Source name. :Returns:", "of media in milliseconds. Supports ffmpeg and vlc media sources", "enabled. *render* type: boolean (optional) Visibility of the scene item.", "`supported-image-export-formats` response field of `GetVersion`). If not specified, tries to", "item in. Defaults to the current scene. *item* type: Object", "type: String Name of the scene to create the scene", "unchanged. Coordinates are relative to the item's parent (the scene", "getSourceType(self): return self.datain['sourceType'] def getSourceSettings(self): return self.datain['sourceSettings'] class SetSourceSettings(Baserequests): \"\"\"Set", "utf-8 -*- # THIS FILE WAS GENERATED BY generate_classes.py -", "outputName self.dataout['force'] = force class SetCurrentProfile(Baserequests): \"\"\"Set the currently active", "return self.datain['obs-websocket-version'] def getObsStudioVersion(self): return self.datain['obs-studio-version'] def getAvailableRequests(self): return self.datain['available-requests']", "from. Defaults to the current scene if not specified. :Returns:", "of a specified source. :Arguments: *source* type: String Source name.", "self.dataout['source'] = source def getSource(self): return self.datain['source'] def getColor1(self): return", "stream class StopStreaming(Baserequests): \"\"\"Stop streaming. Will return an `error` if", "provided text as embedded CEA-608 caption data. :Arguments: *text* type:", "Baserequests.__init__(self) self.name = 'ResumeRecording' class SetRecordingFolder(Baserequests): \"\"\" Please note: if", "Gradient enabled. *gradient_color* type: int Gradient color. *gradient_dir* type: float", "*sourceName* type: String Source name. :Returns: *mediaDuration* type: int The", "font=None, from_file=None, log_mode=None, outline=None, text=None, text_file=None, word_wrap=None): Baserequests.__init__(self) self.name =", "color self.dataout['extents'] = extents self.dataout['extents_cx'] = extents_cx self.dataout['extents_cy'] = extents_cy", "specified source *sourceSettings* type: Object Updated source settings \"\"\" def", "format *colorSpace* type: String Color space for YUV *colorRange* type:", "from the top. *position.alignment* type: int The point on the", "return self.datain['groupChildren'] class SetSceneItemProperties(Baserequests): \"\"\"Sets the scene specific properties of", "getShutdown(self): return self.datain['shutdown'] class SetBrowserSourceProperties(Baserequests): \"\"\"Set current properties for a", "type: boolean Trigger Control (Ctrl) Key *keyModifiers.command* type: boolean Trigger", "self.datain['transitionDuration'] = None self.dataout['sceneName'] = sceneName def getTransitionName(self): return self.datain['transitionName']", "type: int Gradient top color. *color2* type: int Gradient bottom", "Width. *height* type: int (optional) Height. *fps* type: int (optional)", "class StartOutput(Baserequests): \"\"\" Note: Controlling outputs is an experimental feature", "Source name. :Returns: *source* type: String Source name. *align* type:", "self.name = 'SetSourceFilterVisibility' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterEnabled']", "*stream_timecode* type: String (optional) Time elapsed since streaming started (only", "the frontend's dropdown menu. :Returns: *current_transition* type: String Name of", "__init__(self): Baserequests.__init__(self) self.name = 'GetRecordingFolder' self.datain['rec-folder'] = None def getRecFolder(self):", "\"\"\"Changes the order of scene items in the requested scene.", "class ToggleStudioMode(Baserequests): \"\"\"Toggles Studio Mode (depending on the current state", "of scenes in the currently active profile. :Returns: *current_scene* type:", "to. *sourceSettings* type: Object (optional) Source settings data. *setVisible* type:", "self.datain['name'] def getOffset(self): return self.datain['offset'] class GetSourceSettings(Baserequests): \"\"\"Get settings of", "gets released automatically after setting its new position (like a", "'SetStreamSettings' self.dataout['type'] = type self.dataout['settings'] = settings self.dataout['save'] = save", "of the currently previewed scene and its list of sources.", "self.datain['muted'] class SetMute(Baserequests): \"\"\"Sets the mute status of a specified", "one of these two parameters is specified. :Arguments: *sourceName* type:", "the mute status of a specified source. :Arguments: *source* type:", "Scene Item ID. \"\"\" def __init__(self, item, scene=None): Baserequests.__init__(self) self.name", "self.datain['position'] class GetTransitionSettings(Baserequests): \"\"\"Get the current settings of a transition", "*filterEnabled* type: Boolean New filter state \"\"\" def __init__(self, sourceName,", "Desired position of the filter in the chain \"\"\" def", "self.dataout['sourceName'] = sourceName self.dataout['monitorType'] = monitorType class TakeSourceScreenshot(Baserequests): \"\"\" At", "String (optional) Name of the scene to get the list", "NextMedia(Baserequests): \"\"\"Skip to the next media item in the playlist.", "self.datain['sceneName'] def getSceneItems(self): return self.datain['sceneItems'] class GetSceneItemProperties(Baserequests): \"\"\"Gets the scene", "specified source item in a specified scene. :Arguments: *scene_name* type:", "def __init__(self, item, fromScene=None, toScene=None): Baserequests.__init__(self) self.name = 'DuplicateSceneItem' self.datain['scene']", "volume self.dataout['useDecibel'] = useDecibel class GetMute(Baserequests): \"\"\"Get the mute status", "None self.datain['type'] = None self.datain['name'] = None self.datain['settings'] = None", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentSceneCollection' self.datain['sc-name'] = None", "Source name. *muted* type: boolean Mute status of the source.", "`ReleaseTBar` manually if you set `release` to false. Defaults to", "of the specified source. Default response uses mul format, NOT", "item from. Defaults to the current scene. *toScene* type: String", "factor. *rotation* type: double Source item rotation (in degrees). \"\"\"", "position self.dataout['rotation'] = rotation self.dataout['scale'] = scale self.dataout['crop'] = crop", "an `error` if recording is already active. \"\"\" def __init__(self):", "request types, formatted as a comma-separated list string (e.g. :", "(optional) Time elapsed since recording started (only present if currently", "of the current recording folder. :Returns: *rec_folder* type: String Path", "as visible or not. Defaults to true :Returns: *itemId* type:", "This value will be between 0.0 and 1.0. Note: Transition", ":Arguments: *transitionName* type: String Transition name :Returns: *transitionSettings* type: Object", "List of transitions. *transitions.*.name* type: String Name of the transition.", "Baserequests.__init__(self) self.name = 'GetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName'] = transitionName", "self.dataout['text'] = text self.dataout['valign'] = valign self.dataout['vertical'] = vertical self.dataout['render']", "`Scene`, `StudioProgram`, or `Multiview` (case insensitive). *monitor* type: int (Optional)", "path name. *read_from_file* type: boolean (optional) Read text from the", "class SetSyncOffset(Baserequests): \"\"\"Set the audio sync offset of a specified", "type: Array<SceneItem> Ordered list of the current scene's source items.", "StartRecording(Baserequests): \"\"\"Start recording. Will return an `error` if recording is", "self.datain['stream-timecode'] def getRecTimecode(self): return self.datain['rec-timecode'] def getPreviewOnly(self): return self.datain['preview-only'] class", "outline self.dataout['text'] = text self.dataout['text_file'] = text_file self.dataout['word_wrap'] = word_wrap", "= 'GetRecordingFolder' self.datain['rec-folder'] = None def getRecFolder(self): return self.datain['rec-folder'] class", "name :Returns: *transitionSettings* type: Object Current transition settings \"\"\" def", "double The clockwise rotation of the item in degrees around", "*font.flags* type: int (optional) Font text styling flag. `Bold=1, Italic=2,", "sourceName self.dataout['playPause'] = playPause class RestartMedia(Baserequests): \"\"\"Restart a media source.", "self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterEnabled'] = filterEnabled class", "= duration class GetTransitionDuration(Baserequests): \"\"\"Get the duration of the currently", "specific transition override. :Arguments: *sceneName* type: String Name of the", "Name of the filter to reconfigure *filterSettings* type: Object New", "*sourceName* type: String Source name *sourceType* type: String Type of", "self.datain['sceneItems'] class GetSceneItemProperties(Baserequests): \"\"\"Gets the scene specific properties of the", "Defaults to the currently active scene. *source* type: String Scene", "def __init__(self): Baserequests.__init__(self) self.name = 'GetPreviewScene' self.datain['name'] = None self.datain['sources']", "an `error` if recording is not active. \"\"\" def __init__(self):", "return an `error` if streaming is already active. :Arguments: *stream*", "def __init__(self, source, align=None, bk_color=None, bk_opacity=None, chatlog=None, chatlog_lines=None, color=None, extents=None,", "\"transition\", \"scene\" or \"unknown\" \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "getCss(self): return self.datain['css'] def getWidth(self): return self.datain['width'] def getHeight(self): return", "Name of the scene the scene item belongs to. Defaults", "= scale self.dataout['crop'] = crop self.dataout['visible'] = visible self.dataout['locked'] =", "*bounds.alignment* type: int Alignment of the bounding box. *bounds.x* type:", "(optional) \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetAuthRequired' self.datain['authRequired'] =", "Scene Item name (prefer `id`, including both is acceptable). *item.id*", "new position (like a user releasing their mouse button after", "StartOutput(Baserequests): \"\"\" Note: Controlling outputs is an experimental feature of", "self.datain['crop'] = None self.datain['visible'] = None self.datain['muted'] = None self.datain['locked']", "Text content to be displayed. *valign* type: String Text vertical", "self.datain['groupChildren'] = None self.dataout['item'] = item self.dataout['scene-name'] = scene_name def", "the streaming server. *settings.username* type: String The username to use", "milliseconds). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionDuration' self.datain['transition-duration'] =", "= None self.datain['text'] = None self.datain['valign'] = None self.datain['vertical'] =", "self.datain['enabled'] = None self.datain['type'] = None self.datain['name'] = None self.datain['settings']", "class ListProfiles(Baserequests): \"\"\"Get a list of available profiles. :Returns: *profiles*", "String Unique source internal type (a.k.a `ffmpeg_source` or `vlc_source`) *mediaSources.*.mediaState*", "String Name of the filter to reorder *newIndex* type: Integer", "class SendCaptions(Baserequests): \"\"\"Send the provided text as embedded CEA-608 caption", "\"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int Alignment of", "CSS to inject. *width* type: int Width. *height* type: int", "self.name = 'GetSceneList' self.datain['current-scene'] = None self.datain['scenes'] = None def", "in the currently active profile. :Returns: *current_scene* type: String Name", "= None self.datain['url'] = None self.datain['css'] = None self.datain['width'] =", "\"\"\"Remove any transition override on a scene. :Arguments: *sceneName* type:", "Numeric, or Boolean field. *stream.settings* type: Object (optional) Settings for", "'SetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName'] = transitionName self.dataout['transitionSettings'] = transitionSettings", "boolean (optional) Chat log. *outline* type: boolean (optional) Outline. *text*", "releasing their mouse button after moving the T-Bar). Call `ReleaseTBar`", "name. \"\"\" def __init__(self, sourceName, newName): Baserequests.__init__(self) self.name = 'SetSourceName'", "4-6, 8-10) *bounds.x* type: double (optional) The new width of", "(if this field is a string) or specification (if it", "an `error` if Studio Mode is not enabled. :Returns: *name*", "all media sources (vlc and media source) :Returns: *mediaSources* type:", "rotation self.dataout['scene-name'] = scene_name class SetSceneItemCrop(Baserequests): \"\"\"Sets the crop coordinates", "\"\"\"Set the volume of the specified source. Default request format", "cx. *extents_cy* type: int (optional) Extents cy. *file* type: String", "the hotkey (e.g. \"ReplayBuffer.Save\") \"\"\" def __init__(self, hotkeyName): Baserequests.__init__(self) self.name", "__init__(self, items, scene=None): Baserequests.__init__(self) self.name = 'ReorderSceneItems' self.dataout['items'] = items", "\"\"\" def __init__(self, source, color1=None, color2=None, custom_width=None, drop_shadow=None, font=None, from_file=None,", "class GetStats(Baserequests): \"\"\"Get OBS stats (almost the same info as", "boolean Current recording status. *isRecordingPaused* type: boolean Whether the recording", "the source is visible. *muted* type: bool If the source", "(optional) Extents wrap. *extents_cx* type: int (optional) Extents cx. *extents_cy*", "self.dataout['scene-name'] = scene_name class SetSceneItemTransform(Baserequests): \"\"\"Set the transform of the", "of the source on which the filter is added *filterName*", "'GetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType'] = None self.datain['sourceSettings'] = None", "scene. *item* type: String Scene Item name. *top* type: int", ":Arguments: *auth* type: String Response to the auth challenge (see", "*chatlog_lines* type: int Chat log lines. *color* type: int Text", "getLocked(self): return self.datain['locked'] def getBounds(self): return self.datain['bounds'] def getSourceWidth(self): return", "def getShutdown(self): return self.datain['shutdown'] class SetBrowserSourceProperties(Baserequests): \"\"\"Set current properties for", "stream. *stream.metadata* type: Object (optional) Adds the given object parameters", "return self.datain['outline'] def getText(self): return self.datain['text'] def getText_file(self): return self.datain['text_file']", "scene. :Arguments: *sceneName* type: String (optional) Name of the scene", "= filterName class ReorderSourceFilter(Baserequests): \"\"\"Move a filter in the chain", "current recording (if paused). Returns an error if recording is", "'PreviousMedia' self.dataout['sourceName'] = sourceName class GetMediaDuration(Baserequests): \"\"\"Get the length of", "`GetSourceTypesList`. :Arguments: *sourceName* type: String Name of the source on", "= 'SetCurrentTransition' self.dataout['transition-name'] = transition_name class SetTransitionDuration(Baserequests): \"\"\"Set the duration", "\"\"\" def __init__(self, item, x, y, scene_name=None): Baserequests.__init__(self) self.name =", "def __init__(self, item, scene_name=None): Baserequests.__init__(self) self.name = 'ResetSceneItem' self.dataout['item'] =", "ID. :Returns: *scene* type: String Name of the scene where", "Object Stream settings object. *settings.server* type: String The publish URL.", "*sources* type: Array<SceneItem> \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetPreviewScene'", "= None self.datain['bk_color'] = None self.datain['bk_opacity'] = None self.datain['chatlog'] =", "= sourceName self.dataout['filterName'] = filterName def getEnabled(self): return self.datain['enabled'] def", "= 'GetStudioModeStatus' self.datain['studio-mode'] = None def getStudioMode(self): return self.datain['studio-mode'] class", "Baserequests.__init__(self) self.name = 'GetMediaDuration' self.datain['mediaDuration'] = None self.dataout['sourceName'] = sourceName", "T-Bar). Call `ReleaseTBar` manually if you set `release` to false.", "Source settings data. *setVisible* type: boolean (optional) Set the created", "`item` field is an object) \"\"\" def __init__(self, item, scene_name=None):", "Authenticate(Baserequests): \"\"\"Attempt to authenticate the client to the server. :Arguments:", "*item* type: String Scene Item name. *x_scale* type: double Width", "and `salt` (see \"Authentication\" for more information). :Returns: *authRequired* type:", "*transition_duration* type: int Duration of the current transition (in milliseconds).", "or \"unknown\" \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSourcesList' self.datain['sources']", "in the UI if there is no current override and", "the stream. *stream.settings.server* type: String (optional) The publish URL. *stream.settings.key*", "self.datain['transition-duration'] = None def getTransitionDuration(self): return self.datain['transition-duration'] class GetTransitionPosition(Baserequests): \"\"\"Get", "the server. :Arguments: *auth* type: String Response to the auth", "= outline_color self.dataout['outline_size'] = outline_size self.dataout['outline_opacity'] = outline_opacity self.dataout['text'] =", "NOT EDIT # # (Generated on 2020-12-20 18:26:33.661372) # from", "when starting the stream. *stream.metadata* type: Object (optional) Adds the", "to perform multiple successive T-Bar moves (e.g. : in an", "sources (vlc and media source) :Returns: *mediaSources* type: Array<Object> Array", "None def getName(self): return self.datain['name'] def getDuration(self): return self.datain['duration'] class", "range (full or partial) \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "(optional) Text content to be displayed. *text_file* type: String (optional)", "class DeleteSceneItem(Baserequests): \"\"\"Deletes a scene item. :Arguments: *scene* type: String", "or `rtmp_common`. *settings* type: Object The actual settings of the", "(0-100). *chatlog* type: boolean Chat log. *chatlog_lines* type: int Chat", "= 'SendCaptions' self.dataout['text'] = text class GetStudioModeStatus(Baserequests): \"\"\"Indicates if Studio", "*name* type: String Name of the currently active scene. *sources*", "8-10) *bounds.x* type: double (optional) The new width of the", "Data URI (if `embedPictureFormat` was specified in the request) *imageFile*", "= None self.dataout['sourceName'] = sourceName def getFilters(self): return self.datain['filters'] class", "self.datain['chatlog'] def getChatlog_lines(self): return self.datain['chatlog_lines'] def getColor(self): return self.datain['color'] def", ":Arguments: *stream* type: Object (optional) Special stream configuration. Please note:", "the source item. *bottom* type: int Pixel position of the", "chain (absolute index positioning) :Arguments: *sourceName* type: String Name of", "= None self.dataout['sourceName'] = sourceName def getMediaDuration(self): return self.datain['mediaDuration'] class", "newName class SetSyncOffset(Baserequests): \"\"\"Set the audio sync offset of a", "Studio Mode is currently enabled. :Returns: *studio_mode* type: boolean Indicates", "*name* type: String Source name. *offset* type: int The audio", "exists as a source, obs-websocket will return an error. :Arguments:", "of the first Desktop Audio capture source. *desktop_2* type: String", "(see \"Authentication\" for more information). \"\"\" def __init__(self, auth): Baserequests.__init__(self)", "self.datain['preview-only'] class StartStopStreaming(Baserequests): \"\"\"Toggle streaming on or off (depending on", "def __init__(self): Baserequests.__init__(self) self.name = 'StopRecording' class PauseRecording(Baserequests): \"\"\"Pause the", "is not set in OBS' settings. Setting this hotkey is", "(optional) Holds data for the font. Ex: `\"font\": { \"face\":", "\"\"\"Sets the coordinates of a specified source item. :Arguments: *scene_name*", "returns 1.0 when not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "to which the filter belongs *filterName* type: String Name of", "(positive or negative) to offset the current media position. \"\"\"", "None self.datain['outline_color'] = None self.datain['outline_size'] = None self.datain['outline_opacity'] = None", ":Returns: *position* type: double current transition position. This value will", "boolean Trigger Alt Key *keyModifiers.control* type: boolean Trigger Control (Ctrl)", "= source class GetAudioActive(Baserequests): \"\"\"Get the audio's active status of", "bounding box. *bounds.y* type: double (optional) The new height of", "Baserequests.__init__(self) self.name = 'MoveSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName", "(optional) Source settings data. *setVisible* type: boolean (optional) Set the", "status of the source. 'true' keeps it in its current", "setVisible): Baserequests.__init__(self) self.name = 'AddSceneItem' self.datain['itemId'] = None self.dataout['sceneName'] =", "an `error` if streaming is already active. :Arguments: *stream* type:", "= 'AddFilterToSource' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterType'] =", "Bold Italic=3, Underline=5, Strikeout=8` *font.size* type: int (optional) Font text", "the \"Save Replay Buffer\" hotkey is not set in OBS'", "*outline_opacity* type: int (optional) Outline opacity (0-100). *text* type: String", "= css self.dataout['width'] = width self.dataout['height'] = height self.dataout['fps'] =", "off by upwards of 50ms. :Arguments: *sourceName* type: String Source", "item belongs to. Defaults to the current scene. *item* type:", "the username for the streaming server. Ignored if `use_auth` is", "self.name = 'TriggerHotkeyByName' self.dataout['hotkeyName'] = hotkeyName class TriggerHotkeyBySequence(Baserequests): \"\"\"Executes hotkey", "as decibels instead of amplitude/mul. \"\"\" def __init__(self, source, volume,", "self.dataout['source'] = source self.dataout['volume'] = volume self.dataout['useDecibel'] = useDecibel class", "in the request) \"\"\" def __init__(self, sourceName=None, embedPictureFormat=None, saveToFilePath=None, fileFormat=None,", "removed *filterName* type: String Name of the filter to remove", "when connecting to the streaming server. *settings.username* type: String (optional)", "monitored and shouldn't be \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "\"unknown\" \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSourcesList' self.datain['sources'] =", "Plus source. :Arguments: *source* type: String Name of the source.", "of pixels cropped off the left of the source before", "source): Baserequests.__init__(self) self.name = 'GetBrowserSourceProperties' self.datain['source'] = None self.datain['is_local_file'] =", "rotation (in degrees). \"\"\" def __init__(self, item, x_scale, y_scale, rotation,", "String Name of the source on which the filter is", "least `embedPictureFormat` or `saveToFilePath` must be specified. Clients can specify", "None self.dataout['sourceName'] = sourceName def getMediaState(self): return self.datain['mediaState'] class GetMediaSourcesList(Baserequests):", "self.datain['parentGroupName'] = None self.datain['groupChildren'] = None self.dataout['item'] = item self.dataout['scene-name']", "current settings of a transition :Arguments: *transitionName* type: String Transition", "self.name = 'DeleteSceneItem' self.dataout['item'] = item self.dataout['scene'] = scene class", "Array<Object> List of transitions. *transitions.*.name* type: String Name of the", "*isRecording* type: boolean Current recording status. *isRecordingPaused* type: boolean Whether", "*fps* type: int Framerate. *shutdown* type: boolean Indicates whether the", "*item* type: Object Scene item to delete (required) *item.name* type:", "transitions available in the frontend's dropdown menu. :Returns: *current_transition* type:", "The monitor type to use. Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\"", "info \"\"\" def __init__(self, outputName): Baserequests.__init__(self) self.name = 'GetOutputInfo' self.datain['outputInfo']", "class GetVideoInfo(Baserequests): \"\"\"Get basic OBS video information :Returns: *baseWidth* type:", "class GetSourcesList(Baserequests): \"\"\"List all sources available in the running OBS", "Baserequests.__init__(self) self.name = 'NextMedia' self.dataout['sourceName'] = sourceName class PreviousMedia(Baserequests): \"\"\"Go", "= 'GetSceneList' self.datain['current-scene'] = None self.datain['scenes'] = None def getCurrentScene(self):", "SetMediaTime(Baserequests): \"\"\"Set the timestamp of a media source. Supports ffmpeg", "'GetSceneItemList' self.datain['sceneName'] = None self.datain['sceneItems'] = None self.dataout['sceneName'] = sceneName", "source. `false` for play, `true` for pause. \"\"\" def __init__(self,", "Baserequests.__init__(self) self.name = 'GetOutputInfo' self.datain['outputInfo'] = None self.dataout['outputName'] = outputName", "specified, tries to guess based on file extension. *compressionQuality* type:", "also sources, you can also provide a scene name. If", "Item name. *x* type: double X coordinate. *y* type: double", "def __init__(self): Baserequests.__init__(self) self.name = 'GetStreamSettings' self.datain['type'] = None self.datain['settings']", "= outputName def getOutputInfo(self): return self.datain['outputInfo'] class StartOutput(Baserequests): \"\"\" Note:", "None self.dataout['source'] = source def getName(self): return self.datain['name'] def getMuted(self):", "String The username to use when accessing the streaming server.", "v25.0.8) :Arguments: *sourceName* type: String Source name. :Returns: *timestamp* type:", "None def getIsRecording(self): return self.datain['isRecording'] def getIsRecordingPaused(self): return self.datain['isRecordingPaused'] def", "Baserequests.__init__(self) self.name = 'GetReplayBufferStatus' self.datain['isReplayBufferActive'] = None def getIsReplayBufferActive(self): return", "class GetTransitionDuration(Baserequests): \"\"\"Get the duration of the currently selected transition", "= sourceName self.dataout['timeOffset'] = timeOffset class GetMediaState(Baserequests): \"\"\"Get the current", "data. *setVisible* type: boolean (optional) Set the created SceneItem as", "= file self.dataout['read_from_file'] = read_from_file self.dataout['font'] = font self.dataout['gradient'] =", "Alignment (\"left\", \"center\", \"right\"). *bk_color* type: int (optional) Background color.", "milliseconds.. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaDuration' self.datain['mediaDuration']", "The new visibility of the source. 'true' shows source, 'false'", "which the filter is added *filterName* type: String Name of", "def __init__(self, sourceName, filterName): Baserequests.__init__(self) self.name = 'GetSourceFilterInfo' self.datain['enabled'] =", "return self.datain['valign'] def getVertical(self): return self.datain['vertical'] class SetTextGDIPlusProperties(Baserequests): \"\"\"Set the", "self.dataout['width'] = width self.dataout['height'] = height def getSourceName(self): return self.datain['sourceName']", "self.datain['profile-name'] = None def getProfileName(self): return self.datain['profile-name'] class ListProfiles(Baserequests): \"\"\"Get", "when accessing the streaming server. Only present if `use_auth` is", "scene's name and source items. :Returns: *name* type: String Name", "self.datain['text_file'] = None self.datain['word_wrap'] = None self.dataout['source'] = source def", "= left self.dataout['right'] = right self.dataout['scene-name'] = scene_name class DeleteSceneItem(Baserequests):", "Defaults to true :Returns: *itemId* type: int ID of the", "__init__(self, position, release=None): Baserequests.__init__(self) self.name = 'SetTBarPosition' self.dataout['position'] = position", "self.datain['from_file'] = None self.datain['log_mode'] = None self.datain['outline'] = None self.datain['text']", "use image export (like the TakeSourceScreenshot request type) formatted as", "scene specific properties of a source. Unspecified properties will remain", "self.dataout['outline_opacity'] = outline_opacity self.dataout['text'] = text self.dataout['valign'] = valign self.dataout['vertical']", "toScene=None): Baserequests.__init__(self) self.name = 'DuplicateSceneItem' self.datain['scene'] = None self.datain['item'] =", "sourceName, timeOffset): Baserequests.__init__(self) self.name = 'ScrubMedia' self.dataout['sourceName'] = sourceName self.dataout['timeOffset']", "self.datain['extents_cx'] = None self.datain['extents_cy'] = None self.datain['file'] = None self.datain['read_from_file']", "to authenticate the client to the server. :Arguments: *auth* type:", "after setting its new position (like a user releasing their", "type: String Video color format *colorSpace* type: String Color space", "this type may cause a feedback loop if it's audio", "field is an object) \"\"\" def __init__(self, item, scene_name=None): Baserequests.__init__(self)", "Fixed to 1.1 for retrocompatibility. *obs_websocket_version* type: String obs-websocket plugin", "(optional) The new clockwise rotation of the item in degrees.", "= 'GetReplayBufferStatus' self.datain['isReplayBufferActive'] = None def getIsReplayBufferActive(self): return self.datain['isReplayBufferActive'] class", "extension included) where the captured image is to be saved.", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartRecording' class StopRecording(Baserequests): \"\"\"Stop", "*transitionName* type: String Name of the current overriding transition. Empty", "configuration. *stream.type* type: String (optional) If specified ensures the type", "parameters to the 'key' of the RTMP stream. Used to", "to uniqueness per scene *items.*.id* type: int (optional) Id of", "type may cause a feedback loop if it's audio is", "through obs-websocket. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartReplayBuffer' class", "'ListOutputs' self.datain['outputs'] = None def getOutputs(self): return self.datain['outputs'] class GetOutputInfo(Baserequests):", "can also provide a scene name. If not provided, the", "self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterType'] = filterType self.dataout['filterSettings']", "scene item in *sourceName* type: String Name of the source", "of media for that source. States: `none`, `playing`, `opening`, `buffering`,", "current transition. :Returns: *position* type: double current transition position. This", "(default: false) \"\"\" def __init__(self, outputName, force=None): Baserequests.__init__(self) self.name =", "of the source. *align* type: String (optional) Text Alignment (\"left\",", "*realm* type: String Identifier to be choosen by the client", "__init__(self, source): Baserequests.__init__(self) self.name = 'GetMute' self.datain['name'] = None self.datain['muted']", "self.datain['local_file'] def getUrl(self): return self.datain['url'] def getCss(self): return self.datain['css'] def", "*extents_cy* type: int Extents cy. *file* type: String File path", "a local file is in use. *local_file* type: String file", "\"Authentication\" for more information). :Returns: *authRequired* type: boolean Indicates whether", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetRecordingStatus' self.datain['isRecording'] = None", "0.0 and 1.0. Note: Transition returns 1.0 when not active.", "self.datain['transitionSettings'] class ReleaseTBar(Baserequests): \"\"\"Release the T-Bar (like a user releasing", "width *outputHeight* type: int Output height *scaleType* type: String Scaling", "May be any String, Numeric, or Boolean field. *stream.settings* type:", "or `saveToFilePath` must be specified. Clients can specify `width` and", "Millisecond offset (positive or negative) to offset the current media", "= 'StopRecording' class PauseRecording(Baserequests): \"\"\"Pause the current recording. Returns an", "OBS will interpret dB values under -100.0 as Inf. Note:", "= None self.datain['align'] = None self.datain['bk_color'] = None self.datain['bk_opacity'] =", "type: double Width of the bounding box. *bounds.y* type: double", "'GetTextGDIPlusProperties' self.datain['source'] = None self.datain['align'] = None self.datain['bk_color'] = None", "def getName(self): return self.datain['name'] def getSources(self): return self.datain['sources'] class GetSceneList(Baserequests):", "current) scene *sceneItems* type: Array<Object> Array of scene items *sceneItems.*.itemId*", "__init__(self, sourceName): Baserequests.__init__(self) self.name = 'NextMedia' self.dataout['sourceName'] = sourceName class", "'DisableStudioMode' class ToggleStudioMode(Baserequests): \"\"\"Toggles Studio Mode (depending on the current", "getMediaSources(self): return self.datain['mediaSources'] class CreateSource(Baserequests): \"\"\"Create a source and add", "preserved if only one of these two parameters is specified.", "filterName self.dataout['filterEnabled'] = filterEnabled class GetAudioMonitorType(Baserequests): \"\"\"Get the audio monitoring", "configured special sources like Desktop Audio and Mic/Aux sources. :Returns:", "window. *geometry* type: String (Optional) Size and position of the", "return self.datain['bounds'] def getSourceWidth(self): return self.datain['sourceWidth'] def getSourceHeight(self): return self.datain['sourceHeight']", "source. Default request format uses mul, NOT SLIDER PERCENTAGE. :Arguments:", "Coordinates are relative to the item's parent (the scene or", "of objects with name and/or id specified. Id preferred due", "items share sources within the scene. \"\"\" def __init__(self, items,", "key of the stream. *settings.use_auth* type: boolean Indicates whether authentication", "getBk_color(self): return self.datain['bk_color'] def getBk_opacity(self): return self.datain['bk_opacity'] def getChatlog(self): return", "type: String Name of the current overriding transition. Empty string", "type: String Path of the recording folder. \"\"\" def __init__(self,", "type, all settings are required. Returns the full settings of", "int The number of pixels cropped off the bottom of", "of the RTMP stream. Used to pass data to the", "self.datain['read_from_file'] def getFont(self): return self.datain['font'] def getGradient(self): return self.datain['gradient'] def", "*bounds.x* type: double (optional) The new width of the bounding", "name. :Returns: *audioActive* type: boolean Audio active status of the", "scene item belongs to. Defaults to the currently active scene.", "= 'GetCurrentScene' self.datain['name'] = None self.datain['sources'] = None def getName(self):", "boolean (optional) Outline. *text* type: String (optional) Text content to", "the source item. *left* type: int Pixel position of the", "keys. A single key combination might trigger multiple hotkey routines", "def __init__(self): Baserequests.__init__(self) self.name = 'GetRecordingFolder' self.datain['rec-folder'] = None def", "of the current overriding transition. Empty string if no override", "and 1.0. Note: Transition returns 1.0 when not active. \"\"\"", "= None self.datain['colorSpace'] = None self.datain['colorRange'] = None def getBaseWidth(self):", "__init__(self, source, offset): Baserequests.__init__(self) self.name = 'SetSyncOffset' self.dataout['source'] = source", "specified file. *log_mode* type: boolean (optional) Chat log. *outline* type:", "current recording folder. :Returns: *rec_folder* type: String Path of the", "source name *mediaSources.*.sourceKind* type: String Unique source internal type (a.k.a", "or omitted, opens a window. *geometry* type: String (Optional) Size", "override on a scene. :Arguments: *sceneName* type: String Name of", "log_mode=None, outline=None, text=None, text_file=None, word_wrap=None): Baserequests.__init__(self) self.name = 'SetTextFreetype2Properties' self.dataout['source']", "self.datain['recordingFilename'] class StartStopRecording(Baserequests): \"\"\"Toggle recording on or off (depending on", "*auth* type: String Response to the auth challenge (see \"Authentication\"", "combination might trigger multiple hotkey routines depending on user settings", "If the currently configured stream type does not match the", "getOutputInfo(self): return self.datain['outputInfo'] class StartOutput(Baserequests): \"\"\" Note: Controlling outputs is", "inject. *width* type: int Width. *height* type: int Height. *fps*", "getTimestamp(self): return self.datain['timestamp'] class SetMediaTime(Baserequests): \"\"\"Set the timestamp of a", "routines depending on user settings :Arguments: *keyId* type: String Main", "added *setVisible* type: boolean Whether to make the sceneitem visible", "(almost the same info as provided in OBS' stats window)", ":Arguments: *fromScene* type: String (optional) Name of the scene to", "class GetSceneTransitionOverride(Baserequests): \"\"\"Get the current scene transition override. :Arguments: *sceneName*", "\"\"\"Executes hotkey routine, identified by hotkey unique name :Arguments: *hotkeyName*", "playing state of a media source. Supports ffmpeg and vlc", "self.dataout['sourceName'] = sourceName def getAudioActive(self): return self.datain['audioActive'] class SetSourceName(Baserequests): \"\"\"", "self.dataout['y'] = y self.dataout['scene-name'] = scene_name class SetSceneItemTransform(Baserequests): \"\"\"Set the", "= sourceName class PreviousMedia(Baserequests): \"\"\"Go to the previous media item", "of the specified source :Arguments: *sourceName* type: String Source name.", "*crop.left* type: int The number of pixels cropped off the", "return self.datain['itemId'] class DuplicateSceneItem(Baserequests): \"\"\"Duplicates a scene item. :Arguments: *fromScene*", "Text vertical alignment (\"top\", \"center\", \"bottom\"). *vertical* type: boolean Vertical", "= 'TakeSourceScreenshot' self.datain['sourceName'] = None self.datain['img'] = None self.datain['imageFile'] =", "the new source to. *sourceSettings* type: Object (optional) Source settings", "GetSpecialSources(Baserequests): \"\"\"Get configured special sources like Desktop Audio and Mic/Aux", "self.dataout['bottom'] = bottom self.dataout['left'] = left self.dataout['right'] = right self.dataout['scene-name']", "given stream type, all settings must be specified in the", "is automatic, 1 is smallest file/most compression, 100 is largest", "= None self.datain['from_file'] = None self.datain['log_mode'] = None self.datain['outline'] =", "self.datain['gradient_color'] def getGradient_dir(self): return self.datain['gradient_dir'] def getGradient_opacity(self): return self.datain['gradient_opacity'] def", "__init__(self, transitionName, transitionSettings): Baserequests.__init__(self) self.name = 'SetTransitionSettings' self.datain['transitionSettings'] = None", "type: int Width. *height* type: int Height. *fps* type: int", "render self.dataout['scene-name'] = scene_name class SetSceneItemPosition(Baserequests): \"\"\"Sets the coordinates of", "to disk. This is basically the same as triggering the", "color. *gradient_dir* type: float (optional) Gradient direction. *gradient_opacity* type: int", "def __init__(self, source): Baserequests.__init__(self) self.name = 'GetBrowserSourceProperties' self.datain['source'] = None", ":Arguments: *sourceName* type: String Name of the source to which", "\"\"\" def __init__(self, sourceName, filterName, movementType): Baserequests.__init__(self) self.name = 'MoveSourceFilter'", "def getVersion(self): return self.datain['version'] def getObsWebsocketVersion(self): return self.datain['obs-websocket-version'] def getObsStudioVersion(self):", "omitted, opens a window. *geometry* type: String (Optional) Size and", "of the source. Between `0.0` and `20.0` if using mul,", "Source filter name *filterEnabled* type: Boolean New filter state \"\"\"", "class SetSourceSettings(Baserequests): \"\"\"Set settings of the specified source. :Arguments: *sourceName*", "True if source of this type provide frames asynchronously *types.*.caps.hasVideo*", "\"\"\"Set the audio sync offset of a specified source. :Arguments:", "type: boolean Vertical text enabled. \"\"\" def __init__(self, source): Baserequests.__init__(self)", "(optional) Source name. Note that, since scenes are also sources,", "settings incompatible with the actual source's type. *sourceSettings* type: Object", "type: String Main key identifier (e.g. `OBS_KEY_A` for key \"A\").", "source self.dataout['render'] = render self.dataout['scene-name'] = scene_name class SetSceneItemPosition(Baserequests): \"\"\"Sets", "or newer. :Arguments: *type* type: String (Optional) Type of projector:", "True if interaction with this sources of this type is", "which the filter belongs *filterName* type: String Name of the", "type *filters.*.name* type: String Filter name *filters.*.settings* type: Object Filter", "the currently selected transition if supported. :Returns: *transition_duration* type: int", "and `20.0` if using mul, under `26.0` if using dB.", "mul, under `26.0` if using dB. *muted* type: boolean Indicates", "box. *bounds.y* type: double Height of the bounding box. *sourceWidth*", "of a specified source item. :Arguments: *scene_name* type: String (optional)", "Display name of the source type *types.*.type* type: String Type.", "with name and/or id specified. Id preferred due to uniqueness", "def getSceneCollections(self): return self.datain['scene-collections'] class GetSceneItemList(Baserequests): \"\"\"Get a list of", "self.datain['sources'] class SetPreviewScene(Baserequests): \"\"\"Set the active preview scene. Will return", "function). *gradient* type: boolean (optional) Gradient enabled. *gradient_color* type: int", "getUrl(self): return self.datain['url'] def getCss(self): return self.datain['css'] def getWidth(self): return", "Default `true` :Returns: *itemId* type: int Numerical ID of the", "double Width of the bounding box. *bounds.y* type: double Height", "transition. *duration* type: int (optional) Transition duration (in milliseconds) if", "visible. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetBrowserSourceProperties' self.datain['source']", "identifiers [here](https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h) *keyModifiers* type: Object (Optional) Optional key modifiers object.", "GetCurrentProfile(Baserequests): \"\"\"Get the name of the current profile. :Returns: *profile_name*", "def __init__(self): Baserequests.__init__(self) self.name = 'ListSceneCollections' self.datain['scene-collections'] = None def", "of the transition (in milliseconds). \"\"\" def __init__(self, duration): Baserequests.__init__(self)", "choosen by the client *data* type: Object User-defined data \"\"\"", "Name of the first Mic/Aux input source. *mic_2* type: String", "query string parameters to the 'key' of the RTMP stream.", "sourceName): Baserequests.__init__(self) self.name = 'StopMedia' self.dataout['sourceName'] = sourceName class NextMedia(Baserequests):", "*valign* type: String (optional) Text vertical alignment (\"top\", \"center\", \"bottom\").", "the following: \"input\", \"filter\", \"transition\", \"scene\" or \"unknown\" \"\"\" def", "type: String (optional) Url. *css* type: String (optional) CSS to", "class SetTextGDIPlusProperties(Baserequests): \"\"\"Set the current properties of a Text GDI", "sourceName self.dataout['filterName'] = filterName self.dataout['filterEnabled'] = filterEnabled class GetAudioMonitorType(Baserequests): \"\"\"Get", "Baserequests.__init__(self) self.name = 'GetRecordingStatus' self.datain['isRecording'] = None self.datain['isRecordingPaused'] = None", "boolean Indicates that a local file is in use. *local_file*", "None self.datain['valign'] = None self.datain['vertical'] = None self.dataout['source'] = source", "NAme of the third Mic/Aux input source. \"\"\" def __init__(self):", "info *item.id* type: int New item ID *item.name* type: String", "is added *filterName* type: String Name of the new filter", "*imageFile* type: String Absolute path to the saved image file", "\"\"\"Get the current streaming server settings. :Returns: *type* type: String", "type: String (optional) Name of the scene the source item", "type: boolean (optional) Output volume in decibels of attenuation instead", "self.name = 'SetFilenameFormatting' self.dataout['filename-formatting'] = filename_formatting class GetFilenameFormatting(Baserequests): \"\"\"Get the", "class StopMedia(Baserequests): \"\"\"Stop a media source. Supports ffmpeg and vlc", "OBS v25.0.8) Note: For some reason, for the first 5", "double The x position of the source from the left.", "Name of the scene to get the list of scene", "sourceName self.dataout['sourceKind'] = sourceKind self.dataout['sceneName'] = sceneName self.dataout['sourceSettings'] = sourceSettings", "of this type may cause a feedback loop if it's", "the requested scene. :Arguments: *scene* type: String (optional) Name of", "def __init__(self): Baserequests.__init__(self) self.name = 'StartRecording' class StopRecording(Baserequests): \"\"\"Stop recording.", "Replay Buffer to disk. This is basically the same as", "of the stream. *stream.settings.use_auth* type: boolean (optional) Indicates whether authentication", "from. Defaults to the current scene. *toScene* type: String (optional)", "\"\"\"Get information about a single output :Arguments: *outputName* type: String", "self.datain['valign'] def getVertical(self): return self.datain['vertical'] class SetTextGDIPlusProperties(Baserequests): \"\"\"Set the current", "Whether to pause or play the source. `false` for play,", "by scene basis. *items.*.name* type: String (optional) Name of a", "the duration of the currently selected transition if supported. :Arguments:", "list string \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetVersion' self.datain['version']", "of the scene the scene item belongs to. Defaults to", "double Height scale factor. *rotation* type: double Source item rotation", "*outputName* type: String Output name :Returns: *outputInfo* type: Output Output", "self.dataout['sourceName'] = sourceName self.dataout['newName'] = newName class SetSyncOffset(Baserequests): \"\"\"Set the", "= None self.dataout['transitionName'] = transitionName def getTransitionSettings(self): return self.datain['transitionSettings'] class", "chatlog=None, chatlog_lines=None, color=None, extents=None, extents_cx=None, extents_cy=None, file=None, read_from_file=None, font=None, gradient=None,", "String Scaling method used if output size differs from base", "__init__(self, sourceName): Baserequests.__init__(self) self.name = 'RestartMedia' self.dataout['sourceName'] = sourceName class", "(e.g. : \"Method1,Method2,Method3\"). *supported_image_export_formats* type: String List of supported formats", "are available from `GetSourceTypesList`. :Arguments: *sourceName* type: String Name of", "parameters as encoded query string parameters to the 'key' of", "self.datain['current-transition'] def getTransitions(self): return self.datain['transitions'] class GetCurrentTransition(Baserequests): \"\"\"Get the name", "name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'NextMedia' self.dataout['sourceName']", "Source name. *is_local_file* type: boolean Indicates that a local file", ":Arguments: *scene* type: String (optional) Name of the scene the", "return self.datain['fps'] def getShutdown(self): return self.datain['shutdown'] class SetBrowserSourceProperties(Baserequests): \"\"\"Set current", "[here](https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h) *keyModifiers* type: Object (Optional) Optional key modifiers object. False", "String (Optional) Name of the source or scene to be", "by Qt's Image module) *saveToFilePath* type: String (optional) Full file", "getFps(self): return self.datain['fps'] def getVideoFormat(self): return self.datain['videoFormat'] def getColorSpace(self): return", "*toScene* type: String (optional) Name of the scene to create", "the scene to get the list of scene items from.", "return self.datain['gradient'] def getGradient_color(self): return self.datain['gradient_color'] def getGradient_dir(self): return self.datain['gradient_dir']", "within the scene. \"\"\" def __init__(self, items, scene=None): Baserequests.__init__(self) self.name", "file self.dataout['read_from_file'] = read_from_file self.dataout['font'] = font self.dataout['gradient'] = gradient", "set. \"\"\" def __init__(self, filename_formatting): Baserequests.__init__(self) self.name = 'SetFilenameFormatting' self.dataout['filename-formatting']", "*mediaState* type: String The media state of the provided source.", "Font face. *font.flags* type: int Font text styling flag. `Bold=1,", "start of the media. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name", "inject. *width* type: int (optional) Width. *height* type: int (optional)", "this type provide audio *types.*.caps.canInteract* type: Boolean True if interaction", "*item.id* type: int (optional) Scene Item ID (if the `item`", "getMuted(self): return self.datain['muted'] class SetVolume(Baserequests): \"\"\"Set the volume of the", "elapsed since streaming started (only present if currently streaming). *rec_timecode*", "the source before scaling. *crop.bottom* type: int (optional) The new", "a single output :Arguments: *outputName* type: String Output name :Returns:", "`error` if streaming is already active. :Arguments: *stream* type: Object", "= None self.datain['color1'] = None self.datain['color2'] = None self.datain['custom_width'] =", "frames asynchronously *types.*.caps.hasVideo* type: Boolean True if sources of this", "\"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int (optional) The new alignment", "to copy the item from. Defaults to the current scene.", "filename formatting string. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetFilenameFormatting'", "\"\"\"List existing outputs :Returns: *outputs* type: Array<Output> Outputs list \"\"\"", "if sources of this type should not be fully duplicated", "(or any other value supported by Qt's Image module) *saveToFilePath*", "be ommitted *keyModifiers.shift* type: boolean Trigger Shift Key *keyModifiers.alt* type:", "getWord_wrap(self): return self.datain['word_wrap'] class SetTextFreetype2Properties(Baserequests): \"\"\"Set the current properties of", "\"\"\"List available scene collections :Returns: *scene_collections* type: Array<String> Scene collections", "source :Arguments: *sourceName* type: String Source name *filterName* type: String", "settings object. *settings.server* type: String The publish URL. *settings.key* type:", "*sourceName* type: String Source name. :Returns: *mediaState* type: String The", "StartStopStreaming(Baserequests): \"\"\"Toggle streaming on or off (depending on the current", "'GetMediaState' self.datain['mediaState'] = None self.dataout['sourceName'] = sourceName def getMediaState(self): return", "the Replay Buffer. Will return an `error` if the Replay", "self.dataout['sourceName'] = sourceName self.dataout['sourceSettings'] = sourceSettings self.dataout['sourceType'] = sourceType def", "int (optional) Height. *fps* type: int (optional) Framerate. *shutdown* type:", "String Type of the scene item's source. Either `input`, `group`,", "class ReleaseTBar(Baserequests): \"\"\"Release the T-Bar (like a user releasing their", "= 'StartStreaming' self.dataout['stream'] = stream class StopStreaming(Baserequests): \"\"\"Stop streaming. Will", "\"\"\"Transitions the currently previewed scene to the main output. Will", "for YUV *colorRange* type: String Color range (full or partial)", "= 'GetSourceTypesList' self.datain['types'] = None def getTypes(self): return self.datain['types'] class", "String Name of the currently active profile. \"\"\" def __init__(self):", "'GetVersion' self.datain['version'] = None self.datain['obs-websocket-version'] = None self.datain['obs-studio-version'] = None", "remove \"\"\" def __init__(self, sourceName, filterName): Baserequests.__init__(self) self.name = 'RemoveFilterFromSource'", "2020-12-20 18:26:33.661372) # from .base_classes import Baserequests class GetVersion(Baserequests): \"\"\"Returns", "type: String Type of bounding box. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\",", "class GetSourceFilters(Baserequests): \"\"\"List filters applied to a source :Arguments: *sourceName*", "Studio Mode (depending on the current state of studio mode).", "you add a source into a scene. :Arguments: *sceneName* type:", "self.datain['scene'] = None self.datain['item'] = None self.dataout['item'] = item self.dataout['fromScene']", "source. :Arguments: *sourceName* type: String Source name. *sourceType* type: String", "return self.datain['sourceName'] def getImg(self): return self.datain['img'] def getImageFile(self): return self.datain['imageFile']", "String (optional) Name of the first Desktop Audio capture source.", "Framerate. *shutdown* type: boolean Indicates whether the source should be", "sync offset (in nanoseconds). \"\"\" def __init__(self, source, offset): Baserequests.__init__(self)", "a group) \"\"\" def __init__(self, item, scene_name=None): Baserequests.__init__(self) self.name =", "a source. Unspecified properties will remain unchanged. Coordinates are relative", "GetSourcesList(Baserequests): \"\"\"List all sources available in the running OBS instance", "type does not match the given stream type, all settings", "belongs *filterName* type: String Name of the filter to reorder", "\"\"\"Set the active preview scene. Will return an `error` if", "SetSceneTransitionOverride(Baserequests): \"\"\"Set a scene to use a specific transition override.", "self.name = 'GetMediaSourcesList' self.datain['mediaSources'] = None def getMediaSources(self): return self.datain['mediaSources']", "Item ID. :Returns: *scene* type: String Name of the scene", "Any options not passed will remain unchanged. Returns the updated", "not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopStreaming' class", "if you called `SetTBarPosition` with the `release` parameter set to", "return self.datain['recordTimecode'] def getRecordingFilename(self): return self.datain['recordingFilename'] class StartStopRecording(Baserequests): \"\"\"Toggle recording", "int (optional) Gradient color. *gradient_dir* type: float (optional) Gradient direction.", "self.dataout['item'] = item self.dataout['x'] = x self.dataout['y'] = y self.dataout['scene-name']", "\"\"\" def __init__(self, sourceName, filterName, filterEnabled): Baserequests.__init__(self) self.name = 'SetSourceFilterVisibility'", "before scaling. *crop.right* type: int The number of pixels cropped", "crop=None, visible=None, locked=None, bounds=None): Baserequests.__init__(self) self.name = 'SetSceneItemProperties' self.dataout['item'] =", "type: double Frames rendered per second *videoFormat* type: String Video", "an `error` if Studio Mode is not enabled. :Arguments: *scene_name*", "in a specified scene. :Arguments: *scene_name* type: String (optional) Name", "class StartStopStreaming(Baserequests): \"\"\"Toggle streaming on or off (depending on the", "Font text size. *font.style* type: String Font Style (unknown function).", "current properties for a Browser Source. :Arguments: *source* type: String", "type, settings, save): Baserequests.__init__(self) self.name = 'SetStreamSettings' self.dataout['type'] = type", "name. *offset* type: int The audio sync offset (in nanoseconds).", "type: int Pixel position of the left of the source", "2 source. :Arguments: *source* type: String Source name. *color1* type:", "def getSourceName(self): return self.datain['sourceName'] def getSourceType(self): return self.datain['sourceType'] def getSourceSettings(self):", "= 'SetSourceFilterSettings' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterSettings'] =", "Name of the scene to copy the item from. Defaults", "width (base source width multiplied by the horizontal scaling factor)", "return self.datain['scenes'] class CreateScene(Baserequests): \"\"\"Create a new scene scene. :Arguments:", "getFile(self): return self.datain['file'] def getRead_from_file(self): return self.datain['read_from_file'] def getFont(self): return", "class SetCurrentScene(Baserequests): \"\"\"Switch to the specified scene. :Arguments: *scene_name* type:", "encoded query string parameters to the 'key' of the RTMP", "= 'NextMedia' self.dataout['sourceName'] = sourceName class PreviousMedia(Baserequests): \"\"\"Go to the", "(optional) Name of the first Mic/Aux input source. *mic_2* type:", "type: int (optional) Screenshot width. Defaults to the source's base", "geometry, name): Baserequests.__init__(self) self.name = 'OpenProjector' self.dataout['type'] = type self.dataout['monitor']", "degrees. *scale.x* type: double (optional) The new x scale of", "monitor type to use. Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def", "String Source name. *muted* type: boolean Mute status of the", "the specified file. *font* type: Object Holds data for the", "the chain \"\"\" def __init__(self, sourceName, filterName, newIndex): Baserequests.__init__(self) self.name", "def getRead_from_file(self): return self.datain['read_from_file'] def getFont(self): return self.datain['font'] def getGradient(self):", "getFps(self): return self.datain['fps'] def getShutdown(self): return self.datain['shutdown'] class SetBrowserSourceProperties(Baserequests): \"\"\"Set", "self.dataout['transitionDuration'] = transitionDuration class RemoveSceneTransitionOverride(Baserequests): \"\"\"Remove any transition override on", "of available request types, formatted as a comma-separated list string", "method used if output size differs from base size *fps*", "vlc media sources (as of OBS v25.0.8) :Arguments: *sourceName* type:", "return self.datain['outputWidth'] def getOutputHeight(self): return self.datain['outputHeight'] def getScaleType(self): return self.datain['scaleType']", "type: int (optional) The new amount of pixels cropped off", "source. Available source types along with their settings properties are", "experimental feature of obs-websocket. Some plugins which add outputs to", "of the third Mic/Aux input source. \"\"\" def __init__(self): Baserequests.__init__(self)", "def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentScene' self.datain['name'] = None self.datain['sources']", "GetVideoInfo(Baserequests): \"\"\"Get basic OBS video information :Returns: *baseWidth* type: int", "Type of bounding box. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\",", "}` *font.face* type: String (optional) Font face. *font.flags* type: int", "extents_cy self.dataout['file'] = file self.dataout['read_from_file'] = read_from_file self.dataout['font'] = font", "values. *useDecibel* type: boolean (optional) Interperet `volume` data as decibels", "type: String (optional) Absolute path to the recording file (only", "color2=None, custom_width=None, drop_shadow=None, font=None, from_file=None, log_mode=None, outline=None, text=None, text_file=None, word_wrap=None):", "Defaults to the current duration specified in the UI if", "self.datain['obs-websocket-version'] def getObsStudioVersion(self): return self.datain['obs-studio-version'] def getAvailableRequests(self): return self.datain['available-requests'] def", "self.name = 'GetStreamSettings' self.datain['type'] = None self.datain['settings'] = None def", "control in your User Interface), set `release` to false and", "int Framerate. *shutdown* type: boolean Indicates whether the source should", "The actual settings of the stream. *settings.server* type: String (optional)", "Font text size. *font.style* type: String (optional) Font Style (unknown", "active scene. *sources* type: Array<SceneItem> Ordered list of the current", "None self.datain['color'] = None self.datain['extents'] = None self.datain['extents_cx'] = None", "type: Boolean Filter status (enabled or not) *filters.*.type* type: String", "add outputs to OBS may not function properly when they", "\"\"\" def __init__(self, scene_name): Baserequests.__init__(self) self.name = 'SetPreviewScene' self.dataout['scene-name'] =", "as a comma-separated list string \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "single output :Arguments: *outputName* type: String Output name :Returns: *outputInfo*", "= filterName self.dataout['newIndex'] = newIndex class MoveSourceFilter(Baserequests): \"\"\"Move a filter", "String Name of the scene to create the scene item", "a source :Arguments: *sourceName* type: String Source name :Returns: *filters*", "the filename formatting string :Arguments: *filename_formatting* type: String Filename formatting", "uses mul format, NOT SLIDER PERCENTAGE. :Arguments: *source* type: String", "= visible self.dataout['locked'] = locked self.dataout['bounds'] = bounds class ResetSceneItem(Baserequests):", "projector on. If -1 or omitted, opens a window. *geometry*", "return self.datain['log_mode'] def getOutline(self): return self.datain['outline'] def getText(self): return self.datain['text']", "= None self.datain['rec-timecode'] = None self.datain['preview-only'] = None def getStreaming(self):", "self.name = 'GetSourcesList' self.datain['sources'] = None def getSources(self): return self.datain['sources']", "Object Default settings of this source type *types.*.caps* type: Object", "Interperet `volume` data as decibels instead of amplitude/mul. \"\"\" def", "*x_scale* type: double Width scale factor. *y_scale* type: double Height", "plugin and the API. :Returns: *version* type: double OBSRemote compatible", "self.name = 'SetSceneItemProperties' self.dataout['item'] = item self.dataout['scene-name'] = scene_name self.dataout['position']", "class GetCurrentProfile(Baserequests): \"\"\"Get the name of the current profile. :Returns:", "(optional) Word wrap. \"\"\" def __init__(self, source, color1=None, color2=None, custom_width=None,", "you expect a specific settings schema. :Returns: *sourceName* type: String", "Format to save the image file as (one of the", "String Scene collection name \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "= source self.dataout['color1'] = color1 self.dataout['color2'] = color2 self.dataout['custom_width'] =", "StartReplayBuffer(Baserequests): \"\"\"Start recording into the Replay Buffer. Will return an", ":Returns: *sourceName* type: String Source name *img* type: String Image", "if currently recording). *recordingFilename* type: String (optional) Absolute path to", "= rec_folder class GetRecordingFolder(Baserequests): \"\"\"Get the path of the current", "is already active or if the \"Save Replay Buffer\" hotkey", "(optional) Outline. *text* type: String (optional) Text content to be", "Object Updated source settings \"\"\" def __init__(self, sourceName, sourceSettings, sourceType=None):", "the \"Save Replay Buffer\" hotkey. Will return an `error` if", "new clockwise rotation of the item in degrees. *scale.x* type:", "sourceName class StopMedia(Baserequests): \"\"\"Stop a media source. Supports ffmpeg and", "gradient_opacity self.dataout['outline'] = outline self.dataout['outline_color'] = outline_color self.dataout['outline_size'] = outline_size", "SetSyncOffset(Baserequests): \"\"\"Set the audio sync offset of a specified source.", "= None self.datain['salt'] = None def getAuthRequired(self): return self.datain['authRequired'] def", "Defaults to the current scene. *toScene* type: String (optional) Name", "with their settings properties are available from `GetSourceTypesList`. :Arguments: *sourceName*", "\"top\" or \"bottom\". \"\"\" def __init__(self, sourceName, filterName, movementType): Baserequests.__init__(self)", "the hotkey, as defined when registering the hotkey (e.g. \"ReplayBuffer.Save\")", "the values provided in the `supported-image-export-formats` response field of `GetVersion`).", "= source self.dataout['is_local_file'] = is_local_file self.dataout['local_file'] = local_file self.dataout['url'] =", "String Name of the filter to reconfigure *filterSettings* type: Object", "local file is in use. *local_file* type: String file path.", "type: String (optional) CSS to inject. *width* type: int (optional)", "dropdown menu. :Returns: *name* type: String Name of the selected", "Italic=3, Underline=5, Strikeout=8` *font.size* type: int (optional) Font text size.", "the RTMP stream. Used to pass data to the RTMP", "must be specified. Clients can specify `width` and `height` parameters", "dB. *muted* type: boolean Indicates whether the source is muted.", "*filters* type: Array<Object> List of filters for the specified source", "a specified source. :Arguments: *sourceName* type: String Source name. :Returns:", "a format different from `pictureFormat`. Can be a relative path.", "int (optional) Screenshot width. Defaults to the source's base width.", "String Source name. *monitorType* type: String The monitor type to", "If specified ensures the type of stream matches the given", "= None self.datain['mic-2'] = None self.datain['mic-3'] = None def getDesktop1(self):", "source. Unspecified properties will remain unchanged. Coordinates are relative to", "Filter name *settings* type: Object Filter settings \"\"\" def __init__(self,", "to create the scene item in *sourceName* type: String Name", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionPosition' self.datain['position'] = None", "Indicates whether the source should be shutdown when not visible.", "the timestamp to. \"\"\" def __init__(self, sourceName, timestamp): Baserequests.__init__(self) self.name", "in use. *local_file* type: String (optional) file path. *url* type:", "Possible values: 'rtmp_custom' or 'rtmp_common'. *settings* type: Object Stream settings", "opacity (0-100). *chatlog* type: boolean Chat log. *chatlog_lines* type: int", "`playing`, `opening`, `buffering`, `paused`, `stopped`, `ended`, `error`, `unknown` \"\"\" def", "enabled. :Arguments: *scene_name* type: String The name of the scene", "type: int Gradient opacity (0-100). *outline* type: boolean Outline. *outline_color*", "self.datain['desktop-1'] = None self.datain['desktop-2'] = None self.datain['mic-1'] = None self.datain['mic-2']", "self.datain['mic-3'] = None def getDesktop1(self): return self.datain['desktop-1'] def getDesktop2(self): return", "= 'GetSceneTransitionOverride' self.datain['transitionName'] = None self.datain['transitionDuration'] = None self.dataout['sceneName'] =", "of the bounding box. (0-2, 4-6, 8-10) *bounds.x* type: double", "type: int Pixel position of the right of the source", "Gradient direction. *gradient_opacity* type: int (optional) Gradient opacity (0-100). *outline*", "int Duration of the current transition (in milliseconds). \"\"\" def", "type: String Name of the filter to remove \"\"\" def", "only one of these two parameters is specified. :Arguments: *sourceName*", "be partial) :Returns: *transitionSettings* type: Object Updated transition settings \"\"\"", "profile. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentProfile' self.datain['profile-name'] =", "the scene item belongs to. Defaults to the currently active", "self.datain['isRecordingPaused'] def getRecordTimecode(self): return self.datain['recordTimecode'] def getRecordingFilename(self): return self.datain['recordingFilename'] class", "GetSourceSettings(Baserequests): \"\"\"Get settings of the specified source :Arguments: *sourceName* type:", "be in a format different from `pictureFormat`. Can be a", "= 'GetStats' self.datain['stats'] = None def getStats(self): return self.datain['stats'] class", "state of the replay buffer). \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "\"center\", \"bottom\"). *vertical* type: boolean Vertical text enabled. \"\"\" def", "= 'GetSourcesList' self.datain['sources'] = None def getSources(self): return self.datain['sources'] class", "type: String (optional) Format to save the image file as", "'RestartMedia' self.dataout['sourceName'] = sourceName class StopMedia(Baserequests): \"\"\"Stop a media source.", "self.datain['mic-1'] def getMic2(self): return self.datain['mic-2'] def getMic3(self): return self.datain['mic-3'] class", "recording). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetRecordingStatus' self.datain['isRecording'] =", "*filterName* type: String Name of the filter to reorder *newIndex*", "type: String Non-unique internal source type ID *types.*.displayName* type: String", "source name. \"\"\" def __init__(self, sourceName, newName): Baserequests.__init__(self) self.name =", "sourceName def getMediaState(self): return self.datain['mediaState'] class GetMediaSourcesList(Baserequests): \"\"\"List the media", "not active or not paused. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "type: String (optional) \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetAuthRequired'", "True if sources of this type should not be fully", "return self.datain['current-scene'] def getScenes(self): return self.datain['scenes'] class CreateScene(Baserequests): \"\"\"Create a", "the media is playing, the total duration can be off", "*muted* type: boolean Indicates whether the source is muted. \"\"\"", "= source self.dataout['render'] = render self.dataout['scene-name'] = scene_name class SetSceneItemPosition(Baserequests):", "self.dataout['source'] = source def getName(self): return self.datain['name'] def getOffset(self): return", ":Returns: *name* type: String The name of the active preview", "Array<Object> List of filters for the specified source *filters.*.enabled* type:", "self.dataout['volume'] = volume self.dataout['useDecibel'] = useDecibel class GetMute(Baserequests): \"\"\"Get the", "If the source is muted. *locked* type: bool If the", "Note: The OBS volume sliders only reach a maximum of", "'SetCurrentScene' self.dataout['scene-name'] = scene_name class GetCurrentScene(Baserequests): \"\"\"Get the current scene's", "type: String Unique name of the hotkey, as defined when", "Outline. *text* type: String (optional) Text content to be displayed.", "def getStreaming(self): return self.datain['streaming'] def getRecording(self): return self.datain['recording'] def getStreamTimecode(self):", "status. *stream_timecode* type: String (optional) Time elapsed since streaming started", "avoid settings a set of settings incompatible with the actual", "of keys. A single key combination might trigger multiple hotkey", "its list of sources. Will return an `error` if Studio", "= None def getSources(self): return self.datain['sources'] class GetSourceTypesList(Baserequests): \"\"\"Get a", "ID *item.name* type: String New item name \"\"\" def __init__(self,", "Baserequests.__init__(self) self.name = 'SetAudioMonitorType' self.dataout['sourceName'] = sourceName self.dataout['monitorType'] = monitorType", "the source. `false` for play, `true` for pause. \"\"\" def", "Outline opacity (0-100). *text* type: String Text content to be", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStreamingStatus' self.datain['streaming'] = None", "on. If -1 or omitted, opens a window. *geometry* type:", "enabled. :Returns: *name* type: String The name of the active", "the position of the current transition. :Returns: *position* type: double", "*source* type: String Source name. :Returns: *source* type: String Source", "def __init__(self, outputName): Baserequests.__init__(self) self.name = 'GetOutputInfo' self.datain['outputInfo'] = None", ":Returns: *baseWidth* type: int Base (canvas) width *baseHeight* type: int", "if `SetRecordingFolder` is called while a recording is in progress,", "getMediaState(self): return self.datain['mediaState'] class GetMediaSourcesList(Baserequests): \"\"\"List the media state of", "of the active preview scene. *sources* type: Array<SceneItem> \"\"\" def", "'GetCurrentTransition' self.datain['name'] = None self.datain['duration'] = None def getName(self): return", "type (a.k.a kind) *sources.*.type* type: String Source type. Value is", "scene. *toScene* type: String (optional) Name of the scene to", "active status of a specified source. :Arguments: *sourceName* type: String", "be between 0.0 and 1.0. Note: Transition returns 1.0 when", "(optional) Screenshot height. Defaults to the source's base height. :Returns:", "'TakeSourceScreenshot' self.datain['sourceName'] = None self.datain['img'] = None self.datain['imageFile'] = None", "scene specific properties of the specified source item. Coordinates are", "current scene. *item* type: Object Scene item to delete (required)", "def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'PreviousMedia' self.dataout['sourceName'] = sourceName", "*extents_cx* type: int Extents cx. *extents_cy* type: int Extents cy.", "`20.0` if using mul, under `26.0` if using dB. *muted*", "self.datain['gradient_color'] = None self.datain['gradient_dir'] = None self.datain['gradient_opacity'] = None self.datain['outline']", "return self.datain['volume'] def getMuted(self): return self.datain['muted'] class SetVolume(Baserequests): \"\"\"Set the", "type: Object Filter settings \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name", "def __init__(self): Baserequests.__init__(self) self.name = 'GetSceneList' self.datain['current-scene'] = None self.datain['scenes']", "Baserequests.__init__(self) self.name = 'StartRecording' class StopRecording(Baserequests): \"\"\"Stop recording. Will return", "is enabled, the password for the streaming server. Ignored if", "name *settings* type: Object Filter settings \"\"\" def __init__(self, sourceName,", "to center on that axis. *rotation* type: double The clockwise", "the stream. *stream.settings.use_auth* type: boolean (optional) Indicates whether authentication should", "or \"bmp\" (or any other value supported by Qt's Image", "source's type. *sourceSettings* type: Object Source settings (varies between source", "class BroadcastCustomMessage(Baserequests): \"\"\"Broadcast custom message to all connected WebSocket clients", "int Scene Item ID. :Returns: *scene* type: String Name of", "partial) :Returns: *transitionSettings* type: Object Updated transition settings \"\"\" def", "Filter type *filterSettings* type: Object Filter settings \"\"\" def __init__(self,", "class TriggerHotkeyBySequence(Baserequests): \"\"\"Executes hotkey routine, identified by bound combination of", "`saveToFilePath` must be specified. Clients can specify `width` and `height`", "def __init__(self, source): Baserequests.__init__(self) self.name = 'GetTextGDIPlusProperties' self.datain['source'] = None", "movementType): Baserequests.__init__(self) self.name = 'MoveSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName'] =", "log. *outline* type: boolean (optional) Outline. *text* type: String (optional)", "def __init__(self, filename_formatting): Baserequests.__init__(self) self.name = 'SetFilenameFormatting' self.dataout['filename-formatting'] = filename_formatting", "\"size\": 150, \"style\": \"\" }` *font.face* type: String (optional) Font", "switch to. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'RemoveSceneTransitionOverride'", "transition override. :Arguments: *sceneName* type: String Name of the scene", "= None self.datain['outline_opacity'] = None self.datain['text'] = None self.datain['valign'] =", "Output name \"\"\" def __init__(self, outputName): Baserequests.__init__(self) self.name = 'StartOutput'", "the current overriding transition. Empty string if no override is", "= text self.dataout['valign'] = valign self.dataout['vertical'] = vertical self.dataout['render'] =", "class SetTransitionSettings(Baserequests): \"\"\"Change the current settings of a transition :Arguments:", "the top of the source item. *bottom* type: int Pixel", "*sourceName* type: String Source name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self)", "source type *types.*.caps* type: Object Source type capabilities *types.*.caps.isAsync* type:", "\"\"\" def __init__(self, source, offset): Baserequests.__init__(self) self.name = 'SetSyncOffset' self.dataout['source']", "of the source. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name =", "return self.datain['local_file'] def getUrl(self): return self.datain['url'] def getCss(self): return self.datain['css']", "false and call `ReleaseTBar` later once the animation/interaction is over.", "of the source before scaling. *crop.right* type: int (optional) The", "type: Boolean True if source of this type provide frames", "server settings. Any options not passed will remain unchanged. Returns", "sub-sources *types.*.caps.doNotDuplicate* type: Boolean True if sources of this type", "class GetVersion(Baserequests): \"\"\"Returns the latest version of the plugin and", "(like a user releasing their mouse button after moving it).", "stats window) :Returns: *stats* type: OBSStats [OBS stats](#obsstats) \"\"\" def", "streaming server. *stream.settings.username* type: String (optional) If authentication is enabled,", "type: String (optional) The password for the streaming service. *save*", "`release` to false. Defaults to true. \"\"\" def __init__(self, position,", "the T-Bar (like a user releasing their mouse button after", "all sources available in the running OBS instance :Returns: *sources*", "following: \"input\", \"filter\", \"transition\", \"scene\" or \"unknown\" \"\"\" def __init__(self):", "of the specified source *sourceSettings* type: Object Updated source settings", "Source name. *offset* type: int The audio sync offset (in", "Extents cx. *extents_cy* type: int Extents cy. *file* type: String", "Text Alignment (\"left\", \"center\", \"right\"). *bk_color* type: int Background color.", "sceneName=None): Baserequests.__init__(self) self.name = 'GetSceneItemList' self.datain['sceneName'] = None self.datain['sceneItems'] =", "scene. \"\"\" def __init__(self, items, scene=None): Baserequests.__init__(self) self.name = 'ReorderSceneItems'", "Will return an `error` if the Replay Buffer is already", "= 'GetSceneItemProperties' self.datain['name'] = None self.datain['itemId'] = None self.datain['position'] =", "= 'GetMute' self.datain['name'] = None self.datain['muted'] = None self.dataout['source'] =", "return self.datain['parentGroupName'] def getGroupChildren(self): return self.datain['groupChildren'] class SetSceneItemProperties(Baserequests): \"\"\"Sets the", "If 'type' is different than the current streaming service type,", "Mode is enabled. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStudioModeStatus'", "type: Boolean True if sources of this type composite one", "= 'SaveStreamSettings' class SendCaptions(Baserequests): \"\"\"Send the provided text as embedded", "sourceName): Baserequests.__init__(self) self.name = 'RestartMedia' self.dataout['sourceName'] = sourceName class StopMedia(Baserequests):", "authentication is required. *challenge* type: String (optional) *salt* type: String", "\"\"\" def __init__(self, filename_formatting): Baserequests.__init__(self) self.name = 'SetFilenameFormatting' self.dataout['filename-formatting'] =", "offset (in nanoseconds). \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name =", "__init__(self, source): Baserequests.__init__(self) self.name = 'GetTextFreetype2Properties' self.datain['source'] = None self.datain['color1']", "source (without scaling) of the source *width* type: double Scene", "self.name = 'RemoveSceneTransitionOverride' self.dataout['sceneName'] = sceneName class GetSceneTransitionOverride(Baserequests): \"\"\"Get the", "= None self.datain['extents_cx'] = None self.datain['extents_cy'] = None self.datain['file'] =", "self.datain['name'] def getItemId(self): return self.datain['itemId'] def getPosition(self): return self.datain['position'] def", "def getSettings(self): return self.datain['settings'] class SaveStreamSettings(Baserequests): \"\"\"Save the current streaming", "`error` if recording is not active. \"\"\" def __init__(self): Baserequests.__init__(self)", "outline_size self.dataout['outline_opacity'] = outline_opacity self.dataout['text'] = text self.dataout['valign'] = valign", "def getMediaState(self): return self.datain['mediaState'] class GetMediaSourcesList(Baserequests): \"\"\"List the media state", "the third Mic/Aux input source. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "self.dataout['gradient_opacity'] = gradient_opacity self.dataout['outline'] = outline self.dataout['outline_color'] = outline_color self.dataout['outline_size']", "None self.datain['outputHeight'] = None self.datain['scaleType'] = None self.datain['fps'] = None", "as a source, obs-websocket will return an error. :Arguments: *sourceName*", "'GetCurrentProfile' self.datain['profile-name'] = None def getProfileName(self): return self.datain['profile-name'] class ListProfiles(Baserequests):", "Alignment (\"left\", \"center\", \"right\"). *bk_color* type: int Background color. *bk_opacity*", "self.datain['chatlog_lines'] def getColor(self): return self.datain['color'] def getExtents(self): return self.datain['extents'] def", "= None self.datain['font'] = None self.datain['from_file'] = None self.datain['log_mode'] =", "type: float (optional) Gradient direction. *gradient_opacity* type: int (optional) Gradient", "scene's source items. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentScene'", "of a source. Unspecified properties will remain unchanged. Coordinates are", "of the Replay Buffer to disk. This is basically the", "image export (like the TakeSourceScreenshot request type) formatted as a", "self.name = 'AddFilterToSource' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterType']", "response to a user moving a T-Bar control in your", "def __init__(self, source, mute): Baserequests.__init__(self) self.name = 'SetMute' self.dataout['source'] =", "getPosition(self): return self.datain['position'] def getRotation(self): return self.datain['rotation'] def getScale(self): return", "source item. *right* type: int Pixel position of the right", "double (optional) The new clockwise rotation of the item in", "PreviousMedia(Baserequests): \"\"\"Go to the previous media item in the playlist.", "streaming is already active. :Arguments: *stream* type: Object (optional) Special", "or \"bottom\". \"\"\" def __init__(self, sourceName, filterName, movementType): Baserequests.__init__(self) self.name", "def getDesktop2(self): return self.datain['desktop-2'] def getMic1(self): return self.datain['mic-1'] def getMic2(self):", "getRecFolder(self): return self.datain['rec-folder'] class GetReplayBufferStatus(Baserequests): \"\"\"Get the status of the", "def __init__(self, position, release=None): Baserequests.__init__(self) self.name = 'SetTBarPosition' self.dataout['position'] =", "Useful for type-checking if you expect a specific settings schema.", "def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaTime' self.datain['timestamp'] = None", "class CreateScene(Baserequests): \"\"\"Create a new scene scene. :Arguments: *sceneName* type:", "class RemoveSceneTransitionOverride(Baserequests): \"\"\"Remove any transition override on a scene. :Arguments:", "type: int The number of pixels cropped off the left", "boolean Chat log. *outline* type: boolean Outline. *text* type: String", "source. *mic_2* type: String (optional) Name of the second Mic/Aux", "self.datain['custom_width'] = None self.datain['drop_shadow'] = None self.datain['font'] = None self.datain['from_file']", "self.datain['itemId'] def getPosition(self): return self.datain['position'] def getRotation(self): return self.datain['rotation'] def", "None self.datain['width'] = None self.datain['height'] = None self.datain['parentGroupName'] = None", "source should be shutdown when not visible. *render* type: boolean", "*release* type: boolean (optional) Whether or not the T-Bar gets", "Output height *scaleType* type: String Scaling method used if output", "type: double (optional) The new x scale of the item.", "may not function properly when they are controlled in this", "Gradient opacity (0-100). *outline* type: boolean (optional) Outline. *outline_color* type:", "is not set to `true`. *stream.settings.password* type: String (optional) If", "boolean Indicates if Studio Mode is enabled. \"\"\" def __init__(self):", "Defaults to the current scene. *item* type: String Scene Item", "how you add a source into a scene. :Arguments: *sceneName*", "Baserequests.__init__(self) self.name = 'GetAudioMonitorType' self.datain['monitorType'] = None self.dataout['sourceName'] = sourceName", "*scene_collections.*.sc_name* type: String Scene collection name \"\"\" def __init__(self): Baserequests.__init__(self)", "True if sources of this type may cause a feedback", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionDuration' self.datain['transition-duration'] = None", "'GetVideoInfo' self.datain['baseWidth'] = None self.datain['baseHeight'] = None self.datain['outputWidth'] = None", "= 'SetCurrentProfile' self.dataout['profile-name'] = profile_name class GetCurrentProfile(Baserequests): \"\"\"Get the name", "the new filter *filterType* type: String Filter type *filterSettings* type:", "class StopStreaming(Baserequests): \"\"\"Stop streaming. Will return an `error` if streaming", "double (optional) The new x position of the source. *position.y*", "getItem(self): return self.datain['item'] class SetCurrentScene(Baserequests): \"\"\"Switch to the specified scene.", "of alignment. *scale.x* type: double The x-scale factor of the", "None self.datain['locked'] = None self.datain['bounds'] = None self.datain['sourceWidth'] = None", "if no override is set. *transitionDuration* type: int Transition duration.", "'GetMediaDuration' self.datain['mediaDuration'] = None self.dataout['sourceName'] = sourceName def getMediaDuration(self): return", "position=None, rotation=None, scale=None, crop=None, visible=None, locked=None, bounds=None): Baserequests.__init__(self) self.name =", "request type) formatted as a comma-separated list string \"\"\" def", "def getDuration(self): return self.datain['duration'] class SetCurrentTransition(Baserequests): \"\"\"Set the active transition.", "self.datain['font'] = None self.datain['from_file'] = None self.datain['log_mode'] = None self.datain['outline']", "not set to `true`. \"\"\" def __init__(self, stream=None): Baserequests.__init__(self) self.name", "def __init__(self): Baserequests.__init__(self) self.name = 'GetVideoInfo' self.datain['baseWidth'] = None self.datain['baseHeight']", "item info *item.id* type: int New item ID *item.name* type:", "*authRequired* type: boolean Indicates whether authentication is required. *challenge* type:", "type: boolean Outline. *outline_color* type: int Outline color. *outline_size* type:", ":Arguments: *sceneName* type: String Name of the scene to switch", "*position.x* type: double (optional) The new x position of the", "Baserequests.__init__(self) self.name = 'SetSceneItemProperties' self.dataout['item'] = item self.dataout['scene-name'] = scene_name", "filterType self.dataout['filterSettings'] = filterSettings class RemoveFilterFromSource(Baserequests): \"\"\"Remove a filter from", "= None self.datain['obs-websocket-version'] = None self.datain['obs-studio-version'] = None self.datain['available-requests'] =", "starting the stream. *stream.metadata* type: Object (optional) Adds the given", "self.name = 'NextMedia' self.dataout['sourceName'] = sourceName class PreviousMedia(Baserequests): \"\"\"Go to", "state). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopStreaming' class StartStreaming(Baserequests):", "streaming service. *save* type: boolean Persist the settings to disk.", "self.dataout['sourceSettings'] = sourceSettings self.dataout['setVisible'] = setVisible def getItemId(self): return self.datain['itemId']", "log lines. *color* type: int (optional) Text color. *extents* type:", "return self.datain['authRequired'] def getChallenge(self): return self.datain['challenge'] def getSalt(self): return self.datain['salt']", "by the horizontal scaling factor) *height* type: double Scene item", "\"size\": 150, \"style\": \"\" }` *font.face* type: String Font face.", "in the source's filter chain. Either \"up\", \"down\", \"top\" or", ":Returns: *profile_name* type: String Name of the currently active profile.", "width self.dataout['height'] = height def getSourceName(self): return self.datain['sourceName'] def getImg(self):", "sourceName self.dataout['filterName'] = filterName self.dataout['filterType'] = filterType self.dataout['filterSettings'] = filterSettings", "to switch to. \"\"\" def __init__(self, scene_name): Baserequests.__init__(self) self.name =", "self.datain['colorRange'] = None def getBaseWidth(self): return self.datain['baseWidth'] def getBaseHeight(self): return", "false. Defaults to true. \"\"\" def __init__(self, position, release=None): Baserequests.__init__(self)", "self.name = 'GetAudioMonitorType' self.datain['monitorType'] = None self.dataout['sourceName'] = sourceName def", "*height* type: int (optional) Screenshot height. Defaults to the source's", "name. *read_from_file* type: boolean (optional) Read text from the specified", "crop coordinates of the specified source item. :Arguments: *scene_name* type:", "file. *font* type: Object (optional) Holds data for the font.", ":Arguments: *outputName* type: String Output name :Returns: *outputInfo* type: Output", "self.datain['scale'] = None self.datain['crop'] = None self.datain['visible'] = None self.datain['muted']", "*type* type: String The type of streaming service configuration, usually", "= None self.datain['outline_size'] = None self.datain['outline_opacity'] = None self.datain['text'] =", "coordinates of the specified source item. :Arguments: *scene_name* type: String", "return self.datain['sources'] class GetSourceTypesList(Baserequests): \"\"\"Get a list of all available", "filterName self.dataout['filterSettings'] = filterSettings class SetSourceFilterVisibility(Baserequests): \"\"\"Change the visibility/enabled state", "BY generate_classes.py - DO NOT EDIT # # (Generated on", ":Arguments: *sourceName* type: String Source name. *sourceKind* type: String Source", "text \"\"\" def __init__(self, text): Baserequests.__init__(self) self.name = 'SendCaptions' self.dataout['text']", "rotation of the item in degrees. *scale.x* type: double (optional)", ":Returns: *stats* type: OBSStats [OBS stats](#obsstats) \"\"\" def __init__(self): Baserequests.__init__(self)", "\"\"\"List all sources available in the running OBS instance :Returns:", "GetPreviewScene(Baserequests): \"\"\"Get the name of the currently previewed scene and", "type: int Base (canvas) height *outputWidth* type: int Output width", "class ReorderSourceFilter(Baserequests): \"\"\"Move a filter in the chain (absolute index", "any String, Numeric, or Boolean field. *stream.settings* type: Object (optional)", "type: int (optional) Gradient top color. *color2* type: int (optional)", "return self.datain['color2'] def getCustom_width(self): return self.datain['custom_width'] def getDrop_shadow(self): return self.datain['drop_shadow']", "the UI if there is no current override and this", "boolean (optional) Read text from the specified file. *log_mode* type:", "int (optional) Background color. *bk_opacity* type: int (optional) Background opacity", "*css* type: String (optional) CSS to inject. *width* type: int", "Key *keyModifiers.command* type: boolean Trigger Command Key (Mac) \"\"\" def", "= url self.dataout['css'] = css self.dataout['width'] = width self.dataout['height'] =", "size. *font.style* type: String Font Style (unknown function). *from_file* type:", "monitorType class TakeSourceScreenshot(Baserequests): \"\"\" At least `embedPictureFormat` or `saveToFilePath` must", "\"\"\"Get current properties for a Browser Source. :Arguments: *source* type:", "item's parent (if this item belongs to a group) *groupChildren*", "not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionPosition' self.datain['position']", "None self.datain['outline'] = None self.datain['outline_color'] = None self.datain['outline_size'] = None", "*sourceName* type: String Name of the source from which the", "fps=None, shutdown=None, render=None): Baserequests.__init__(self) self.name = 'SetBrowserSourceProperties' self.dataout['source'] = source", "type: boolean Indicates whether authentication should be used when connecting", "True if sources of this type composite one or more", "the scene. \"\"\" def __init__(self, sourceName, sourceKind, sceneName, sourceSettings=None, setVisible=None):", "sourceName self.dataout['sourceSettings'] = sourceSettings self.dataout['sourceType'] = sourceType def getSourceName(self): return", ":Returns: *profiles* type: Array<Object> List of available profiles. *profiles.*.profile_name* type:", "*transitionName* type: String Transition name :Returns: *transitionSettings* type: Object Current", "= None self.datain['settings'] = None self.dataout['sourceName'] = sourceName self.dataout['filterName'] =", "\"\"\"Get the name of the current scene collection. :Returns: *sc_name*", "self.name = 'OpenProjector' self.dataout['type'] = type self.dataout['monitor'] = monitor self.dataout['geometry']", "the stream (the same as GetStreamSettings). :Arguments: *type* type: String", "class SetVolume(Baserequests): \"\"\"Set the volume of the specified source. Default", "type: int Base source (without scaling) of the source *width*", ":Arguments: *duration* type: int Desired duration of the transition (in", "to offset the current media position. \"\"\" def __init__(self, sourceName,", "*types.*.caps.doNotDuplicate* type: Boolean True if sources of this type should", "override. :Arguments: *sceneName* type: String Name of the scene to", "None self.datain['available-requests'] = None self.datain['supported-image-export-formats'] = None def getVersion(self): return", "None self.datain['outputWidth'] = None self.datain['outputHeight'] = None self.datain['scaleType'] = None", "THIS if you called `SetTBarPosition` with the `release` parameter set", "specify `width` and `height` parameters to receive scaled pictures. Aspect", "(optional) The new x scale of the item. *scale.y* type:", "self.datain['isRecording'] def getIsRecordingPaused(self): return self.datain['isRecordingPaused'] def getRecordTimecode(self): return self.datain['recordTimecode'] def", "be specified in the `settings` object or an error will", "path name. *read_from_file* type: boolean Read text from the specified", "bool (optional) The new locked status of the source. 'true'", "class GetAudioMonitorType(Baserequests): \"\"\"Get the audio monitoring type of the specified", "settings of a filter :Arguments: *sourceName* type: String Name of", "monitor. Requires OBS v24.0.4 or newer. :Arguments: *type* type: String", "v25.0.8) :Arguments: *sourceName* type: String Source name. *playPause* type: boolean", "type: boolean Trigger Command Key (Mac) \"\"\" def __init__(self, keyId,", "source. 'true' shows source, 'false' hides source. *locked* type: bool", "to get the list of scene items from. Defaults to", "direction. *gradient_opacity* type: int (optional) Gradient opacity (0-100). *outline* type:", "types :Returns: *types* type: Array<Object> Array of source types *types.*.typeId*", "in progress, the change won't be applied immediately and will", "self.dataout['item'] = item self.dataout['scene'] = scene class AddSceneItem(Baserequests): \"\"\"Creates a", "useDecibel class GetMute(Baserequests): \"\"\"Get the mute status of a specified", "5 or so seconds that the media is playing, the", "self.datain['desktop-1'] def getDesktop2(self): return self.datain['desktop-2'] def getMic1(self): return self.datain['mic-1'] def", "= None def getProfileName(self): return self.datain['profile-name'] class ListProfiles(Baserequests): \"\"\"Get a", "__init__(self, sourceName, filterName, filterEnabled): Baserequests.__init__(self) self.name = 'SetSourceFilterVisibility' self.dataout['sourceName'] =", "Baserequests.__init__(self) self.name = 'SetCurrentScene' self.dataout['scene-name'] = scene_name class GetCurrentScene(Baserequests): \"\"\"Get", "type: String The name of the scene to preview. \"\"\"", "if Studio Mode is enabled. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "video *types.*.caps.hasAudio* type: Boolean True if sources of this type", "the Heartbeat event :Arguments: *enable* type: boolean Starts/Stops emitting heartbeat", "\"\"\"Start streaming. Will return an `error` if streaming is already", "def getSourceType(self): return self.datain['sourceType'] def getSourceSettings(self): return self.datain['sourceSettings'] class GetTextGDIPlusProperties(Baserequests):", "their mouse button after moving it). *YOU MUST CALL THIS", "input source. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSpecialSources' self.datain['desktop-1']", "String (optional) CSS to inject. *width* type: int (optional) Width.", "getFilenameFormatting(self): return self.datain['filename-formatting'] class GetStats(Baserequests): \"\"\"Get OBS stats (almost the", "String Source name. *volume* type: double Volume of the source.", "type: String Filter name *filters.*.settings* type: Object Filter settings \"\"\"", "as (one of the values provided in the `supported-image-export-formats` response", "String Name of the scene where the new item was", "type (usually 'rtmp_custom' or 'rtmp_common'). If the currently configured stream", "__init__(self, sourceName, timestamp): Baserequests.__init__(self) self.name = 'SetMediaTime' self.dataout['sourceName'] = sourceName", "= None self.datain['obs-studio-version'] = None self.datain['available-requests'] = None self.datain['supported-image-export-formats'] =", "self.name = 'CreateSource' self.datain['itemId'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceKind']", "*sourceName* type: String Source name. *sourceKind* type: String Source kind,", "*right* type: int Pixel position of the right of the", "as triggering the \"Save Replay Buffer\" hotkey. Will return an", "information). \"\"\" def __init__(self, auth): Baserequests.__init__(self) self.name = 'Authenticate' self.dataout['auth']", "the `supported-image-export-formats` response field of `GetVersion`). If not specified, tries", "file/least compression. Varies with image type. *width* type: int (optional)", "String Filter type *filterSettings* type: Object Filter settings \"\"\" def", "outputs to OBS may not function properly when they are", "Can be \"png\", \"jpg\", \"jpeg\" or \"bmp\" (or any other", "(optional) List of children (if this item is a group)", "formatting string. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetFilenameFormatting' self.datain['filename-formatting']", "frontend's dropdown menu. :Returns: *name* type: String Name of the", "getHeight(self): return self.datain['height'] def getFps(self): return self.datain['fps'] def getShutdown(self): return", "RTMP stream. Used to pass data to the RTMP service", "= None self.dataout['transitionName'] = transitionName self.dataout['transitionSettings'] = transitionSettings def getTransitionSettings(self):", "milliseconds). \"\"\" def __init__(self, duration): Baserequests.__init__(self) self.name = 'SetTransitionDuration' self.dataout['duration']", "`0.0` and `20.0` for mul, and under 26.0 for dB.", "'SetCurrentSceneCollection' self.dataout['sc-name'] = sc_name class GetCurrentSceneCollection(Baserequests): \"\"\"Get the name of", "= valign self.dataout['vertical'] = vertical self.dataout['render'] = render class GetTextFreetype2Properties(Baserequests):", "String (optional) Scene Item name (if the `item` field is", "comma-separated list string \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetVersion'", "'rtmp_custom' or 'rtmp_common'. *settings* type: Object Stream settings object. *settings.server*", "mode). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ToggleStudioMode' class GetTransitionList(Baserequests):", "getChallenge(self): return self.datain['challenge'] def getSalt(self): return self.datain['salt'] class Authenticate(Baserequests): \"\"\"Attempt", "of a Text GDI Plus source. :Arguments: *source* type: String", "getStudioMode(self): return self.datain['studio-mode'] class GetPreviewScene(Baserequests): \"\"\"Get the name of the", "getMic1(self): return self.datain['mic-1'] def getMic2(self): return self.datain['mic-2'] def getMic3(self): return", "\"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment* type:", "name class TriggerHotkeyByName(Baserequests): \"\"\"Executes hotkey routine, identified by hotkey unique", "\"\"\"Sets the scene specific properties of a source. Unspecified properties", "is not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopReplayBuffer'", "\"\" }` *font.face* type: String Font face. *font.flags* type: int", "color format *colorSpace* type: String Color space for YUV *colorRange*", "the first 5 or so seconds that the media is", "Baserequests.__init__(self) self.name = 'GetVolume' self.datain['name'] = None self.datain['volume'] = None", "= newName class SetSyncOffset(Baserequests): \"\"\"Set the audio sync offset of", "set `release` to false and call `ReleaseTBar` later once the", "= None self.datain['gradient_opacity'] = None self.datain['outline'] = None self.datain['outline_color'] =", "self.datain['sources'] class GetSourceTypesList(Baserequests): \"\"\"Get a list of all available sources", "name. *top* type: int Pixel position of the top of", "`vlc_source`) *mediaSources.*.mediaState* type: String The current state of media for", "class GetStudioModeStatus(Baserequests): \"\"\"Indicates if Studio Mode is currently enabled. :Returns:", "(only present if currently recording). *preview_only* type: boolean Always false.", "return self.datain['salt'] class Authenticate(Baserequests): \"\"\"Attempt to authenticate the client to", "and shouldn't be \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSourceTypesList'", "class GetStreamSettings(Baserequests): \"\"\"Get the current streaming server settings. :Returns: *type*", "of OBS v25.0.8) Note: Due to processing/network delays, this request", "String Text content to be displayed. *text_file* type: String File", "of the source before scaling. *crop.bottom* type: int (optional) The", "= sourceName def getFilters(self): return self.datain['filters'] class GetSourceFilterInfo(Baserequests): \"\"\"List filters", "class RemoveFilterFromSource(Baserequests): \"\"\"Remove a filter from a source :Arguments: *sourceName*", "Filter status (enabled or not) *filters.*.type* type: String Filter type", "*scene_name* type: String Name of the scene to switch to.", "`Multiview` (case insensitive). *monitor* type: int (Optional) Monitor to open", "to be saved. Can be in a format different from", "self.name = 'GetRecordingStatus' self.datain['isRecording'] = None self.datain['isRecordingPaused'] = None self.datain['recordTimecode']", "on the current state of the replay buffer). \"\"\" def", "scene transition override. :Arguments: *sceneName* type: String Name of the", "self.datain['salt'] = None def getAuthRequired(self): return self.datain['authRequired'] def getChallenge(self): return", "'PauseRecording' class ResumeRecording(Baserequests): \"\"\"Resume/unpause the current recording (if paused). Returns", "self.datain['text'] = None self.datain['text_file'] = None self.datain['word_wrap'] = None self.dataout['source']", "'StartStopReplayBuffer' class StartReplayBuffer(Baserequests): \"\"\"Start recording into the Replay Buffer. Will", "the path of the current recording folder. :Returns: *rec_folder* type:", "\"center\", \"bottom\"). *vertical* type: boolean (optional) Vertical text enabled. *render*", "left of the source before scaling. *visible* type: bool If", "of streaming service configuration, usually `rtmp_custom` or `rtmp_common`. *settings* type:", "self.dataout['fps'] = fps self.dataout['shutdown'] = shutdown self.dataout['render'] = render class", "class SaveStreamSettings(Baserequests): \"\"\"Save the current streaming server settings to disk.", "def __init__(self): Baserequests.__init__(self) self.name = 'GetMediaSourcesList' self.datain['mediaSources'] = None def", "PauseRecording(Baserequests): \"\"\"Pause the current recording. Returns an error if recording", "\"\"\" def __init__(self, rec_folder): Baserequests.__init__(self) self.name = 'SetRecordingFolder' self.dataout['rec-folder'] =", "mul, NOT SLIDER PERCENTAGE. :Arguments: *source* type: String Source name.", "boolean Current recording status. *stream_timecode* type: String (optional) Time elapsed", "\"png\", \"jpg\", \"jpeg\" or \"bmp\" (or any other value supported", "self.datain['visible'] def getMuted(self): return self.datain['muted'] def getLocked(self): return self.datain['locked'] def", "accessing the streaming server. Only present if `use_auth` is `true`.", "format, NOT SLIDER PERCENTAGE. :Arguments: *source* type: String Source name.", "of filters for the specified source *filters.*.enabled* type: Boolean Filter", "filter chain. Either \"up\", \"down\", \"top\" or \"bottom\". \"\"\" def", "def __init__(self, sceneName, transitionName, transitionDuration): Baserequests.__init__(self) self.name = 'SetSceneTransitionOverride' self.dataout['sceneName']", "return self.datain['transitionDuration'] class GetStreamingStatus(Baserequests): \"\"\"Get current streaming and recording status.", "Stream settings object. *settings.server* type: String The publish URL. *settings.key*", "type: boolean (optional) Outline. *text* type: String (optional) Text content", "profile's scenes (See [GetCurrentScene](#getcurrentscene) for more information). \"\"\" def __init__(self):", "kind) *sources.*.type* type: String Source type. Value is one of", "Read text from the specified file. *font* type: Object (optional)", "the current timestamp of media in milliseconds. Supports ffmpeg and", "\"A\"). Available identifiers [here](https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h) *keyModifiers* type: Object (Optional) Optional key", "to set the timestamp to. \"\"\" def __init__(self, sourceName, timestamp):", "relative path. *fileFormat* type: String (optional) Format to save the", "*gradient_dir* type: float (optional) Gradient direction. *gradient_opacity* type: int (optional)", "Baserequests.__init__(self) self.name = 'GetTransitionPosition' self.datain['position'] = None def getPosition(self): return", "(only if monitor is -1). Encoded in Base64 using [Qt's", "the item's parent (the scene or group it belongs to).", "currently selected transition if supported. :Arguments: *duration* type: int Desired", "GetVolume(Baserequests): \"\"\"Get the volume of the specified source. Default response", "Extents cx. *extents_cy* type: int (optional) Extents cy. *file* type:", "that axis. *rotation* type: double The clockwise rotation of the", "List of children (if this item is a group) \"\"\"", "stream type, all settings must be specified in the `settings`", "type: int (optional) Background color. *bk_opacity* type: int (optional) Background", "boolean (optional) Read text from the specified file. *font* type:", "a filter :Arguments: *sourceName* type: String Source name *filterName* type:", "ratio between -1 and 100 to write the image with.", "type: String Output name *force* type: boolean (optional) Force stop", "\"\"\"Get a list of all scene items in a scene.", "def __init__(self, stream=None): Baserequests.__init__(self) self.name = 'StartStreaming' self.dataout['stream'] = stream", "Object Current transition settings \"\"\" def __init__(self, transitionName): Baserequests.__init__(self) self.name", "*mic_1* type: String (optional) Name of the first Mic/Aux input", "= None self.datain['sourceHeight'] = None self.datain['width'] = None self.datain['height'] =", "String (optional) Name of the scene the scene item belongs", "(optional) Indicates that a local file is in use. *local_file*", "String obs-websocket plugin version. *obs_studio_version* type: String OBS Studio program", "def getHeight(self): return self.datain['height'] def getParentGroupName(self): return self.datain['parentGroupName'] def getGroupChildren(self):", "*muted* type: boolean Mute status of the source. \"\"\" def", "'GetTransitionPosition' self.datain['position'] = None def getPosition(self): return self.datain['position'] class GetTransitionSettings(Baserequests):", "user settings :Arguments: *keyId* type: String Main key identifier (e.g.", "if output size differs from base size *fps* type: double", "type: boolean (optional) Read text from the specified file. *font*", "shows source, 'false' hides source. *locked* type: bool (optional) The", "= 'SetMute' self.dataout['source'] = source self.dataout['mute'] = mute class ToggleMute(Baserequests):", "Baserequests.__init__(self) self.name = 'TriggerHotkeyByName' self.dataout['hotkeyName'] = hotkeyName class TriggerHotkeyBySequence(Baserequests): \"\"\"Executes", "self.name = 'SetSyncOffset' self.dataout['source'] = source self.dataout['offset'] = offset class", "*types.*.caps.hasVideo* type: Boolean True if sources of this type provide", "is acceptable). *item.id* type: int Scene Item ID. :Returns: *scene*", "# from .base_classes import Baserequests class GetVersion(Baserequests): \"\"\"Returns the latest", "degrees). \"\"\" def __init__(self, item, x_scale, y_scale, rotation, scene_name=None): Baserequests.__init__(self)", "self.dataout['sourceName'] = sourceName self.dataout['timestamp'] = timestamp class ScrubMedia(Baserequests): \"\"\"Scrub media", "on the current recording state). \"\"\" def __init__(self): Baserequests.__init__(self) self.name", ":Arguments: *scene_name* type: String (optional) Name of the scene the", "= height def getSourceName(self): return self.datain['sourceName'] def getImg(self): return self.datain['img']", "vertical alignment (\"top\", \"center\", \"bottom\"). *vertical* type: boolean Vertical text", "Command Key (Mac) \"\"\" def __init__(self, keyId, keyModifiers): Baserequests.__init__(self) self.name", "`pictureFormat`. Can be a relative path. *fileFormat* type: String (optional)", "\"input\", \"filter\", \"transition\" or \"other\" *types.*.defaultSettings* type: Object Default settings", "__init__(self): Baserequests.__init__(self) self.name = 'GetTransitionDuration' self.datain['transition-duration'] = None def getTransitionDuration(self):", "type: String Font face. *font.flags* type: int Font text styling", "Baserequests.__init__(self) self.name = 'GetTextGDIPlusProperties' self.datain['source'] = None self.datain['align'] = None", "= geometry self.dataout['name'] = name class TriggerHotkeyByName(Baserequests): \"\"\"Executes hotkey routine,", "None self.dataout['sceneName'] = sceneName def getSceneName(self): return self.datain['sceneName'] def getSceneItems(self):", ":Arguments: *scene_name* type: String Name of the scene to switch", "*stream.type* type: String (optional) If specified ensures the type of", "Baserequests.__init__(self) self.name = 'AddFilterToSource' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName", "text as embedded CEA-608 caption data. :Arguments: *text* type: String", "*color1* type: int Gradient top color. *color2* type: int Gradient", "self.datain['colorSpace'] def getColorRange(self): return self.datain['colorRange'] class OpenProjector(Baserequests): \"\"\"Open a projector", "type: boolean Whether to make the sceneitem visible on creation", "the audio monitoring type of the specified source. :Arguments: *sourceName*", "Type of the scene item's source. Either `input`, `group`, or", "be displayed. *valign* type: String Text vertical alignment (\"top\", \"center\",", "recording is not active or already paused. \"\"\" def __init__(self):", "amplitude/mul. :Returns: *name* type: String Source name. *volume* type: double", "second *videoFormat* type: String Video color format *colorSpace* type: String", "the item. *scale.y* type: double (optional) The new y scale", "Baserequests.__init__(self) self.name = 'SetRecordingFolder' self.dataout['rec-folder'] = rec_folder class GetRecordingFolder(Baserequests): \"\"\"Get", "*bounds.y* type: double Height of the bounding box. *sourceWidth* type:", "to the recording file (only present if currently recording). \"\"\"", "return self.datain['stream-timecode'] def getRecTimecode(self): return self.datain['rec-timecode'] def getPreviewOnly(self): return self.datain['preview-only']", "self.datain['volume'] def getMuted(self): return self.datain['muted'] class SetVolume(Baserequests): \"\"\"Set the volume", "source. *is_local_file* type: boolean (optional) Indicates that a local file", "get the list of scene items from. Defaults to the", "x self.dataout['y'] = y self.dataout['scene-name'] = scene_name class SetSceneItemTransform(Baserequests): \"\"\"Set", "self.datain['settings'] = None self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName def", "return self.datain['itemId'] class GetSourcesList(Baserequests): \"\"\"List all sources available in the", "sceneName class GetSceneTransitionOverride(Baserequests): \"\"\"Get the current scene transition override. :Arguments:", "no scene items share sources within the scene. \"\"\" def", "profile_name): Baserequests.__init__(self) self.name = 'SetCurrentProfile' self.dataout['profile-name'] = profile_name class GetCurrentProfile(Baserequests):", "scene. *item* type: String | Object Scene Item name (if", "self.datain['types'] class GetVolume(Baserequests): \"\"\"Get the volume of the specified source.", "\"jpeg\" or \"bmp\" (or any other value supported by Qt's", "type: int The number of pixels cropped off the top", "chain \"\"\" def __init__(self, sourceName, filterName, newIndex): Baserequests.__init__(self) self.name =", "of the bounding box. *sourceWidth* type: int Base width (without", "None self.datain['muted'] = None self.dataout['source'] = source self.dataout['useDecibel'] = useDecibel", "newIndex class MoveSourceFilter(Baserequests): \"\"\"Move a filter in the chain (relative", "Can be a relative path. *fileFormat* type: String (optional) Format", "specified file. *font* type: Object Holds data for the font.", "*types.*.caps.isComposite* type: Boolean True if sources of this type composite", "self.datain['outputInfo'] = None self.dataout['outputName'] = outputName def getOutputInfo(self): return self.datain['outputInfo']", "return self.datain['drop_shadow'] def getFont(self): return self.datain['font'] def getFrom_file(self): return self.datain['from_file']", "\"\"\" def __init__(self, sceneName, sourceName, setVisible): Baserequests.__init__(self) self.name = 'AddSceneItem'", "of amplitude/mul. \"\"\" def __init__(self, source, volume, useDecibel=None): Baserequests.__init__(self) self.name", "Vertical text enabled. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name =", "(if `embedPictureFormat` was specified in the request) *imageFile* type: String", "getMic3(self): return self.datain['mic-3'] class GetSourceFilters(Baserequests): \"\"\"List filters applied to a", "self.datain['filters'] class GetSourceFilterInfo(Baserequests): \"\"\"List filters applied to a source :Arguments:", "between source types, may require some probing around). \"\"\" def", "\"\"\"Get the duration of the currently selected transition if supported.", "sourceName self.dataout['embedPictureFormat'] = embedPictureFormat self.dataout['saveToFilePath'] = saveToFilePath self.dataout['fileFormat'] = fileFormat", "filter is added *filterName* type: String Name of the new", "String (optional) Time elapsed since streaming started (only present if", "server. *stream.settings.username* type: String (optional) If authentication is enabled, the", "= None self.datain['settings'] = None def getType(self): return self.datain['type'] def", "self.dataout['transitionName'] = transitionName self.dataout['transitionDuration'] = transitionDuration class RemoveSceneTransitionOverride(Baserequests): \"\"\"Remove any", "= filterName self.dataout['filterType'] = filterType self.dataout['filterSettings'] = filterSettings class RemoveFilterFromSource(Baserequests):", "self.datain['sourceSettings'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceType'] = sourceType def", "or not. Defaults to true :Returns: *itemId* type: int ID", "the chain (absolute index positioning) :Arguments: *sourceName* type: String Name", "type: boolean Drop shadow. *font* type: Object Holds data for", "`item` field is an object) *item.id* type: int (optional) Scene", "self.dataout['save'] = save class GetStreamSettings(Baserequests): \"\"\"Get the current streaming server", "specified source. Default request format uses mul, NOT SLIDER PERCENTAGE.", "type: String (optional) Type of the specified source. Useful for", "Object (optional) Holds data for the font. Ex: `\"font\": {", "None self.datain['sources'] = None def getName(self): return self.datain['name'] def getSources(self):", "*with_transition.name* type: String Name of the transition. *with_transition.duration* type: int", "sourceName, filterName, newIndex): Baserequests.__init__(self) self.name = 'ReorderSourceFilter' self.dataout['sourceName'] = sourceName", "*outline_opacity* type: int Outline opacity (0-100). *text* type: String Text", "scale=None, crop=None, visible=None, locked=None, bounds=None): Baserequests.__init__(self) self.name = 'SetSceneItemProperties' self.dataout['item']", "of the source. *scale.y* type: double The y-scale factor of", "= source def getSource(self): return self.datain['source'] def getIs_local_file(self): return self.datain['is_local_file']", "SceneItem as visible or not. Defaults to true :Returns: *itemId*", "= None self.datain['sourceType'] = None self.datain['sourceSettings'] = None self.dataout['sourceName'] =", "Name of the transition to use. *transitionDuration* type: int (Optional)", "is not perfect. The processing rate of this request has", "self.name = 'StopRecording' class PauseRecording(Baserequests): \"\"\"Pause the current recording. Returns", "= None self.dataout['sourceName'] = sourceName self.dataout['embedPictureFormat'] = embedPictureFormat self.dataout['saveToFilePath'] =", ":Arguments: *source* type: String Source name. *offset* type: int The", "self.datain['read_from_file'] = None self.datain['font'] = None self.datain['gradient'] = None self.datain['gradient_color']", "transition :Arguments: *transitionName* type: String Transition name :Returns: *transitionSettings* type:", "class SetCurrentProfile(Baserequests): \"\"\"Set the currently active profile. :Arguments: *profile_name* type:", "`true` for pause. \"\"\" def __init__(self, sourceName, playPause): Baserequests.__init__(self) self.name", "alignment (\"top\", \"center\", \"bottom\"). *vertical* type: boolean Vertical text enabled.", "properties are available from `GetSourceTypesList`. :Arguments: *sourceName* type: String Name", "getTypes(self): return self.datain['types'] class GetVolume(Baserequests): \"\"\"Get the volume of the", "item. \"\"\" def __init__(self, item, top, bottom, left, right, scene_name=None):", "boolean Gradient enabled. *gradient_color* type: int Gradient color. *gradient_dir* type:", "def __init__(self): Baserequests.__init__(self) self.name = 'GetVersion' self.datain['version'] = None self.datain['obs-websocket-version']", "type: boolean Desired mute status. \"\"\" def __init__(self, source, mute):", "if no scene items share sources within the scene. \"\"\"", ":Returns: *transitionSettings* type: Object Updated transition settings \"\"\" def __init__(self,", "client *data* type: Object User-defined data \"\"\" def __init__(self, realm,", "one of the following: \"input\", \"filter\", \"transition\", \"scene\" or \"unknown\"", "currently recording). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetRecordingStatus' self.datain['isRecording']", "monitor, geometry, name): Baserequests.__init__(self) self.name = 'OpenProjector' self.dataout['type'] = type", "{ \"face\": \"Arial\", \"flags\": 0, \"size\": 150, \"style\": \"\" }`", "can be partial) :Returns: *transitionSettings* type: Object Updated transition settings", "to all connected WebSocket clients :Arguments: *realm* type: String Identifier", "= from_file self.dataout['log_mode'] = log_mode self.dataout['outline'] = outline self.dataout['text'] =", "*sceneName* type: String (optional) Name of the scene to get", "return self.datain['gradient_color'] def getGradient_dir(self): return self.datain['gradient_dir'] def getGradient_opacity(self): return self.datain['gradient_opacity']", "source settings \"\"\" def __init__(self, sourceName, sourceSettings, sourceType=None): Baserequests.__init__(self) self.name", "source item in a specified scene. :Arguments: *scene_name* type: String", "under `26.0` if using dB. *muted* type: boolean Indicates whether", "Desired mute status. \"\"\" def __init__(self, source, mute): Baserequests.__init__(self) self.name", "type: boolean (optional) Indicates whether the source should be shutdown", "self.datain['chatlog_lines'] = None self.datain['color'] = None self.datain['extents'] = None self.datain['extents_cx']", "\"\"\"Get basic OBS video information :Returns: *baseWidth* type: int Base", "def __init__(self, sourceName, filterName, filterEnabled): Baserequests.__init__(self) self.name = 'SetSourceFilterVisibility' self.dataout['sourceName']", "preferred due to uniqueness per scene *items.*.id* type: int (optional)", "is largest file/least compression. Varies with image type. *width* type:", "type: int Chat log lines. *color* type: int Text color.", "*useDecibel* type: boolean (optional) Output volume in decibels of attenuation", "of the currently active scene collection. \"\"\" def __init__(self): Baserequests.__init__(self)", "= None self.datain['challenge'] = None self.datain['salt'] = None def getAuthRequired(self):", "Shift Key *keyModifiers.alt* type: boolean Trigger Alt Key *keyModifiers.control* type:", "type: String Unique source internal type (a.k.a `ffmpeg_source` or `vlc_source`)", "status of the OBS replay buffer. :Returns: *isReplayBufferActive* type: boolean", "scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemRender' self.dataout['source'] = source self.dataout['render'] =", "for pause. \"\"\" def __init__(self, sourceName, playPause): Baserequests.__init__(self) self.name =", "return self.datain['outputHeight'] def getScaleType(self): return self.datain['scaleType'] def getFps(self): return self.datain['fps']", "'key' of the RTMP stream. Used to pass data to", "name. :Returns: *source* type: String Source name. *is_local_file* type: boolean", "self.dataout['embedPictureFormat'] = embedPictureFormat self.dataout['saveToFilePath'] = saveToFilePath self.dataout['fileFormat'] = fileFormat self.dataout['compressionQuality']", "'GetOutputInfo' self.datain['outputInfo'] = None self.dataout['outputName'] = outputName def getOutputInfo(self): return", "type: boolean Indicates whether the source should be shutdown when", "of the bounding box. *bounds.y* type: double (optional) The new", "provide video *types.*.caps.hasAudio* type: Boolean True if sources of this", "File path. *word_wrap* type: boolean (optional) Word wrap. \"\"\" def", "is used. *embedPictureFormat* type: String (optional) Format of the Data", "None self.datain['bk_color'] = None self.datain['bk_opacity'] = None self.datain['chatlog'] = None", "(Generated on 2020-12-20 18:26:33.661372) # from .base_classes import Baserequests class", "API. :Returns: *version* type: double OBSRemote compatible API version. Fixed", "def getSupportedImageExportFormats(self): return self.datain['supported-image-export-formats'] class GetAuthRequired(Baserequests): \"\"\"Tells the client if", "'rtmp_custom' or 'rtmp_common'). If the currently configured stream type does", "of studio mode). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ToggleStudioMode'", "plugin version. *obs_studio_version* type: String OBS Studio program version. *available_requests*", "type: String | Object Scene Item name (if this field", "Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\".", "while a recording is in progress, the change won't be", "file. *font* type: Object Holds data for the font. Ex:", "basically the same as triggering the \"Save Replay Buffer\" hotkey.", "(optional) Outline opacity (0-100). *text* type: String (optional) Text content", "def __init__(self): Baserequests.__init__(self) self.name = 'GetSpecialSources' self.datain['desktop-1'] = None self.datain['desktop-2']", "YUV *colorRange* type: String Color range (full or partial) \"\"\"", "\"\"\" def __init__(self, source, useDecibel=None): Baserequests.__init__(self) self.name = 'GetVolume' self.datain['name']", "a filter from a source :Arguments: *sourceName* type: String Name", "return self.datain['recordingFilename'] class StartStopRecording(Baserequests): \"\"\"Toggle recording on or off (depending", "*bounds.type* type: String Type of bounding box. Can be \"OBS_BOUNDS_STRETCH\",", "def __init__(self): Baserequests.__init__(self) self.name = 'StartReplayBuffer' class StopReplayBuffer(Baserequests): \"\"\"Stop recording", "*filterName* type: String Name of the new filter *filterType* type:", "self.datain['text'] = None self.datain['valign'] = None self.datain['vertical'] = None self.dataout['source']", "an `error` if the Replay Buffer is not active. \"\"\"", "getVolume(self): return self.datain['volume'] def getMuted(self): return self.datain['muted'] class SetVolume(Baserequests): \"\"\"Set", "self.datain['extents'] def getExtents_cx(self): return self.datain['extents_cx'] def getExtents_cy(self): return self.datain['extents_cy'] def", "*width* type: int (optional) Width. *height* type: int (optional) Height.", "= None def getCurrentScene(self): return self.datain['current-scene'] def getScenes(self): return self.datain['scenes']", "Baserequests.__init__(self) self.name = 'ListOutputs' self.datain['outputs'] = None def getOutputs(self): return", "= local_file self.dataout['url'] = url self.dataout['css'] = css self.dataout['width'] =", "def __init__(self, with_transition=None): Baserequests.__init__(self) self.name = 'TransitionToProgram' self.dataout['with-transition'] = with_transition", "sourceName): Baserequests.__init__(self) self.name = 'GetAudioActive' self.datain['audioActive'] = None self.dataout['sourceName'] =", "visibility/enabled state of a filter :Arguments: *sourceName* type: String Source", "is a group) \"\"\" def __init__(self, item, scene_name=None): Baserequests.__init__(self) self.name", "int (optional) The new alignment of the bounding box. (0-2,", "= None self.datain['chatlog_lines'] = None self.datain['color'] = None self.datain['extents'] =", "settings of the stream (the same as GetStreamSettings). :Arguments: *type*", ":Arguments: *hotkeyName* type: String Unique name of the hotkey, as", "(if `saveToFilePath` was specified in the request) \"\"\" def __init__(self,", "*mediaSources* type: Array<Object> Array of sources *mediaSources.*.sourceName* type: String Unique", "elapsed since recording started (only present if currently recording). *recordingFilename*", "active transition. :Arguments: *transition_name* type: String The name of the", "self.datain['valign'] = None self.datain['vertical'] = None self.dataout['source'] = source def", "multiplied by the vertical scaling factor) *parentGroupName* type: String (optional)", "*item.name* type: String (optional) Scene Item name (if the `item`", "= item self.dataout['scene-name'] = scene_name self.dataout['position'] = position self.dataout['rotation'] =", "boolean Word wrap. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name =", "of this source type *types.*.caps* type: Object Source type capabilities", "on a monitor. Requires OBS v24.0.4 or newer. :Arguments: *type*", "item \"\"\" def __init__(self, sceneName, sourceName, setVisible): Baserequests.__init__(self) self.name =", "from base size *fps* type: double Frames rendered per second", "def getVertical(self): return self.datain['vertical'] class SetTextGDIPlusProperties(Baserequests): \"\"\"Set the current properties", "an `error` if Studio Mode is not enabled. :Arguments: *with_transition*", "scenes (See [GetCurrentScene](#getcurrentscene) for more information). \"\"\" def __init__(self): Baserequests.__init__(self)", "= sourceName self.dataout['setVisible'] = setVisible def getItemId(self): return self.datain['itemId'] class", "self.datain['scene-collections'] class GetSceneItemList(Baserequests): \"\"\"Get a list of all scene items", "= None def getType(self): return self.datain['type'] def getSettings(self): return self.datain['settings']", "self.dataout['with-transition'] = with_transition class EnableStudioMode(Baserequests): \"\"\"Enables Studio Mode. \"\"\" def", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSpecialSources' self.datain['desktop-1'] = None", "getGradient_dir(self): return self.datain['gradient_dir'] def getGradient_opacity(self): return self.datain['gradient_opacity'] def getOutline(self): return", "type: Object (optional) Holds data for the font. Ex: `\"font\":", "def getStreamTimecode(self): return self.datain['stream-timecode'] def getRecTimecode(self): return self.datain['rec-timecode'] def getPreviewOnly(self):", "output size differs from base size *fps* type: double Frames", "Due to processing/network delays, this request is not perfect. The", "maximum of 1.0mul/0.0dB, however OBS actually supports larger values. *useDecibel*", "if recording is already active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "*font.style* type: String Font Style (unknown function). *gradient* type: boolean", "None self.datain['scaleType'] = None self.datain['fps'] = None self.datain['videoFormat'] = None", "Item ID (if the `item` field is an object) :Returns:", "type: int ID of the SceneItem in the scene. \"\"\"", "String Name of the filter to reorder *movementType* type: String", "class GetMediaDuration(Baserequests): \"\"\"Get the length of media in milliseconds. Supports", "useDecibel=None): Baserequests.__init__(self) self.name = 'GetVolume' self.datain['name'] = None self.datain['volume'] =", "on the current state of studio mode). \"\"\" def __init__(self):", "selected transition if supported. :Arguments: *duration* type: int Desired duration", "are controlled in this way. :Arguments: *outputName* type: String Output", "type: int The desired audio sync offset (in nanoseconds). \"\"\"", "*gradient* type: boolean Gradient enabled. *gradient_color* type: int Gradient color.", "Gradient enabled. *gradient_color* type: int (optional) Gradient color. *gradient_dir* type:", "def __init__(self, sourceName, sourceType=None): Baserequests.__init__(self) self.name = 'GetSourceSettings' self.datain['sourceName'] =", "outputName): Baserequests.__init__(self) self.name = 'GetOutputInfo' self.datain['outputInfo'] = None self.dataout['outputName'] =", "*scene* type: String (optional) Name of the scene the scene", "scene. :Arguments: *sceneName* type: String Name of the scene to", "a comma-separated list string \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "streaming service configuration, usually `rtmp_custom` or `rtmp_common`. *settings* type: Object", ":Arguments: *sourceName* type: String (optional) Source name. Note that, since", "the streaming service. *settings.password* type: String (optional) The password for", "type: boolean (optional) Outline. *outline_color* type: int (optional) Outline color.", ":Arguments: *scene* type: String (optional) Name of the scene to", "successive T-Bar moves (e.g. : in an animation, or in", "ffmpeg and vlc media sources (as of OBS v25.0.8) Note:", "getVersion(self): return self.datain['version'] def getObsWebsocketVersion(self): return self.datain['obs-websocket-version'] def getObsStudioVersion(self): return", "scene. *sources* type: Array<SceneItem> Ordered list of the current scene's", "scene. :Arguments: *scene_name* type: String Name of the scene to", "The publish URL. *settings.key* type: String (optional) The publish key.", "list string (e.g. : \"Method1,Method2,Method3\"). *supported_image_export_formats* type: String List of", "self.datain['sourceName'] def getSourceType(self): return self.datain['sourceType'] def getSourceSettings(self): return self.datain['sourceSettings'] class", "Baserequests.__init__(self) self.name = 'SaveStreamSettings' class SendCaptions(Baserequests): \"\"\"Send the provided text", "setVisible=None): Baserequests.__init__(self) self.name = 'CreateSource' self.datain['itemId'] = None self.dataout['sourceName'] =", "def __init__(self, duration): Baserequests.__init__(self) self.name = 'SetTransitionDuration' self.dataout['duration'] = duration", "Key (Mac) \"\"\" def __init__(self, keyId, keyModifiers): Baserequests.__init__(self) self.name =", "item in a scene. In other words, this is how", "position. \"\"\" def __init__(self, sourceName, timeOffset): Baserequests.__init__(self) self.name = 'ScrubMedia'", "type: Object Updated source settings \"\"\" def __init__(self, sourceName, sourceSettings,", "Baserequests.__init__(self) self.name = 'GetAudioActive' self.datain['audioActive'] = None self.dataout['sourceName'] = sourceName", "type: String (optional) *salt* type: String (optional) \"\"\" def __init__(self):", "milliseconds since the start of the media. \"\"\" def __init__(self,", "of the transition if transition is not fixed. Defaults to", "source item. *left* type: int Pixel position of the left", "Change the active transition before switching scenes. Defaults to the", "current scene collection. :Returns: *sc_name* type: String Name of the", "def __init__(self): Baserequests.__init__(self) self.name = 'StartStopStreaming' class StartStreaming(Baserequests): \"\"\"Start streaming.", "SetTextGDIPlusProperties(Baserequests): \"\"\"Set the current properties of a Text GDI Plus", "is preserved if only one of these two parameters is", "self.datain['obs-studio-version'] def getAvailableRequests(self): return self.datain['available-requests'] def getSupportedImageExportFormats(self): return self.datain['supported-image-export-formats'] class", "scene to the main output. Will return an `error` if", "position of the source. *position.alignment* type: int (optional) The new", "`\"font\": { \"face\": \"Arial\", \"flags\": 0, \"size\": 150, \"style\": \"\"", "filter name :Returns: *enabled* type: Boolean Filter status (enabled or", "Source name *img* type: String Image Data URI (if `embedPictureFormat`", "Baserequests.__init__(self) self.name = 'ReorderSceneItems' self.dataout['items'] = items self.dataout['scene'] = scene", "projector: `Preview` (default), `Source`, `Scene`, `StudioProgram`, or `Multiview` (case insensitive).", "publish key of the stream. *stream.settings.use_auth* type: boolean (optional) Indicates", "*itemId* type: int ID of the SceneItem in the scene.", "def getGradient_color(self): return self.datain['gradient_color'] def getGradient_dir(self): return self.datain['gradient_dir'] def getGradient_opacity(self):", "type: String obs-websocket plugin version. *obs_studio_version* type: String OBS Studio", "and recording status. :Returns: *streaming* type: boolean Current streaming status.", "type: boolean (optional) Set the created SceneItem as visible or", "Name of the item's parent (if this item belongs to", "x_scale self.dataout['y-scale'] = y_scale self.dataout['rotation'] = rotation self.dataout['scene-name'] = scene_name", "current streaming service type, all settings are required. Returns the", "the source that the item is manipulated from. The sum", "\"\"\"Set the duration of the currently selected transition if supported.", "= None self.datain['sourceSettings'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceType'] =", "__init__(self, sc_name): Baserequests.__init__(self) self.name = 'SetCurrentSceneCollection' self.dataout['sc-name'] = sc_name class", "*transitionSettings* type: Object Current transition settings \"\"\" def __init__(self, transitionName):", "the current streaming service type, all settings are required. Returns", "needs to perform multiple successive T-Bar moves (e.g. : in", "source scene (required) *item.name* type: String Scene Item name (prefer", "*types.*.caps* type: Object Source type capabilities *types.*.caps.isAsync* type: Boolean True", "is_local_file self.dataout['local_file'] = local_file self.dataout['url'] = url self.dataout['css'] = css", "self.dataout['sourceName'] = sourceName def getMonitorType(self): return self.datain['monitorType'] class SetAudioMonitorType(Baserequests): \"\"\"Set", "String Scene Item name. *itemId* type: int Scene Item ID.", "set. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'GetSceneTransitionOverride' self.datain['transitionName']", "of the transition. \"\"\" def __init__(self, transition_name): Baserequests.__init__(self) self.name =", "scene item's source. Either `input`, `group`, or `scene` \"\"\" def", "Item name. *render* type: boolean true = shown ; false", "animation, or in response to a user moving a T-Bar", "type: Boolean New filter state \"\"\" def __init__(self, sourceName, filterName,", "Output info \"\"\" def __init__(self, outputName): Baserequests.__init__(self) self.name = 'GetOutputInfo'", "x position of the source. *position.y* type: double (optional) The", "= 'GetTextGDIPlusProperties' self.datain['source'] = None self.datain['align'] = None self.datain['bk_color'] =", "object. False entries can be ommitted *keyModifiers.shift* type: boolean Trigger", "boolean true = shown ; false = hidden \"\"\" def", "to be added *setVisible* type: boolean Whether to make the", "not. Defaults to true :Returns: *itemId* type: int ID of", "the order of scene items in the requested scene. :Arguments:", "one of the following: \"input\", \"filter\", \"transition\" or \"other\" *types.*.defaultSettings*", "the given stream type, all settings must be specified in", "as Inf. Note: The OBS volume sliders only reach a", "(optional) Name of the scene to copy the item from.", "return self.datain['height'] def getFps(self): return self.datain['fps'] def getShutdown(self): return self.datain['shutdown']", "Defaults to the current scene. *item* type: Object Scene item", "String Url. *css* type: String CSS to inject. *width* type:", "the scene to create. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name", "scene items in a scene. :Arguments: *sceneName* type: String (optional)", ": \"Method1,Method2,Method3\"). *supported_image_export_formats* type: String List of supported formats for", "\"\"\" Note: Controlling outputs is an experimental feature of obs-websocket.", "mute class ToggleMute(Baserequests): \"\"\"Inverts the mute status of a specified", "to pause or play the source. `false` for play, `true`", "name :Returns: *enabled* type: Boolean Filter status (enabled or not)", ":Returns: *enabled* type: Boolean Filter status (enabled or not) *type*", "scene item. Sufficiently unique if no scene items share sources", "set. *transitionDuration* type: int Transition duration. `-1` if no override", "wrap. *extents_cx* type: int (optional) Extents cx. *extents_cy* type: int", "__init__(self, item, x_scale, y_scale, rotation, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemTransform'", "= 'GetStreamingStatus' self.datain['streaming'] = None self.datain['recording'] = None self.datain['stream-timecode'] =", "= None self.datain['imageFile'] = None self.dataout['sourceName'] = sourceName self.dataout['embedPictureFormat'] =", "of supported formats for features that use image export (like", "= None self.datain['read_from_file'] = None self.datain['font'] = None self.datain['gradient'] =", "type: int New item ID *item.name* type: String New item", "of the transition. *with_transition.duration* type: int (optional) Transition duration (in", "of the plugin and the API. :Returns: *version* type: double", "*crop.top* type: int The number of pixels cropped off the", "\"\"\"Get the audio monitoring type of the specified source. :Arguments:", "= transitionName self.dataout['transitionDuration'] = transitionDuration class RemoveSceneTransitionOverride(Baserequests): \"\"\"Remove any transition", "ReleaseTBar(Baserequests): \"\"\"Release the T-Bar (like a user releasing their mouse", "'SetSceneTransitionOverride' self.dataout['sceneName'] = sceneName self.dataout['transitionName'] = transitionName self.dataout['transitionDuration'] = transitionDuration", "= 'GetTransitionDuration' self.datain['transition-duration'] = None def getTransitionDuration(self): return self.datain['transition-duration'] class", "these won't be saved to OBS' configuration. *stream.type* type: String", "name of the current profile. :Returns: *profile_name* type: String Name", "Clients can specify `width` and `height` parameters to receive scaled", "streaming server. *settings.username* type: String The username to use when", "getItemId(self): return self.datain['itemId'] class DuplicateSceneItem(Baserequests): \"\"\"Duplicates a scene item. :Arguments:", "scene. :Arguments: *sourceName* type: String Source name. *sourceKind* type: String", "*types.*.type* type: String Type. Value is one of the following:", "self.datain['filename-formatting'] = None def getFilenameFormatting(self): return self.datain['filename-formatting'] class GetStats(Baserequests): \"\"\"Get", "name *sources.*.typeId* type: String Non-unique source internal type (a.k.a kind)", "currently selected transition if supported. :Returns: *transition_duration* type: int Duration", "of available profiles. :Returns: *profiles* type: Array<Object> List of available", "source): Baserequests.__init__(self) self.name = 'GetMute' self.datain['name'] = None self.datain['muted'] =", "= 'GetAudioActive' self.datain['audioActive'] = None self.dataout['sourceName'] = sourceName def getAudioActive(self):", "= toScene def getScene(self): return self.datain['scene'] def getItem(self): return self.datain['item']", "self.datain['recordTimecode'] = None self.datain['recordingFilename'] = None def getIsRecording(self): return self.datain['isRecording']", "int Background color. *bk_opacity* type: int Background opacity (0-100). *chatlog*", "Name of the source. *align* type: String (optional) Text Alignment", "type: double OBSRemote compatible API version. Fixed to 1.1 for", "from `GetSourceTypesList`. :Arguments: *sourceName* type: String Name of the source", "that, since scenes are also sources, you can also provide", "def getSceneName(self): return self.datain['sceneName'] def getSceneItems(self): return self.datain['sceneItems'] class GetSceneItemProperties(Baserequests):", "type: String (optional) Font Style (unknown function). *gradient* type: boolean", "Name of the new filter *filterType* type: String Filter type", "around). \"\"\" def __init__(self, sourceName, sourceType=None): Baserequests.__init__(self) self.name = 'GetSourceSettings'", "def getFont(self): return self.datain['font'] def getGradient(self): return self.datain['gradient'] def getGradient_color(self):", "type: Object New settings. These will be merged to the", "def getLog_mode(self): return self.datain['log_mode'] def getOutline(self): return self.datain['outline'] def getText(self):", "file. *log_mode* type: boolean Chat log. *outline* type: boolean Outline.", "word_wrap=None): Baserequests.__init__(self) self.name = 'SetTextFreetype2Properties' self.dataout['source'] = source self.dataout['color1'] =", "name *filterName* type: String Source filter name *filterEnabled* type: Boolean", "self.name = 'StopReplayBuffer' class SaveReplayBuffer(Baserequests): \"\"\"Flush and save the contents", "None self.datain['scale'] = None self.datain['crop'] = None self.datain['visible'] = None", "item self.dataout['top'] = top self.dataout['bottom'] = bottom self.dataout['left'] = left", "scale of the item. *scale.y* type: double (optional) The new", "given. \"\"\" def __init__(self, sceneName, transitionName, transitionDuration): Baserequests.__init__(self) self.name =", "type: boolean Outline. *text* type: String Text content to be", "caption data. :Arguments: *text* type: String Captions text \"\"\" def", "*sceneItems.*.sourceName* type: String Name of the scene item's source *sceneItems.*.sourceType*", "over. :Arguments: *position* type: double T-Bar position. This value must", "status of the source. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name", "current properties of a Text GDI Plus source. :Arguments: *source*", "T-Bar moves (e.g. : in an animation, or in response", "filterName def getEnabled(self): return self.datain['enabled'] def getType(self): return self.datain['type'] def", "filter to reorder *newIndex* type: Integer Desired position of the", "is monitored and shouldn't be \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "String ID if the scene item's source. For example `vlc_source`", "String Source name. *color1* type: int (optional) Gradient top color.", "'GetCurrentScene' self.datain['name'] = None self.datain['sources'] = None def getName(self): return", "x_scale, y_scale, rotation, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemTransform' self.dataout['item'] =", "geometry encoding](https://doc.qt.io/qt-5/qwidget.html#saveGeometry). Corresponds to OBS's saved projectors. *name* type: String", "v25.0.8) Note: Due to processing/network delays, this request is not", "Source name. *useDecibel* type: boolean (optional) Output volume in decibels", "opacity (0-100). *text* type: String Text content to be displayed.", "type: String (optional) The publish key. *settings.use_auth* type: boolean (optional)", "self.datain['sourceType'] def getSourceSettings(self): return self.datain['sourceSettings'] class GetTextGDIPlusProperties(Baserequests): \"\"\"Get the current", "bk_opacity self.dataout['chatlog'] = chatlog self.dataout['chatlog_lines'] = chatlog_lines self.dataout['color'] = color", "getRecordingFilename(self): return self.datain['recordingFilename'] class StartStopRecording(Baserequests): \"\"\"Toggle recording on or off", "already paused. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'PauseRecording' class", "= bk_color self.dataout['bk_opacity'] = bk_opacity self.dataout['chatlog'] = chatlog self.dataout['chatlog_lines'] =", "def getName(self): return self.datain['name'] def getDuration(self): return self.datain['duration'] class SetCurrentTransition(Baserequests):", "String OBS Studio program version. *available_requests* type: String List of", "self.datain['name'] def getDuration(self): return self.datain['duration'] class SetCurrentTransition(Baserequests): \"\"\"Set the active", "`error`, `unknown` \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetMediaSourcesList' self.datain['mediaSources']", "`error` if Studio Mode is not enabled. :Arguments: *with_transition* type:", "self.datain['outline'] = None self.datain['text'] = None self.datain['text_file'] = None self.datain['word_wrap']", "sourceName, filterName): Baserequests.__init__(self) self.name = 'GetSourceFilterInfo' self.datain['enabled'] = None self.datain['type']", "def __init__(self, sourceName, monitorType): Baserequests.__init__(self) self.name = 'SetAudioMonitorType' self.dataout['sourceName'] =", "hotkey routines depending on user settings :Arguments: *keyId* type: String", "= outline self.dataout['text'] = text self.dataout['text_file'] = text_file self.dataout['word_wrap'] =", "def getTransitionSettings(self): return self.datain['transitionSettings'] class SetTransitionSettings(Baserequests): \"\"\"Change the current settings", "self.datain['types'] = None def getTypes(self): return self.datain['types'] class GetVolume(Baserequests): \"\"\"Get", "specified source. Useful for type-checking if you expect a specific", "the scene specific properties of the specified source item. Coordinates", "100 is largest file/least compression. Varies with image type. *width*", "= None self.datain['height'] = None self.datain['fps'] = None self.datain['shutdown'] =", "true. \"\"\" def __init__(self, position, release=None): Baserequests.__init__(self) self.name = 'SetTBarPosition'", "with. -1 is automatic, 1 is smallest file/most compression, 100", "\"\"\"Get the volume of the specified source. Default response uses", "type: double (optional) The new height of the bounding box.", "`release` to false and call `ReleaseTBar` later once the animation/interaction", "__init__(self, transition_name): Baserequests.__init__(self) self.name = 'SetCurrentTransition' self.dataout['transition-name'] = transition_name class", "class TakeSourceScreenshot(Baserequests): \"\"\" At least `embedPictureFormat` or `saveToFilePath` must be", "of a transition :Arguments: *transitionName* type: String Transition name *transitionSettings*", "y self.dataout['scene-name'] = scene_name class SetSceneItemTransform(Baserequests): \"\"\"Set the transform of", "None self.datain['word_wrap'] = None self.dataout['source'] = source def getSource(self): return", "*transitionDuration* type: int (Optional) Duration in milliseconds of the transition", "self.name = 'SetSceneItemCrop' self.dataout['item'] = item self.dataout['top'] = top self.dataout['bottom']", "OBS actually supports larger values. *useDecibel* type: boolean (optional) Interperet", "on a scene. :Arguments: *sceneName* type: String Name of the", "*css* type: String CSS to inject. *width* type: int Width.", "def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentProfile' self.datain['profile-name'] = None def", "*bounds.type* type: String (optional) The new bounds type of the", "self.datain['profiles'] class GetRecordingStatus(Baserequests): \"\"\"Get current recording status. :Returns: *isRecording* type:", "on 2020-12-20 18:26:33.661372) # from .base_classes import Baserequests class GetVersion(Baserequests):", "100 to write the image with. -1 is automatic, 1", "List of available profiles. *profiles.*.profile_name* type: String Filter name \"\"\"", "self.datain['extents_cx'] def getExtents_cy(self): return self.datain['extents_cy'] def getFile(self): return self.datain['file'] def", "self.dataout['height'] = height self.dataout['fps'] = fps self.dataout['shutdown'] = shutdown self.dataout['render']", "of obs-websocket. Some plugins which add outputs to OBS may", "Boolean Filter status (enabled or not) *filters.*.type* type: String Filter", "offset class GetSyncOffset(Baserequests): \"\"\"Get the audio sync offset of a", "obs-websocket plugin version. *obs_studio_version* type: String OBS Studio program version.", "*color2* type: int Gradient bottom color. *custom_width* type: int Custom", "EnableStudioMode(Baserequests): \"\"\"Enables Studio Mode. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "source. :Arguments: *source* type: String Source name. *mute* type: boolean", "of the current scene's source items. \"\"\" def __init__(self): Baserequests.__init__(self)", "def getFrom_file(self): return self.datain['from_file'] def getLog_mode(self): return self.datain['log_mode'] def getOutline(self):", "String Name of the new filter *filterType* type: String Filter", "the font. Ex: `\"font\": { \"face\": \"Arial\", \"flags\": 0, \"size\":", "shutdown when not visible. *render* type: boolean (optional) Visibility of", "Scene collection name \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListSceneCollections'", "String Unique name of the hotkey, as defined when registering", "__init__(self): Baserequests.__init__(self) self.name = 'GetTransitionList' self.datain['current-transition'] = None self.datain['transitions'] =", "group) \"\"\" def __init__(self, item, scene_name=None): Baserequests.__init__(self) self.name = 'GetSceneItemProperties'", "source to be added *setVisible* type: boolean Whether to make", "Baserequests.__init__(self) self.name = 'EnableStudioMode' class DisableStudioMode(Baserequests): \"\"\"Disables Studio Mode. \"\"\"", "self.datain['fps'] = None self.datain['videoFormat'] = None self.datain['colorSpace'] = None self.datain['colorRange']", "String Main key identifier (e.g. `OBS_KEY_A` for key \"A\"). Available", "boolean Desired mute status. \"\"\" def __init__(self, source, mute): Baserequests.__init__(self)", "list \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListOutputs' self.datain['outputs'] =", "OBS v24.0.4 or newer. :Arguments: *type* type: String (Optional) Type", "media for that source. States: `none`, `playing`, `opening`, `buffering`, `paused`,", "None def getIsReplayBufferActive(self): return self.datain['isReplayBufferActive'] class StartStopReplayBuffer(Baserequests): \"\"\"Toggle the Replay", "\"\"\" def __init__(self, item, top, bottom, left, right, scene_name=None): Baserequests.__init__(self)", ":Returns: *outputs* type: Array<Output> Outputs list \"\"\" def __init__(self): Baserequests.__init__(self)", "(optional) *salt* type: String (optional) \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "type: String Source name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name", "self.dataout['color1'] = color1 self.dataout['color2'] = color2 self.dataout['custom_width'] = custom_width self.dataout['drop_shadow']", "scene the source item belongs to. Defaults to the current", "(defaults to current). *items* type: Array<Scene> Ordered list of objects", "if not specified. :Returns: *sceneName* type: String Name of the", "\"\"\"Start recording into the Replay Buffer. Will return an `error`", "*bounds.x* type: double Width of the bounding box. *bounds.y* type:", "or create a projector on a monitor. Requires OBS v24.0.4", "Height. *fps* type: int Framerate. *shutdown* type: boolean Indicates whether", "= playPause class RestartMedia(Baserequests): \"\"\"Restart a media source. Supports ffmpeg", "Supports only vlc media source (as of OBS v25.0.8) :Arguments:", "Mic/Aux input source. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSpecialSources'", "The new amount of pixels cropped off the top of", "*colorRange* type: String Color range (full or partial) \"\"\" def", "RestartMedia(Baserequests): \"\"\"Restart a media source. Supports ffmpeg and vlc media", "*YOU MUST CALL THIS if you called `SetTBarPosition` with the", "Baserequests.__init__(self) self.name = 'SetVolume' self.dataout['source'] = source self.dataout['volume'] = volume", "a source, obs-websocket will return an error. :Arguments: *sourceName* type:", "SaveStreamSettings(Baserequests): \"\"\"Save the current streaming server settings to disk. \"\"\"", "shown ; false = hidden \"\"\" def __init__(self, source, render,", "source def getSource(self): return self.datain['source'] def getIs_local_file(self): return self.datain['is_local_file'] def", "input source. *mic_2* type: String (optional) Name of the second", "Baserequests.__init__(self) self.name = 'GetFilenameFormatting' self.datain['filename-formatting'] = None def getFilenameFormatting(self): return", "css=None, width=None, height=None, fps=None, shutdown=None, render=None): Baserequests.__init__(self) self.name = 'SetBrowserSourceProperties'", "for the streaming service. *settings.password* type: String (optional) The password", "of transitions. *transitions.*.name* type: String Name of the transition. \"\"\"", "self.datain['audioActive'] = None self.dataout['sourceName'] = sourceName def getAudioActive(self): return self.datain['audioActive']", "of the source. *position.y* type: double (optional) The new y", "Baserequests.__init__(self) self.name = 'GetMute' self.datain['name'] = None self.datain['muted'] = None", "Chat log lines. *color* type: int Text color. *extents* type:", "color. *outline_size* type: int (optional) Outline size. *outline_opacity* type: int", "def getSources(self): return self.datain['sources'] class SetPreviewScene(Baserequests): \"\"\"Set the active preview", "type: String Color space for YUV *colorRange* type: String Color", "way. :Arguments: *outputName* type: String Output name \"\"\" def __init__(self,", "the scene item's source. For example `vlc_source` or `image_source` *sceneItems.*.sourceName*", "= 'DuplicateSceneItem' self.datain['scene'] = None self.datain['item'] = None self.dataout['item'] =", "picture. Can be \"png\", \"jpg\", \"jpeg\" or \"bmp\" (or any", "String Name of the transition. *with_transition.duration* type: int (optional) Transition", "\"\"\"Attempt to authenticate the client to the server. :Arguments: *auth*", "once the animation/interaction is over. :Arguments: *position* type: double T-Bar", "self.dataout['chatlog_lines'] = chatlog_lines self.dataout['color'] = color self.dataout['extents'] = extents self.dataout['extents_cx']", "type: int (optional) Outline size. *outline_opacity* type: int (optional) Outline", ":Returns: *name* type: String Source name. *offset* type: int The", "transitionName self.dataout['transitionDuration'] = transitionDuration class RemoveSceneTransitionOverride(Baserequests): \"\"\"Remove any transition override", "be saved to OBS' configuration. *stream.type* type: String (optional) If", "rec_folder class GetRecordingFolder(Baserequests): \"\"\"Get the path of the current recording", "width. *height* type: int (optional) Screenshot height. Defaults to the", "__init__(self, sourceName, filterName, movementType): Baserequests.__init__(self) self.name = 'MoveSourceFilter' self.dataout['sourceName'] =", "streaming service type, all settings are required. Returns the full", "def getMediaDuration(self): return self.datain['mediaDuration'] class GetMediaTime(Baserequests): \"\"\"Get the current timestamp", "getName(self): return self.datain['name'] def getSettings(self): return self.datain['settings'] class AddFilterToSource(Baserequests): \"\"\"Add", "sourceName self.dataout['timestamp'] = timestamp class ScrubMedia(Baserequests): \"\"\"Scrub media using a", "\"\"\" def __init__(self, sourceName, filterName, filterType, filterSettings): Baserequests.__init__(self) self.name =", "*studio_mode* type: boolean Indicates if Studio Mode is enabled. \"\"\"", "specified. :Returns: *sceneName* type: String Name of the requested (or", "\"\"\"Sets the mute status of a specified source. :Arguments: *source*", "self.dataout['scene'] = scene class AddSceneItem(Baserequests): \"\"\"Creates a scene item in", "sourceName): Baserequests.__init__(self) self.name = 'PreviousMedia' self.dataout['sourceName'] = sourceName class GetMediaDuration(Baserequests):", "server. Only present if `use_auth` is `true`. \"\"\" def __init__(self):", "'SetAudioMonitorType' self.dataout['sourceName'] = sourceName self.dataout['monitorType'] = monitorType class TakeSourceScreenshot(Baserequests): \"\"\"", "(optional) The new alignment of the source. *rotation* type: double", "Baserequests.__init__(self) self.name = 'GetMediaSourcesList' self.datain['mediaSources'] = None def getMediaSources(self): return", "of 1.0mul/0.0dB, however OBS actually supports larger values. *useDecibel* type:", "name :Returns: *filters* type: Array<Object> List of filters for the", "SetCurrentTransition(Baserequests): \"\"\"Set the active transition. :Arguments: *transition_name* type: String The", "= 'SetVolume' self.dataout['source'] = source self.dataout['volume'] = volume self.dataout['useDecibel'] =", "def getIs_local_file(self): return self.datain['is_local_file'] def getLocal_file(self): return self.datain['local_file'] def getUrl(self):", "not be fully duplicated *types.*.caps.doNotSelfMonitor* type: Boolean True if sources", "must be specified in the `settings` object or an error", "self.dataout['source'] = source self.dataout['mute'] = mute class ToggleMute(Baserequests): \"\"\"Inverts the", "self.dataout['source'] = source def getSource(self): return self.datain['source'] def getIs_local_file(self): return", "Baserequests.__init__(self) self.name = 'CreateSource' self.datain['itemId'] = None self.dataout['sourceName'] = sourceName", "transitionDuration class RemoveSceneTransitionOverride(Baserequests): \"\"\"Remove any transition override on a scene.", ":Arguments: *sourceName* type: String Source name. :Returns: *mediaDuration* type: int", "about a single output :Arguments: *outputName* type: String Output name", "opacity (0-100). *outline* type: boolean (optional) Outline. *outline_color* type: int", "currently active scene collection. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "String Filter name \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListProfiles'", "(absolute index positioning) :Arguments: *sourceName* type: String Name of the", "return self.datain['recording'] def getStreamTimecode(self): return self.datain['stream-timecode'] def getRecTimecode(self): return self.datain['rec-timecode']", "= 'DeleteSceneItem' self.dataout['item'] = item self.dataout['scene'] = scene class AddSceneItem(Baserequests):", "def getSettings(self): return self.datain['settings'] class AddFilterToSource(Baserequests): \"\"\"Add a new filter", "a Text GDI Plus source. :Arguments: *source* type: String Source", "Text content to be displayed. *valign* type: String (optional) Text", "def getMediaSources(self): return self.datain['mediaSources'] class CreateSource(Baserequests): \"\"\"Create a source and", "getTransitionSettings(self): return self.datain['transitionSettings'] class SetTransitionSettings(Baserequests): \"\"\"Change the current settings of", "has also not been tested. :Arguments: *sourceName* type: String Source", "None def getTypes(self): return self.datain['types'] class GetVolume(Baserequests): \"\"\"Get the volume", "Filter type *filters.*.name* type: String Filter name *filters.*.settings* type: Object", "boolean (optional) Force stop (default: false) \"\"\" def __init__(self, outputName,", "not passed will remain unchanged. Returns the updated settings in", "Baserequests.__init__(self) self.name = 'SetTBarPosition' self.dataout['position'] = position self.dataout['release'] = release", "getOutputs(self): return self.datain['outputs'] class GetOutputInfo(Baserequests): \"\"\"Get information about a single", "Baserequests.__init__(self) self.name = 'SetStreamSettings' self.dataout['type'] = type self.dataout['settings'] = settings", ":Arguments: *keyId* type: String Main key identifier (e.g. `OBS_KEY_A` for", "the source. *is_local_file* type: boolean (optional) Indicates that a local", "source. Between `0.0` and `20.0` if using mul, under `26.0`", "*font.size* type: int (optional) Font text size. *font.style* type: String", "*scene_name* type: String The name of the scene to preview.", "if recording is not active or not paused. \"\"\" def", "coding: utf-8 -*- # THIS FILE WAS GENERATED BY generate_classes.py", "= 'SetSyncOffset' self.dataout['source'] = source self.dataout['offset'] = offset class GetSyncOffset(Baserequests):", "these two parameters is specified. :Arguments: *sourceName* type: String (optional)", "self.name = 'GetReplayBufferStatus' self.datain['isReplayBufferActive'] = None def getIsReplayBufferActive(self): return self.datain['isReplayBufferActive']", "def __init__(self, type, settings, save): Baserequests.__init__(self) self.name = 'SetStreamSettings' self.dataout['type']", "'GetSourceFilters' self.datain['filters'] = None self.dataout['sourceName'] = sourceName def getFilters(self): return", "the current settings of a transition :Arguments: *transitionName* type: String", "wrap. *extents_cx* type: int Extents cx. *extents_cy* type: int Extents", "\"bmp\" (or any other value supported by Qt's Image module)", "a scene by scene basis. *items.*.name* type: String (optional) Name", "sourceName, filterName, filterEnabled): Baserequests.__init__(self) self.name = 'SetSourceFilterVisibility' self.dataout['sourceName'] = sourceName", "opacity (0-100). *text* type: String (optional) Text content to be", "None self.datain['obs-studio-version'] = None self.datain['available-requests'] = None self.datain['supported-image-export-formats'] = None", "duration can be off by upwards of 50ms. :Arguments: *sourceName*", "name *transitionSettings* type: Object Transition settings (they can be partial)", "bound combination of keys. A single key combination might trigger", "def getPosition(self): return self.datain['position'] class GetTransitionSettings(Baserequests): \"\"\"Get the current settings", "text from the specified file. *log_mode* type: boolean Chat log.", "which add outputs to OBS may not function properly when", "Used to pass data to the RTMP service about the", "transition. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentTransition' self.datain['name'] =", "class StartStopRecording(Baserequests): \"\"\"Toggle recording on or off (depending on the", "*sourceName* type: String Source name. :Returns: *timestamp* type: int The", "server. Ignored if `use_auth` is not set to `true`. *stream.settings.password*", "self.datain['monitorType'] = None self.dataout['sourceName'] = sourceName def getMonitorType(self): return self.datain['monitorType']", "the source before scaling. *crop.right* type: int (optional) The new", "*mediaSources.*.sourceKind* type: String Unique source internal type (a.k.a `ffmpeg_source` or", "String Source name. *timestamp* type: int Milliseconds to set the", "= 'AddSceneItem' self.datain['itemId'] = None self.dataout['sceneName'] = sceneName self.dataout['sourceName'] =", "the currently selected transition in the frontend's dropdown menu. :Returns:", "*profile_name* type: String Name of the desired profile. \"\"\" def", "None self.datain['file'] = None self.datain['read_from_file'] = None self.datain['font'] = None", "saved to OBS' configuration. *stream.type* type: String (optional) If specified", "class GetTextFreetype2Properties(Baserequests): \"\"\"Get the current properties of a Text Freetype", "release=None): Baserequests.__init__(self) self.name = 'SetTBarPosition' self.dataout['position'] = position self.dataout['release'] =", "pictures. Aspect ratio is preserved if only one of these", "mul format, NOT SLIDER PERCENTAGE. :Arguments: *source* type: String Source", "of a specified source. :Arguments: *sourceName* type: String Source name.", "self.name = 'GetTransitionList' self.datain['current-transition'] = None self.datain['transitions'] = None def", "bottom of the source item. *left* type: int Pixel position", "output :Arguments: *outputName* type: String Output name :Returns: *outputInfo* type:", "self.dataout['transitionName'] = transitionName def getTransitionSettings(self): return self.datain['transitionSettings'] class SetTransitionSettings(Baserequests): \"\"\"Change", "'SetCurrentTransition' self.dataout['transition-name'] = transition_name class SetTransitionDuration(Baserequests): \"\"\"Set the duration of", "-1 and 100 to write the image with. -1 is", "an object) :Returns: *name* type: String Scene Item name. *itemId*", "current transition (in milliseconds). \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "type *types.*.type* type: String Type. Value is one of the", "type: boolean (optional) Force stop (default: false) \"\"\" def __init__(self,", "of sources *sources.*.name* type: String Unique source name *sources.*.typeId* type:", "usually `rtmp_custom` or `rtmp_common`. *settings* type: Object The actual settings", ":Returns: *scene* type: String Name of the scene where the", "boolean (optional) Indicates whether authentication should be used when connecting", "Studio Mode is not enabled. :Returns: *name* type: String The", "def getObsWebsocketVersion(self): return self.datain['obs-websocket-version'] def getObsStudioVersion(self): return self.datain['obs-studio-version'] def getAvailableRequests(self):", "remain unchanged. Returns the updated settings in response. If 'type'", "__init__(self): Baserequests.__init__(self) self.name = 'GetStreamingStatus' self.datain['streaming'] = None self.datain['recording'] =", "String (optional) The publish key of the stream. *stream.settings.use_auth* type:", "'SetTextFreetype2Properties' self.dataout['source'] = source self.dataout['color1'] = color1 self.dataout['color2'] = color2", "class StartStreaming(Baserequests): \"\"\"Start streaming. Will return an `error` if streaming", "text from the specified file. *log_mode* type: boolean (optional) Chat", "return self.datain['url'] def getCss(self): return self.datain['css'] def getWidth(self): return self.datain['width']", "to the RTMP service about the streaming. May be any", "be effective on the next recording. :Arguments: *rec_folder* type: String", "double (optional) The new x scale of the item. *scale.y*", "(if the `item` field is an object) *position.x* type: double", "self.datain['sourceSettings'] class SetSourceSettings(Baserequests): \"\"\"Set settings of the specified source. :Arguments:", "Ex: `\"font\": { \"face\": \"Arial\", \"flags\": 0, \"size\": 150, \"style\":", "__init__(self, sourceName, sourceType=None): Baserequests.__init__(self) self.name = 'GetSourceSettings' self.datain['sourceName'] = None", "\"\"\"Sets the crop coordinates of the specified source item. :Arguments:", "self.dataout['filename-formatting'] = filename_formatting class GetFilenameFormatting(Baserequests): \"\"\"Get the filename formatting string", "String The media state of the provided source. States: `none`,", "`item` field is an object) :Returns: *name* type: String Scene", "self.dataout['sourceName'] = sourceName class PreviousMedia(Baserequests): \"\"\"Go to the previous media", "the animation/interaction is over. :Arguments: *position* type: double T-Bar position.", "type: int Scene Item ID. *position.x* type: double The x", "class SetSceneItemTransform(Baserequests): \"\"\"Set the transform of the specified source item.", "source item. \"\"\" def __init__(self, item, top, bottom, left, right,", "self.datain['align'] = None self.datain['bk_color'] = None self.datain['bk_opacity'] = None self.datain['chatlog']", "def getWord_wrap(self): return self.datain['word_wrap'] class SetTextFreetype2Properties(Baserequests): \"\"\"Set the current properties", "currently previewed scene and its list of sources. Will return", "getStreamTimecode(self): return self.datain['stream-timecode'] def getRecTimecode(self): return self.datain['rec-timecode'] def getPreviewOnly(self): return", "a list of all available sources types :Returns: *types* type:", "same as GetStreamSettings). :Arguments: *type* type: String The type of", "\"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaTime' self.datain['timestamp'] =", "type, all settings must be specified in the `settings` object", "in OBS' settings. Setting this hotkey is mandatory, even when", "type: bool If the source's transform is locked. *bounds.type* type:", "all available sources types :Returns: *types* type: Array<Object> Array of", "or not the T-Bar gets released automatically after setting its", "order of scene items in the requested scene. :Arguments: *scene*", "(only present if currently streaming). *rec_timecode* type: String (optional) Time", "int Chat log lines. *color* type: int Text color. *extents*", "getText_file(self): return self.datain['text_file'] def getWord_wrap(self): return self.datain['word_wrap'] class SetTextFreetype2Properties(Baserequests): \"\"\"Set", "'SetVolume' self.dataout['source'] = source self.dataout['volume'] = volume self.dataout['useDecibel'] = useDecibel", "def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionDuration' self.datain['transition-duration'] = None def", ":Arguments: *sourceName* type: String Source name. *playPause* type: boolean Whether", "current state of studio mode). \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "number of pixels cropped off the bottom of the source", "type: Boolean True if interaction with this sources of this", "from the specified file. *log_mode* type: boolean Chat log. *outline*", "settings self.dataout['save'] = save class GetStreamSettings(Baserequests): \"\"\"Get the current streaming", "type: String (optional) Time elapsed since recording started (only present", "Array<SceneItem> \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetPreviewScene' self.datain['name'] =", "= text class GetStudioModeStatus(Baserequests): \"\"\"Indicates if Studio Mode is currently", "an object). *item.name* type: String (optional) Scene Item name (if", "*sourceName* type: String Source name :Returns: *filters* type: Array<Object> List", "streaming service configuration. Possible values: 'rtmp_custom' or 'rtmp_common'. *settings* type:", "transition. :Arguments: *transition_name* type: String The name of the transition.", "to true :Returns: *itemId* type: int ID of the SceneItem", "Screenshot width. Defaults to the source's base width. *height* type:", "self.name = 'SetTransitionDuration' self.dataout['duration'] = duration class GetTransitionDuration(Baserequests): \"\"\"Get the", ".base_classes import Baserequests class GetVersion(Baserequests): \"\"\"Returns the latest version of", "extents_cy=None, file=None, read_from_file=None, font=None, gradient=None, gradient_color=None, gradient_dir=None, gradient_opacity=None, outline=None, outline_color=None,", "type: boolean Indicates whether the source is muted. \"\"\" def", "type: String Filter name \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "in response. If 'type' is different than the current streaming", "\"\"\"Change the current settings of a transition :Arguments: *transitionName* type:", "scene_name class SetSceneItemRender(Baserequests): \"\"\"Show or hide a specified source item", "current streaming server settings. :Returns: *type* type: String The type", "self.dataout['bounds'] = bounds class ResetSceneItem(Baserequests): \"\"\"Reset a scene item. :Arguments:", "URI encoded picture. Can be \"png\", \"jpg\", \"jpeg\" or \"bmp\"", "Transition returns 1.0 when not active. \"\"\" def __init__(self): Baserequests.__init__(self)", "releasing their mouse button after moving it). *YOU MUST CALL", "*position.alignment* type: int (optional) The new alignment of the source.", "self.datain['outputs'] = None def getOutputs(self): return self.datain['outputs'] class GetOutputInfo(Baserequests): \"\"\"Get", "size. *font.style* type: String Font Style (unknown function). *gradient* type:", "PERCENTAGE. :Arguments: *source* type: String Source name. *useDecibel* type: boolean", "string. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetFilenameFormatting' self.datain['filename-formatting'] =", "new scene scene. :Arguments: *sceneName* type: String Name of the", "None self.datain['css'] = None self.datain['width'] = None self.datain['height'] = None", "= None self.datain['duration'] = None def getName(self): return self.datain['name'] def", "source is visible. *muted* type: bool If the source is", "getSource(self): return self.datain['source'] def getColor1(self): return self.datain['color1'] def getColor2(self): return", "(optional) Format to save the image file as (one of", "in the requested scene. :Arguments: *scene* type: String (optional) Name", "type: String (optional) Name of the scene to create the", "actual source's type. *sourceSettings* type: Object Source settings (varies between", "position of the bottom of the source item. *left* type:", "and/or id specified. Id preferred due to uniqueness per scene", "item belongs to. Defaults to the currently active scene. *source*", "Empty string if no override is set. *transitionDuration* type: int", "self.datain['obs-websocket-version'] = None self.datain['obs-studio-version'] = None self.datain['available-requests'] = None self.datain['supported-image-export-formats']", "the scene the scene item belongs to. Defaults to the", "for features that use image export (like the TakeSourceScreenshot request", "getSceneCollections(self): return self.datain['scene-collections'] class GetSceneItemList(Baserequests): \"\"\"Get a list of all", "def getTransitionName(self): return self.datain['transitionName'] def getTransitionDuration(self): return self.datain['transitionDuration'] class GetStreamingStatus(Baserequests):", "the currently active profile. :Returns: *current_scene* type: String Name of", "a group) *groupChildren* type: Array<SceneItemTransform> (optional) List of children (if", "'GetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName'] = transitionName def getTransitionSettings(self): return", "of the specified source. Default request format uses mul, NOT", "bounds class ResetSceneItem(Baserequests): \"\"\"Reset a scene item. :Arguments: *scene_name* type:", "a scene item in a scene. In other words, this", "*movementType* type: String How to move the filter around in", "type: boolean Chat log. *chatlog_lines* type: int Chat log lines.", "also not been tested. :Arguments: *sourceName* type: String Source name.", "return self.datain['monitorType'] class SetAudioMonitorType(Baserequests): \"\"\"Set the audio monitoring type of", "*drop_shadow* type: boolean (optional) Drop shadow. *font* type: Object (optional)", "matches the given type (usually 'rtmp_custom' or 'rtmp_common'). If the", "source width multiplied by the horizontal scaling factor) *height* type:", "type: Object (optional) Change the active transition before switching scenes.", "the specified scene. :Arguments: *scene_name* type: String Name of the", "Color range (full or partial) \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "\"\"\"Get the mute status of a specified source. :Arguments: *source*", "authentication parameters `challenge` and `salt` (see \"Authentication\" for more information).", "and vlc media sources (as of OBS v25.0.8) Note: Due", "filterSettings class RemoveFilterFromSource(Baserequests): \"\"\"Remove a filter from a source :Arguments:", "\"center\", \"right\"). *bk_color* type: int Background color. *bk_opacity* type: int", "The clockwise rotation of the item in degrees around the", "self.dataout['scene-name'] = scene_name class SetSceneItemCrop(Baserequests): \"\"\"Sets the crop coordinates of", "color. *extents* type: boolean Extents wrap. *extents_cx* type: int Extents", "type: double The clockwise rotation of the item in degrees", "(optional) Text Alignment (\"left\", \"center\", \"right\"). *bk_color* type: int (optional)", "type: boolean (optional) Read text from the specified file. *log_mode*", "self.dataout['render'] = render self.dataout['scene-name'] = scene_name class SetSceneItemPosition(Baserequests): \"\"\"Sets the", "\"scene\" or \"unknown\" \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSourcesList'", "to avoid settings a set of settings incompatible with the", "the active scene collection. :Arguments: *sc_name* type: String Name of", "ResetSceneItem(Baserequests): \"\"\"Reset a scene item. :Arguments: *scene_name* type: String (optional)", "self.datain['text_file'] def getWord_wrap(self): return self.datain['word_wrap'] class SetTextFreetype2Properties(Baserequests): \"\"\"Set the current", "features that use image export (like the TakeSourceScreenshot request type)", "The processing rate of this request has also not been", "outline_color self.dataout['outline_size'] = outline_size self.dataout['outline_opacity'] = outline_opacity self.dataout['text'] = text", "and position of the projector window (only if monitor is", "26.0 for dB. OBS will interpret dB values under -100.0", "user releasing their mouse button after moving the T-Bar). Call", "*scale.y* type: double The y-scale factor of the source. *crop.top*", "auth): Baserequests.__init__(self) self.name = 'Authenticate' self.dataout['auth'] = auth class SetHeartbeat(Baserequests):", "\"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int Alignment of the bounding", "to. Defaults to the current scene. *item* type: Object Scene", "render class GetSpecialSources(Baserequests): \"\"\"Get configured special sources like Desktop Audio", "String Type of bounding box. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\",", "*mediaSources.*.sourceName* type: String Unique source name *mediaSources.*.sourceKind* type: String Unique", "*transitionName* type: String Transition name *transitionSettings* type: Object Transition settings", "create the item in. Defaults to the current scene. *item*", "left self.dataout['right'] = right self.dataout['scene-name'] = scene_name class DeleteSceneItem(Baserequests): \"\"\"Deletes", "return self.datain['mediaState'] class GetMediaSourcesList(Baserequests): \"\"\"List the media state of all", "more sub-sources *types.*.caps.doNotDuplicate* type: Boolean True if sources of this", "or omit to center on that axis. *rotation* type: double", "(as of OBS v25.0.8) Note: Due to processing/network delays, this", "Outline opacity (0-100). *text* type: String (optional) Text content to", "(optional) Gradient direction. *gradient_opacity* type: int (optional) Gradient opacity (0-100).", "and `height` parameters to receive scaled pictures. Aspect ratio is", "None self.dataout['transitionName'] = transitionName def getTransitionSettings(self): return self.datain['transitionSettings'] class SetTransitionSettings(Baserequests):", "type: String Font Style (unknown function). *gradient* type: boolean Gradient", "to OBS's saved projectors. *name* type: String (Optional) Name of", "type: Boolean Filter status (enabled or not) *type* type: String", "= embedPictureFormat self.dataout['saveToFilePath'] = saveToFilePath self.dataout['fileFormat'] = fileFormat self.dataout['compressionQuality'] =", "None self.datain['name'] = None self.datain['settings'] = None self.dataout['sourceName'] = sourceName", "type: boolean Indicates whether authentication is required. *challenge* type: String", "getTransitions(self): return self.datain['transitions'] class GetCurrentTransition(Baserequests): \"\"\"Get the name of the", "streaming server. Only present if `use_auth` is `true`. *settings.password* type:", "def getTransitions(self): return self.datain['transitions'] class GetCurrentTransition(Baserequests): \"\"\"Get the name of", "__init__(self, source, render, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemRender' self.dataout['source'] =", "first Mic/Aux input source. *mic_2* type: String (optional) Name of", "\"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int", "\"\"\" def __init__(self, sourceName, monitorType): Baserequests.__init__(self) self.name = 'SetAudioMonitorType' self.dataout['sourceName']", "Text content to be displayed. *text_file* type: String (optional) File", "preview scene. *sources* type: Array<SceneItem> \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "*sourceName* type: String Source name *img* type: String Image Data", "scene item. \"\"\" def __init__(self, source, align=None, bk_color=None, bk_opacity=None, chatlog=None,", "'SetCurrentProfile' self.dataout['profile-name'] = profile_name class GetCurrentProfile(Baserequests): \"\"\"Get the name of", "'GetMute' self.datain['name'] = None self.datain['muted'] = None self.dataout['source'] = source", "*settings.password* type: String (optional) The password for the streaming service.", "name. *playPause* type: boolean Whether to pause or play the", "scene collection. \"\"\" def __init__(self, sc_name): Baserequests.__init__(self) self.name = 'SetCurrentSceneCollection'", "*img* type: String Image Data URI (if `embedPictureFormat` was specified", "= None def getStudioMode(self): return self.datain['studio-mode'] class GetPreviewScene(Baserequests): \"\"\"Get the", "the name of the current profile. :Returns: *profile_name* type: String", "*sceneItems.*.itemId* type: int Unique item id of the source item", "(0-100). *outline* type: boolean (optional) Outline. *outline_color* type: int (optional)", "capture source. *desktop_2* type: String (optional) Name of the second", "self.dataout['hotkeyName'] = hotkeyName class TriggerHotkeyBySequence(Baserequests): \"\"\"Executes hotkey routine, identified by", "of the currently selected transition in the frontend's dropdown menu.", "source. Either `input`, `group`, or `scene` \"\"\" def __init__(self, sceneName=None):", "type: boolean (optional) Gradient enabled. *gradient_color* type: int (optional) Gradient", "if Studio Mode is currently enabled. :Returns: *studio_mode* type: boolean", "0, \"size\": 150, \"style\": \"\" }` *font.face* type: String Font", "self.dataout['scene-name'] = scene_name class GetCurrentScene(Baserequests): \"\"\"Get the current scene's name", "if transition is not fixed. Defaults to the current duration", "be merged to the current filter settings. \"\"\" def __init__(self,", "the T-Bar). Call `ReleaseTBar` manually if you set `release` to", "self.dataout['filterSettings'] = filterSettings class RemoveFilterFromSource(Baserequests): \"\"\"Remove a filter from a", "elapsed since recording started (only present if currently recording). *preview_only*", "int Pixel position of the right of the source item.", "type: double Desired volume. Must be between `0.0` and `20.0`", "hotkey. Will return an `error` if the Replay Buffer is", "object) :Returns: *name* type: String Scene Item name. *itemId* type:", "filter settings. \"\"\" def __init__(self, sourceName, filterName, filterSettings): Baserequests.__init__(self) self.name", "sources of this type provide audio *types.*.caps.canInteract* type: Boolean True", "double (optional) The new y scale of the item. *crop.top*", "if you expect a specific settings schema. :Returns: *sourceName* type:", "*y_scale* type: double Height scale factor. *rotation* type: double Source", "Drop shadow. *font* type: Object Holds data for the font.", "def getHeight(self): return self.datain['height'] def getFps(self): return self.datain['fps'] def getShutdown(self):", "the specified source. Default request format uses mul, NOT SLIDER", "source's filter chain. Either \"up\", \"down\", \"top\" or \"bottom\". \"\"\"", "width self.dataout['height'] = height self.dataout['fps'] = fps self.dataout['shutdown'] = shutdown", "or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int Alignment of the bounding box.", "sourceName self.dataout['timeOffset'] = timeOffset class GetMediaState(Baserequests): \"\"\"Get the current playing", "event :Arguments: *enable* type: boolean Starts/Stops emitting heartbeat messages \"\"\"", "type. *sourceSettings* type: Object Source settings (varies between source types,", "\"\"\" def __init__(self, outputName): Baserequests.__init__(self) self.name = 'StartOutput' self.dataout['outputName'] =", "Baserequests.__init__(self) self.name = 'SetCurrentSceneCollection' self.dataout['sc-name'] = sc_name class GetCurrentSceneCollection(Baserequests): \"\"\"Get", "in response to a user moving a T-Bar control in", ":Returns: *mediaSources* type: Array<Object> Array of sources *mediaSources.*.sourceName* type: String", "time in milliseconds since the start of the media. \"\"\"", "source :Arguments: *sourceName* type: String Source name :Returns: *filters* type:", "service. *save* type: boolean Persist the settings to disk. \"\"\"", "that a local file is in use. *local_file* type: String", "*outputName* type: String Output name *force* type: boolean (optional) Force", "scene items share sources within the scene. \"\"\" def __init__(self,", ":Arguments: *sourceName* type: String Source name. \"\"\" def __init__(self, sourceName):", "self.datain['mediaState'] = None self.dataout['sourceName'] = sourceName def getMediaState(self): return self.datain['mediaState']", "source before scaling. *visible* type: bool If the source is", "= None self.datain['scale'] = None self.datain['crop'] = None self.datain['visible'] =", "use a specific transition override. :Arguments: *sceneName* type: String Name", "from. The sum of 1=Left or 2=Right, and 4=Top or", "of this type composite one or more sub-sources *types.*.caps.doNotDuplicate* type:", "*chatlog* type: boolean (optional) Chat log. *chatlog_lines* type: int (optional)", "type: Object Transition settings (they can be partial) :Returns: *transitionSettings*", "self.dataout['log_mode'] = log_mode self.dataout['outline'] = outline self.dataout['text'] = text self.dataout['text_file']", "self.datain['rec-timecode'] = None self.datain['preview-only'] = None def getStreaming(self): return self.datain['streaming']", "*position.x* type: double The x position of the source from", "set to `true`. *stream.settings.password* type: String (optional) If authentication is", "of the media. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name =", "self.dataout['sceneName'] = sceneName self.dataout['transitionName'] = transitionName self.dataout['transitionDuration'] = transitionDuration class", "to be displayed. *text_file* type: String (optional) File path. *word_wrap*", "return self.datain['outputInfo'] class StartOutput(Baserequests): \"\"\" Note: Controlling outputs is an", "self.datain['sourceWidth'] = None self.datain['sourceHeight'] = None self.datain['width'] = None self.datain['height']", "self.datain['rec-timecode'] def getPreviewOnly(self): return self.datain['preview-only'] class StartStopStreaming(Baserequests): \"\"\"Toggle streaming on", "class PauseRecording(Baserequests): \"\"\"Pause the current recording. Returns an error if", "selected transition if supported. :Returns: *transition_duration* type: int Duration of", "boolean Chat log. *chatlog_lines* type: int Chat log lines. *color*", "specified in the request) \"\"\" def __init__(self, sourceName=None, embedPictureFormat=None, saveToFilePath=None,", "basic OBS video information :Returns: *baseWidth* type: int Base (canvas)", "\"right\"). *bk_color* type: int (optional) Background color. *bk_opacity* type: int", "self.datain['sourceName'] = None self.datain['img'] = None self.datain['imageFile'] = None self.dataout['sourceName']", "Source name. *playPause* type: boolean Whether to pause or play", "name (if the `item` field is an object) *item.id* type:", "a scene. In other words, this is how you add", "a window. *geometry* type: String (Optional) Size and position of", "\"\"\"Set current properties for a Browser Source. :Arguments: *source* type:", "Scene Item name. *top* type: int Pixel position of the", "self.datain['transitions'] class GetCurrentTransition(Baserequests): \"\"\"Get the name of the currently selected", "= filterName self.dataout['movementType'] = movementType class SetSourceFilterSettings(Baserequests): \"\"\"Update settings of", "type: String Name of the transition. *with_transition.duration* type: int (optional)", "OBS v25.0.8) :Arguments: *sourceName* type: String Source name. \"\"\" def", "'GetSceneList' self.datain['current-scene'] = None self.datain['scenes'] = None def getCurrentScene(self): return", "return self.datain['font'] def getGradient(self): return self.datain['gradient'] def getGradient_color(self): return self.datain['gradient_color']", "getHeight(self): return self.datain['height'] def getParentGroupName(self): return self.datain['parentGroupName'] def getGroupChildren(self): return", "String Name of the source from which the specified filter", "self.name = 'GetTransitionDuration' self.datain['transition-duration'] = None def getTransitionDuration(self): return self.datain['transition-duration']", "SetBrowserSourceProperties(Baserequests): \"\"\"Set current properties for a Browser Source. :Arguments: *source*", "fps self.dataout['shutdown'] = shutdown self.dataout['render'] = render class GetSpecialSources(Baserequests): \"\"\"Get", "self.datain['mic-1'] = None self.datain['mic-2'] = None self.datain['mic-3'] = None def", "(optional) Name of the scene to get the list of", "specified source item. :Arguments: *scene_name* type: String (optional) Name of", "name. *useDecibel* type: boolean (optional) Output volume in decibels of", "String Unique source name *mediaSources.*.sourceKind* type: String Unique source internal", "def __init__(self): Baserequests.__init__(self) self.name = 'StartStopReplayBuffer' class StartReplayBuffer(Baserequests): \"\"\"Start recording", "Indicates if Studio Mode is enabled. \"\"\" def __init__(self): Baserequests.__init__(self)", "None self.datain['salt'] = None def getAuthRequired(self): return self.datain['authRequired'] def getChallenge(self):", "String Image Data URI (if `embedPictureFormat` was specified in the", "= rotation self.dataout['scale'] = scale self.dataout['crop'] = crop self.dataout['visible'] =", "*local_file* type: String file path. *url* type: String Url. *css*", "currently active scene. *scenes* type: Array<Scene> Ordered list of the", "*settings* type: Object The actual settings of the stream. *settings.server*", "values under -100.0 as Inf. Note: The OBS volume sliders", "int Width. *height* type: int Height. *fps* type: int Framerate.", "= scene_name class SetSceneItemTransform(Baserequests): \"\"\"Set the transform of the specified", "perform multiple successive T-Bar moves (e.g. : in an animation,", "is an object). *item.name* type: String (optional) Scene Item name", "type: boolean Trigger Alt Key *keyModifiers.control* type: boolean Trigger Control", "String Output name \"\"\" def __init__(self, outputName): Baserequests.__init__(self) self.name =", ":Returns: *transitionName* type: String Name of the current overriding transition.", ": in an animation, or in response to a user", "`Source`, `Scene`, `StudioProgram`, or `Multiview` (case insensitive). *monitor* type: int", ":Returns: *rec_folder* type: String Path of the recording folder. \"\"\"", "text size. *font.style* type: String Font Style (unknown function). *from_file*", "the specified source. :Arguments: *sourceName* type: String Source name. *sourceType*", "OBS v25.0.8) :Arguments: *sourceName* type: String Source name. :Returns: *timestamp*", "self.datain['word_wrap'] class SetTextFreetype2Properties(Baserequests): \"\"\"Set the current properties of a Text", "def getItemId(self): return self.datain['itemId'] class DuplicateSceneItem(Baserequests): \"\"\"Duplicates a scene item.", "all settings are required. Returns the full settings of the", "String Name of the source. *align* type: String (optional) Text", "parameters `challenge` and `salt` (see \"Authentication\" for more information). :Returns:", "self.datain['type'] def getName(self): return self.datain['name'] def getSettings(self): return self.datain['settings'] class", "int (optional) Text color. *extents* type: boolean (optional) Extents wrap.", "if recording is not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "top of the source item. *bottom* type: int Pixel position", "*outputWidth* type: int Output width *outputHeight* type: int Output height", "type: String (optional) Text vertical alignment (\"top\", \"center\", \"bottom\"). *vertical*", "*fps* type: int (optional) Framerate. *shutdown* type: boolean (optional) Indicates", "boolean Trigger Control (Ctrl) Key *keyModifiers.command* type: boolean Trigger Command", "\"OBS_BOUNDS_NONE\". *bounds.alignment* type: int (optional) The new alignment of the", "filterName self.dataout['filterType'] = filterType self.dataout['filterSettings'] = filterSettings class RemoveFilterFromSource(Baserequests): \"\"\"Remove", "of the recording folder. \"\"\" def __init__(self, rec_folder): Baserequests.__init__(self) self.name", "the scene to switch to. \"\"\" def __init__(self, scene_name): Baserequests.__init__(self)", "int Base width (without scaling) of the source *sourceHeight* type:", "= None self.datain['crop'] = None self.datain['visible'] = None self.datain['muted'] =", "source :Arguments: *sourceName* type: String Source name. *sourceType* type: String", "String Response to the auth challenge (see \"Authentication\" for more", "called `SetTBarPosition` with the `release` parameter set to `false`.* \"\"\"", "4=Top or 8=Bottom, or omit to center on that axis.", "= sceneName self.dataout['sourceSettings'] = sourceSettings self.dataout['setVisible'] = setVisible def getItemId(self):", "getName(self): return self.datain['name'] def getSources(self): return self.datain['sources'] class SetPreviewScene(Baserequests): \"\"\"Set", "use. *local_file* type: String file path. *url* type: String Url.", "return self.datain['source'] def getIs_local_file(self): return self.datain['is_local_file'] def getLocal_file(self): return self.datain['local_file']", "`false` for play, `true` for pause. \"\"\" def __init__(self, sourceName,", "= None self.dataout['sceneName'] = sceneName def getTransitionName(self): return self.datain['transitionName'] def", "self.dataout['transition-name'] = transition_name class SetTransitionDuration(Baserequests): \"\"\"Set the duration of the", "\"\"\" def __init__(self, sc_name): Baserequests.__init__(self) self.name = 'SetCurrentSceneCollection' self.dataout['sc-name'] =", "self.datain['sceneName'] = None self.datain['sceneItems'] = None self.dataout['sceneName'] = sceneName def", "[GetCurrentScene](#getcurrentscene) for more information). \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "transform is locked. *bounds.type* type: String Type of bounding box.", "name. *timestamp* type: int Milliseconds to set the timestamp to.", "bottom color. *custom_width* type: int Custom width (0 to disable).", "streaming server settings. :Returns: *type* type: String The type of", "filename formatting string :Arguments: *filename_formatting* type: String Filename formatting string", "= volume self.dataout['useDecibel'] = useDecibel class GetMute(Baserequests): \"\"\"Get the mute", "was specified in the request) *imageFile* type: String Absolute path", "self.dataout['profile-name'] = profile_name class GetCurrentProfile(Baserequests): \"\"\"Get the name of the", "the current scene transition override. :Arguments: *sceneName* type: String Name", "Baserequests.__init__(self) self.name = 'SendCaptions' self.dataout['text'] = text class GetStudioModeStatus(Baserequests): \"\"\"Indicates", "(optional) The new amount of pixels cropped off the top", "source. 'true' keeps it in its current position, 'false' allows", "= None self.datain['recording'] = None self.datain['stream-timecode'] = None self.datain['rec-timecode'] =", "\"jpg\", \"jpeg\" or \"bmp\" (or any other value supported by", "current streaming server settings to disk. \"\"\" def __init__(self): Baserequests.__init__(self)", "or not. Default `true` :Returns: *itemId* type: int Numerical ID", "set to `false`.* \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ReleaseTBar'", "the source's transform is locked. *bounds.type* type: String Type of", "class SetSceneItemCrop(Baserequests): \"\"\"Sets the crop coordinates of the specified source", "challenge (see \"Authentication\" for more information). \"\"\" def __init__(self, auth):", "in the chain \"\"\" def __init__(self, sourceName, filterName, newIndex): Baserequests.__init__(self)", "(only present if currently recording). *recordingFilename* type: String (optional) Absolute", "getCurrentScene(self): return self.datain['current-scene'] def getScenes(self): return self.datain['scenes'] class CreateScene(Baserequests): \"\"\"Create", "*is_local_file* type: boolean (optional) Indicates that a local file is", "Name of the source to which the filter belongs *filterName*", "ReorderSourceFilter(Baserequests): \"\"\"Move a filter in the chain (absolute index positioning)", "specified source. :Arguments: *sourceName* type: String Source name. *monitorType* type:", "boolean (optional) Indicates that a local file is in use.", "self.datain['locked'] def getBounds(self): return self.datain['bounds'] def getSourceWidth(self): return self.datain['sourceWidth'] def", "text): Baserequests.__init__(self) self.name = 'SendCaptions' self.dataout['text'] = text class GetStudioModeStatus(Baserequests):", "source self.dataout['offset'] = offset class GetSyncOffset(Baserequests): \"\"\"Get the audio sync", "Baserequests.__init__(self) self.name = 'StopRecording' class PauseRecording(Baserequests): \"\"\"Pause the current recording.", "output. Will return an `error` if Studio Mode is not", "Desktop Audio capture source. *desktop_2* type: String (optional) Name of", "keeps it in its current position, 'false' allows movement. *bounds.type*", "extents_cx=None, extents_cy=None, file=None, read_from_file=None, font=None, gradient=None, gradient_color=None, gradient_dir=None, gradient_opacity=None, outline=None,", "Type of the specified source *sourceSettings* type: Object Source settings", "a user releasing their mouse button after moving it). *YOU", "type: int Font text styling flag. `Bold=1, Italic=2, Bold Italic=3,", "= None self.datain['type'] = None self.datain['name'] = None self.datain['settings'] =", "belongs to. Defaults to the current scene. *item* type: String", "'StopMedia' self.dataout['sourceName'] = sourceName class NextMedia(Baserequests): \"\"\"Skip to the next", "upwards of 50ms. :Arguments: *sourceName* type: String Source name. :Returns:", "__init__(self, sourceName, timeOffset): Baserequests.__init__(self) self.name = 'ScrubMedia' self.dataout['sourceName'] = sourceName", "(optional) The new amount of pixels cropped off the bottom", "the provided text as embedded CEA-608 caption data. :Arguments: *text*", "GetMediaState(Baserequests): \"\"\"Get the current playing state of a media source.", "moving the T-Bar). Call `ReleaseTBar` manually if you set `release`", "\"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetAudioActive' self.datain['audioActive'] =", "(optional) Outline size. *outline_opacity* type: int (optional) Outline opacity (0-100).", ":Returns: *name* type: String Name of the currently active scene.", "getSettings(self): return self.datain['settings'] class AddFilterToSource(Baserequests): \"\"\"Add a new filter to", "used. *embedPictureFormat* type: String (optional) Format of the Data URI", "None def getVersion(self): return self.datain['version'] def getObsWebsocketVersion(self): return self.datain['obs-websocket-version'] def", "= None self.datain['supported-image-export-formats'] = None def getVersion(self): return self.datain['version'] def", ":Returns: *mediaState* type: String The media state of the provided", "self.datain['scaleType'] def getFps(self): return self.datain['fps'] def getVideoFormat(self): return self.datain['videoFormat'] def", "= None self.datain['available-requests'] = None self.datain['supported-image-export-formats'] = None def getVersion(self):", "self.dataout['sourceSettings'] = sourceSettings self.dataout['sourceType'] = sourceType def getSourceName(self): return self.datain['sourceName']", "= 'PlayPauseMedia' self.dataout['sourceName'] = sourceName self.dataout['playPause'] = playPause class RestartMedia(Baserequests):", "The name of the transition. \"\"\" def __init__(self, transition_name): Baserequests.__init__(self)", "'ReorderSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['newIndex'] = newIndex", "'AddSceneItem' self.datain['itemId'] = None self.dataout['sceneName'] = sceneName self.dataout['sourceName'] = sourceName", "Returns the updated settings in response. If 'type' is different", "Freetype 2 source. :Arguments: *source* type: String Source name. :Returns:", "*monitorType* type: String The monitor type to use. Options: `none`,", "audio *types.*.caps.canInteract* type: Boolean True if interaction with this sources", "type: Output Output info \"\"\" def __init__(self, outputName): Baserequests.__init__(self) self.name", "recording folder. :Returns: *rec_folder* type: String Path of the recording", "settings :Arguments: *keyId* type: String Main key identifier (e.g. `OBS_KEY_A`", "= None self.dataout['item'] = item self.dataout['scene-name'] = scene_name def getName(self):", "all connected WebSocket clients :Arguments: *realm* type: String Identifier to", "= fps self.dataout['shutdown'] = shutdown self.dataout['render'] = render class GetSpecialSources(Baserequests):", "and Mic/Aux sources. :Returns: *desktop_1* type: String (optional) Name of", "be \"png\", \"jpg\", \"jpeg\" or \"bmp\" (or any other value", "of the stream. *settings.server* type: String (optional) The publish URL.", "use. *transitionDuration* type: int (Optional) Duration in milliseconds of the", "position. This value will be between 0.0 and 1.0. Note:", "use when accessing the streaming server. Only present if `use_auth`", "type: String (optional) Name of the second Desktop Audio capture", "The new amount of pixels cropped off the bottom of", "(in milliseconds) if supported by the transition. \"\"\" def __init__(self):", "= sourceName def getAudioActive(self): return self.datain['audioActive'] class SetSourceName(Baserequests): \"\"\" Note:", "an object) \"\"\" def __init__(self, item, scene_name=None): Baserequests.__init__(self) self.name =", "T-Bar (like a user releasing their mouse button after moving", "type: String Name of the source to be added *setVisible*", "share sources within the scene. \"\"\" def __init__(self, items, scene=None):", "hotkey is not set in OBS' settings. Setting this hotkey", "__init__(self): Baserequests.__init__(self) self.name = 'StartReplayBuffer' class StopReplayBuffer(Baserequests): \"\"\"Stop recording into", "(optional) Name of the first Desktop Audio capture source. *desktop_2*", "children (if this item is a group) \"\"\" def __init__(self,", "(optional) Full file path (file extension included) where the captured", "`true`. *stream.settings.password* type: String (optional) If authentication is enabled, the", "updated settings in response. If 'type' is different than the", "Baserequests.__init__(self) self.name = 'GetSceneItemProperties' self.datain['name'] = None self.datain['itemId'] = None", "scene to switch to. *transitionName* type: String Name of the", "self.datain['name'] def getSettings(self): return self.datain['settings'] class AddFilterToSource(Baserequests): \"\"\"Add a new", "\"\"\"Get the name of the currently selected transition in the", "controlled in this way. :Arguments: *outputName* type: String Output name", "def __init__(self): Baserequests.__init__(self) self.name = 'StartStopRecording' class StartRecording(Baserequests): \"\"\"Start recording.", "path. *word_wrap* type: boolean (optional) Word wrap. \"\"\" def __init__(self,", "getName(self): return self.datain['name'] def getMuted(self): return self.datain['muted'] class SetMute(Baserequests): \"\"\"Sets", "may require some probing around). :Returns: *sourceName* type: String Source", "def __init__(self, item, top, bottom, left, right, scene_name=None): Baserequests.__init__(self) self.name", "= None self.datain['gradient_dir'] = None self.datain['gradient_opacity'] = None self.datain['outline'] =", "type: String New item name \"\"\" def __init__(self, item, fromScene=None,", "type: int Outline opacity (0-100). *text* type: String Text content", "path. *url* type: String (optional) Url. *css* type: String (optional)", "the status of the OBS replay buffer. :Returns: *isReplayBufferActive* type:", "= None def getFilenameFormatting(self): return self.datain['filename-formatting'] class GetStats(Baserequests): \"\"\"Get OBS", "__init__(self): Baserequests.__init__(self) self.name = 'ReleaseTBar' class SetTBarPosition(Baserequests): \"\"\" If your", "the scene to create the scene item in *sourceName* type:", "of the source. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\",", "*sourceName* type: String Source name. :Returns: *monitorType* type: String The", "= 'StopMedia' self.dataout['sourceName'] = sourceName class NextMedia(Baserequests): \"\"\"Skip to the", "getRotation(self): return self.datain['rotation'] def getScale(self): return self.datain['scale'] def getCrop(self): return", "nanoseconds). \"\"\" def __init__(self, source, offset): Baserequests.__init__(self) self.name = 'SetSyncOffset'", "def getOutline_opacity(self): return self.datain['outline_opacity'] def getText(self): return self.datain['text'] def getValign(self):", "= 'CreateSource' self.datain['itemId'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceKind'] =", "= None self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName def getEnabled(self):", "into the Replay Buffer. Will return an `error` if the", "coordinate. *y* type: double Y coordinate. \"\"\" def __init__(self, item,", "only through obs-websocket. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartReplayBuffer'", "override and this value is not given. \"\"\" def __init__(self,", "acceptable). *item.id* type: int Scene Item ID. \"\"\" def __init__(self,", "GetSyncOffset(Baserequests): \"\"\"Get the audio sync offset of a specified source.", "url self.dataout['css'] = css self.dataout['width'] = width self.dataout['height'] = height", "*stream* type: Object (optional) Special stream configuration. Please note: these", "(relative positioning) :Arguments: *sourceName* type: String Name of the source", "getText(self): return self.datain['text'] def getValign(self): return self.datain['valign'] def getVertical(self): return", "getDrop_shadow(self): return self.datain['drop_shadow'] def getFont(self): return self.datain['font'] def getFrom_file(self): return", "switch to. :Returns: *transitionName* type: String Name of the current", "in milliseconds.. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaDuration'", "scene to be displayed (ignored for other projector types). \"\"\"", "\"\"\"Get the current playing state of a media source. Supports", "self.name = 'GetSceneTransitionOverride' self.datain['transitionName'] = None self.datain['transitionDuration'] = None self.dataout['sceneName']", "of this type provide audio *types.*.caps.canInteract* type: Boolean True if", "getChatlog(self): return self.datain['chatlog'] def getChatlog_lines(self): return self.datain['chatlog_lines'] def getColor(self): return", "self.dataout['scene'] = scene class SetSceneTransitionOverride(Baserequests): \"\"\"Set a scene to use", "the audio sync offset of a specified source. :Arguments: *source*", "(optional) Visibility of the scene item. \"\"\" def __init__(self, source,", "the SceneItem in the scene. \"\"\" def __init__(self, sourceName, sourceKind,", "shutdown self.dataout['render'] = render class GetSpecialSources(Baserequests): \"\"\"Get configured special sources", "of the currently active profile. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "OBSRemote. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStreamingStatus' self.datain['streaming'] =", "settings. :Returns: *type* type: String The type of streaming service", "The number of pixels cropped off the left of the", "name *filterName* type: String Source filter name :Returns: *enabled* type:", "New filter state \"\"\" def __init__(self, sourceName, filterName, filterEnabled): Baserequests.__init__(self)", "*setVisible* type: boolean (optional) Set the created SceneItem as visible", "settings \"\"\" def __init__(self, sourceName, sourceSettings, sourceType=None): Baserequests.__init__(self) self.name =", "\"\"\"Flush and save the contents of the Replay Buffer to", "String Non-unique source internal type (a.k.a kind) *sources.*.type* type: String", "= color1 self.dataout['color2'] = color2 self.dataout['custom_width'] = custom_width self.dataout['drop_shadow'] =", "items *sceneItems.*.itemId* type: int Unique item id of the source", "Name of the source. *is_local_file* type: boolean (optional) Indicates that", "to. Defaults to the current scene. *item* type: String Scene", "current). *items* type: Array<Scene> Ordered list of objects with name", "type: String (optional) Source name. Note that, since scenes are", "cropped off the bottom of the source before scaling. *crop.left*", "in the chain (relative positioning) :Arguments: *sourceName* type: String Name", "= None def getCurrentTransition(self): return self.datain['current-transition'] def getTransitions(self): return self.datain['transitions']", "to the auth challenge (see \"Authentication\" for more information). \"\"\"", "*sourceName* type: String Source name. *newName* type: String New source", "int (optional) Gradient top color. *color2* type: int (optional) Gradient", "Baserequests.__init__(self) self.name = 'SetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName'] = transitionName", "*visible* type: bool If the source is visible. *muted* type:", "the new item was created *item* type: Object New item", "type *filterSettings* type: Object Filter settings \"\"\" def __init__(self, sourceName,", "name. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'ToggleMute' self.dataout['source']", "when triggering saves only through obs-websocket. \"\"\" def __init__(self): Baserequests.__init__(self)", "def getEnabled(self): return self.datain['enabled'] def getType(self): return self.datain['type'] def getName(self):", "information :Returns: *baseWidth* type: int Base (canvas) width *baseHeight* type:", "= 'TriggerHotkeyBySequence' self.dataout['keyId'] = keyId self.dataout['keyModifiers'] = keyModifiers class PlayPauseMedia(Baserequests):", "return an `error` if recording is already active. \"\"\" def", "return self.datain['img'] def getImageFile(self): return self.datain['imageFile'] class ListOutputs(Baserequests): \"\"\"List existing", "sourceName self.dataout['newName'] = newName class SetSyncOffset(Baserequests): \"\"\"Set the audio sync", "to be displayed. *text_file* type: String File path. *word_wrap* type:", "return self.datain['word_wrap'] class SetTextFreetype2Properties(Baserequests): \"\"\"Set the current properties of a", "*rotation* type: double Source item rotation (in degrees). \"\"\" def", "'ToggleStudioMode' class GetTransitionList(Baserequests): \"\"\"List of all transitions available in the", "top color. *color2* type: int (optional) Gradient bottom color. *custom_width*", "SetSceneItemPosition(Baserequests): \"\"\"Sets the coordinates of a specified source item. :Arguments:", "and call `ReleaseTBar` later once the animation/interaction is over. :Arguments:", "current recording. Returns an error if recording is not active", "String Video color format *colorSpace* type: String Color space for", "in. Defaults to the current scene. *item* type: Object Scene", "self.name = 'ResumeRecording' class SetRecordingFolder(Baserequests): \"\"\" Please note: if `SetRecordingFolder`", "0, \"size\": 150, \"style\": \"\" }` *font.face* type: String (optional)", "not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopReplayBuffer' class", "getFrom_file(self): return self.datain['from_file'] def getLog_mode(self): return self.datain['log_mode'] def getOutline(self): return", "def __init__(self, realm, data): Baserequests.__init__(self) self.name = 'BroadcastCustomMessage' self.dataout['realm'] =", "source. :Arguments: *sourceName* type: String Source name. *monitorType* type: String", "is already active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartRecording'", "*settings.use_auth* type: boolean (optional) Indicates whether authentication should be used", "self.datain['file'] def getRead_from_file(self): return self.datain['read_from_file'] def getFont(self): return self.datain['font'] def", "\"\"\" def __init__(self, source, align=None, bk_color=None, bk_opacity=None, chatlog=None, chatlog_lines=None, color=None,", "offset): Baserequests.__init__(self) self.name = 'SetSyncOffset' self.dataout['source'] = source self.dataout['offset'] =", "the volume of the specified source. Default response uses mul", "in a scene. In other words, this is how you", "`Preview` (default), `Source`, `Scene`, `StudioProgram`, or `Multiview` (case insensitive). *monitor*", "class GetBrowserSourceProperties(Baserequests): \"\"\"Get current properties for a Browser Source. :Arguments:", "input source. *mic_3* type: String (optional) NAme of the third", "class GetMediaTime(Baserequests): \"\"\"Get the current timestamp of media in milliseconds.", "return self.datain['mediaSources'] class CreateSource(Baserequests): \"\"\"Create a source and add it", "on or off (depending on the current stream state). \"\"\"", ":Returns: *current_transition* type: String Name of the currently active transition.", "asynchronously *types.*.caps.hasVideo* type: Boolean True if sources of this type", "sourceName, filterName, movementType): Baserequests.__init__(self) self.name = 'MoveSourceFilter' self.dataout['sourceName'] = sourceName", "*source* type: String Source name. *mute* type: boolean Desired mute", "settings of a transition :Arguments: *transitionName* type: String Transition name", "to the source's base height. :Returns: *sourceName* type: String Source", "file is in use. *local_file* type: String file path. *url*", "self.datain['transitionSettings'] = None self.dataout['transitionName'] = transitionName self.dataout['transitionSettings'] = transitionSettings def", "comma-separated list string (e.g. : \"Method1,Method2,Method3\"). *supported_image_export_formats* type: String List", "Baserequests.__init__(self) self.name = 'ReleaseTBar' class SetTBarPosition(Baserequests): \"\"\" If your code", "Baserequests.__init__(self) self.name = 'StartOutput' self.dataout['outputName'] = outputName class StopOutput(Baserequests): \"\"\"", "currently configured stream type does not match the given stream", "*filterName* type: String Name of the filter to remove \"\"\"", "modifiers object. False entries can be ommitted *keyModifiers.shift* type: boolean", "not visible. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetBrowserSourceProperties'", "self.dataout['drop_shadow'] = drop_shadow self.dataout['font'] = font self.dataout['from_file'] = from_file self.dataout['log_mode']", "class GetReplayBufferStatus(Baserequests): \"\"\"Get the status of the OBS replay buffer.", "self.datain['colorSpace'] = None self.datain['colorRange'] = None def getBaseWidth(self): return self.datain['baseWidth']", "None self.datain['outline_size'] = None self.datain['outline_opacity'] = None self.datain['text'] = None", "class GetSyncOffset(Baserequests): \"\"\"Get the audio sync offset of a specified", "(optional) Extents cx. *extents_cy* type: int (optional) Extents cy. *file*", "type: String The publish URL. *settings.key* type: String The publish", "ListSceneCollections(Baserequests): \"\"\"List available scene collections :Returns: *scene_collections* type: Array<String> Scene", "retrocompatibility. *obs_websocket_version* type: String obs-websocket plugin version. *obs_studio_version* type: String", "'GetMediaTime' self.datain['timestamp'] = None self.dataout['sourceName'] = sourceName def getTimestamp(self): return", "= scene_name class DeleteSceneItem(Baserequests): \"\"\"Deletes a scene item. :Arguments: *scene*", "in the frontend's dropdown menu. :Returns: *name* type: String Name", "bounding box. \"\"\" def __init__(self, item, scene_name=None, position=None, rotation=None, scale=None,", "type: String Scene to add the new source to. *sourceSettings*", "OBS video information :Returns: *baseWidth* type: int Base (canvas) width", "Source name. :Returns: *name* type: String Source name. *muted* type:", "the source. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetAudioActive'", "a source. Available source types along with their settings properties", "self.datain['mediaState'] class GetMediaSourcesList(Baserequests): \"\"\"List the media state of all media", "of the requested (or current) scene *sceneItems* type: Array<Object> Array", "Baserequests.__init__(self) self.name = 'SetTransitionDuration' self.dataout['duration'] = duration class GetTransitionDuration(Baserequests): \"\"\"Get", "outline self.dataout['outline_color'] = outline_color self.dataout['outline_size'] = outline_size self.dataout['outline_opacity'] = outline_opacity", "the image with. -1 is automatic, 1 is smallest file/most", "None self.datain['sourceType'] = None self.datain['sourceSettings'] = None self.dataout['sourceName'] = sourceName", "obs-websocket will return an error. :Arguments: *sourceName* type: String Source", "the `item` field is an object) *position.x* type: double (optional)", "self.name = 'GetSourceTypesList' self.datain['types'] = None def getTypes(self): return self.datain['types']", "DuplicateSceneItem(Baserequests): \"\"\"Duplicates a scene item. :Arguments: *fromScene* type: String (optional)", "if using mul, under `26.0` if using dB. *muted* type:", "self.datain['source'] = None self.datain['align'] = None self.datain['bk_color'] = None self.datain['bk_opacity']", "getValign(self): return self.datain['valign'] def getVertical(self): return self.datain['vertical'] class SetTextGDIPlusProperties(Baserequests): \"\"\"Set", "self.datain['rec-folder'] = None def getRecFolder(self): return self.datain['rec-folder'] class GetReplayBufferStatus(Baserequests): \"\"\"Get", "return self.datain['text'] def getText_file(self): return self.datain['text_file'] def getWord_wrap(self): return self.datain['word_wrap']", "in *sourceName* type: String Name of the source to be", "*font.style* type: String Font Style (unknown function). *from_file* type: boolean", "saved image file (if `saveToFilePath` was specified in the request)", "sourceName): Baserequests.__init__(self) self.name = 'GetSourceFilters' self.datain['filters'] = None self.dataout['sourceName'] =", "None self.datain['read_from_file'] = None self.datain['font'] = None self.datain['gradient'] = None", "streaming. May be any String, Numeric, or Boolean field. *stream.settings*", "the selected transition. *duration* type: int (optional) Transition duration (in", "self.dataout['color'] = color self.dataout['extents'] = extents self.dataout['extents_cx'] = extents_cx self.dataout['extents_cy']", "Buffer is already active or if the \"Save Replay Buffer\"", "self.datain['outputWidth'] = None self.datain['outputHeight'] = None self.datain['scaleType'] = None self.datain['fps']", "type: double T-Bar position. This value must be between 0.0", "type: int (optional) Background opacity (0-100). *chatlog* type: boolean (optional)", "item. :Arguments: *scene* type: String (optional) Name of the scene", "= 'GetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType'] = None self.datain['sourceSettings'] =", "self.datain['isReplayBufferActive'] class StartStopReplayBuffer(Baserequests): \"\"\"Toggle the Replay Buffer on/off (depending on", "= 'GetMediaDuration' self.datain['mediaDuration'] = None self.dataout['sourceName'] = sourceName def getMediaDuration(self):", "\"\"\"Change the active scene collection. :Arguments: *sc_name* type: String Name", "of OBS v25.0.8) Note: For some reason, for the first", "source before scaling. *crop.right* type: int (optional) The new amount", "the created scene item \"\"\" def __init__(self, sceneName, sourceName, setVisible):", "self.name = 'Authenticate' self.dataout['auth'] = auth class SetHeartbeat(Baserequests): \"\"\"Enable/disable sending", "None self.datain['text'] = None self.datain['text_file'] = None self.datain['word_wrap'] = None", "self.datain['transitionSettings'] class SetTransitionSettings(Baserequests): \"\"\"Change the current settings of a transition", "hotkeyName): Baserequests.__init__(self) self.name = 'TriggerHotkeyByName' self.dataout['hotkeyName'] = hotkeyName class TriggerHotkeyBySequence(Baserequests):", "= sourceSettings self.dataout['sourceType'] = sourceType def getSourceName(self): return self.datain['sourceName'] def", "audio sync offset of a specified source. :Arguments: *source* type:", "text size. *font.style* type: String (optional) Font Style (unknown function).", "Controlling outputs is an experimental feature of obs-websocket. Some plugins", ":Returns: *source* type: String Source name. *align* type: String Text", "as encoded query string parameters to the 'key' of the", "item. Sufficiently unique if no scene items share sources within", "self.dataout['item'] = item self.dataout['scene-name'] = scene_name self.dataout['position'] = position self.dataout['rotation']", "String The type of streaming service configuration. Possible values: 'rtmp_custom'", "between source types, may require some probing around). :Returns: *sourceName*", "status. *isRecordingPaused* type: boolean Whether the recording is paused or", "`vlc_source` or `image_source` *sceneItems.*.sourceName* type: String Name of the scene", "this type provide video *types.*.caps.hasAudio* type: Boolean True if sources", "self.datain['duration'] class SetCurrentTransition(Baserequests): \"\"\"Set the active transition. :Arguments: *transition_name* type:", "currently recording). *recordingFilename* type: String (optional) Absolute path to the", "= font self.dataout['gradient'] = gradient self.dataout['gradient_color'] = gradient_color self.dataout['gradient_dir'] =", "*parentGroupName* type: String (optional) Name of the item's parent (if", "or more attributes of the current streaming server settings. Any", "*source* type: String Source name. :Returns: *name* type: String Source", "preview scene. Will return an `error` if Studio Mode is", "String Source name. :Returns: *source* type: String Source name. *align*", "getVertical(self): return self.datain['vertical'] class SetTextGDIPlusProperties(Baserequests): \"\"\"Set the current properties of", "def getSource(self): return self.datain['source'] def getIs_local_file(self): return self.datain['is_local_file'] def getLocal_file(self):", "active scene collection. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentSceneCollection'", "*type* type: String The type of streaming service configuration. Possible", "off the left of the source before scaling. *visible* type:", "one or more attributes of the current streaming server settings.", "outputName class StopOutput(Baserequests): \"\"\" Note: Controlling outputs is an experimental", "a specified source. :Arguments: *source* type: String Source name. \"\"\"", "set of settings incompatible with the actual source's type. *sourceSettings*", "of amplitude/mul. :Returns: *name* type: String Source name. *volume* type:", "String Source name. :Returns: *audioActive* type: boolean Audio active status", "transition_name): Baserequests.__init__(self) self.name = 'SetCurrentTransition' self.dataout['transition-name'] = transition_name class SetTransitionDuration(Baserequests):", "sceneName class ReorderSceneItems(Baserequests): \"\"\"Changes the order of scene items in", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetPreviewScene' self.datain['name'] = None", "negative) to offset the current media position. \"\"\" def __init__(self,", "reorder *movementType* type: String How to move the filter around", "type: Array<Object> List of transitions. *transitions.*.name* type: String Name of", "= 'SaveReplayBuffer' class SetCurrentSceneCollection(Baserequests): \"\"\"Change the active scene collection. :Arguments:", "name. *volume* type: double Desired volume. Must be between `0.0`", "String Source name :Returns: *filters* type: Array<Object> List of filters", "*name* type: String Source name. *muted* type: boolean Mute status", "*outline_color* type: int (optional) Outline color. *outline_size* type: int (optional)", "vertical=None, render=None): Baserequests.__init__(self) self.name = 'SetTextGDIPlusProperties' self.dataout['source'] = source self.dataout['align']", "= None self.datain['width'] = None self.datain['height'] = None self.datain['parentGroupName'] =", "should be used when connecting to the streaming server. *stream.settings.username*", "be specified. Clients can specify `width` and `height` parameters to", "the item's parent (if this item belongs to a group)", "= locked self.dataout['bounds'] = bounds class ResetSceneItem(Baserequests): \"\"\"Reset a scene", "\"\"\"Get a list of scenes in the currently active profile.", "String Source name. *sourceType* type: String (optional) Type of the", "Item to duplicate from the source scene (required) *item.name* type:", "String Captions text \"\"\" def __init__(self, text): Baserequests.__init__(self) self.name =", "a Text GDI Plus source. :Arguments: *source* type: String Name", "self.name = 'GetCurrentTransition' self.datain['name'] = None self.datain['duration'] = None def", "Filter name *filters.*.settings* type: Object Filter settings \"\"\" def __init__(self,", "per second *videoFormat* type: String Video color format *colorSpace* type:", "def __init__(self, source, volume, useDecibel=None): Baserequests.__init__(self) self.name = 'SetVolume' self.dataout['source']", "name *force* type: boolean (optional) Force stop (default: false) \"\"\"", "Name of the currently active scene. *scenes* type: Array<Scene> Ordered", "self.datain['outline_opacity'] = None self.datain['text'] = None self.datain['valign'] = None self.datain['vertical']", "*volume* type: double Desired volume. Must be between `0.0` and", "getCrop(self): return self.datain['crop'] def getVisible(self): return self.datain['visible'] def getMuted(self): return", "available profiles. *profiles.*.profile_name* type: String Filter name \"\"\" def __init__(self):", "words, this is how you add a source into a", "Ordered list of the current profile's scenes (See [GetCurrentScene](#getcurrentscene) for", "self.name = 'TriggerHotkeyBySequence' self.dataout['keyId'] = keyId self.dataout['keyModifiers'] = keyModifiers class", "return self.datain['color1'] def getColor2(self): return self.datain['color2'] def getCustom_width(self): return self.datain['custom_width']", "Screenshot height. Defaults to the source's base height. :Returns: *sourceName*", "item in degrees. *scale.x* type: double (optional) The new x", "getOutline_size(self): return self.datain['outline_size'] def getOutline_opacity(self): return self.datain['outline_opacity'] def getText(self): return", "Filter name \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListProfiles' self.datain['profiles']", "`use_auth` is not set to `true`. *stream.settings.password* type: String (optional)", "getGroupChildren(self): return self.datain['groupChildren'] class SetSceneItemProperties(Baserequests): \"\"\"Sets the scene specific properties", "Defaults to the active transition. *with_transition.name* type: String Name of", "change won't be applied immediately and will be effective on", "type: int The number of pixels cropped off the right", "None def getAuthRequired(self): return self.datain['authRequired'] def getChallenge(self): return self.datain['challenge'] def", "a scene. :Arguments: *sceneName* type: String (optional) Name of the", "The x-scale factor of the source. *scale.y* type: double The", "self.name = 'GetTransitionPosition' self.datain['position'] = None def getPosition(self): return self.datain['position']", "color1 self.dataout['color2'] = color2 self.dataout['custom_width'] = custom_width self.dataout['drop_shadow'] = drop_shadow", "self.dataout['source'] = source def getSource(self): return self.datain['source'] def getAlign(self): return", "'SetTextGDIPlusProperties' self.dataout['source'] = source self.dataout['align'] = align self.dataout['bk_color'] = bk_color", "displayed. *valign* type: String Text vertical alignment (\"top\", \"center\", \"bottom\").", "height *scaleType* type: String Scaling method used if output size", "extension. *compressionQuality* type: int (optional) Compression ratio between -1 and", "'GetRecordingFolder' self.datain['rec-folder'] = None def getRecFolder(self): return self.datain['rec-folder'] class GetReplayBufferStatus(Baserequests):", "Strikeout=8` *font.size* type: int (optional) Font text size. *font.style* type:", "def getLocal_file(self): return self.datain['local_file'] def getUrl(self): return self.datain['url'] def getCss(self):", "the Replay Buffer on/off (depending on the current state of", "service. *settings.password* type: String (optional) The password for the streaming", "None self.dataout['item'] = item self.dataout['fromScene'] = fromScene self.dataout['toScene'] = toScene", "'GetAuthRequired' self.datain['authRequired'] = None self.datain['challenge'] = None self.datain['salt'] = None", "current scene. *item* type: String Scene Item name. *x_scale* type:", "is not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopStreaming'", "specified source. :Arguments: *sourceName* type: String Source name. *sourceType* type:", "= gradient_color self.dataout['gradient_dir'] = gradient_dir self.dataout['gradient_opacity'] = gradient_opacity self.dataout['outline'] =", "or partial) \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetVideoInfo' self.datain['baseWidth']", "scaling. *crop.right* type: int (optional) The new amount of pixels", "1.1 for retrocompatibility. *obs_websocket_version* type: String obs-websocket plugin version. *obs_studio_version*", "Absolute path to the saved image file (if `saveToFilePath` was", "StopReplayBuffer(Baserequests): \"\"\"Stop recording into the Replay Buffer. Will return an", "GetTransitionDuration(Baserequests): \"\"\"Get the duration of the currently selected transition if", "= outline_opacity self.dataout['text'] = text self.dataout['valign'] = valign self.dataout['vertical'] =", "getSources(self): return self.datain['sources'] class SetPreviewScene(Baserequests): \"\"\"Set the active preview scene.", "trigger multiple hotkey routines depending on user settings :Arguments: *keyId*", "= scene_name class GetCurrentScene(Baserequests): \"\"\"Get the current scene's name and", "= text self.dataout['text_file'] = text_file self.dataout['word_wrap'] = word_wrap class GetBrowserSourceProperties(Baserequests):", "transition. *transitions* type: Array<Object> List of transitions. *transitions.*.name* type: String", "if authentication is required. If so, returns authentication parameters `challenge`", "def __init__(self): Baserequests.__init__(self) self.name = 'GetAuthRequired' self.datain['authRequired'] = None self.datain['challenge']", "or play a media source. Supports ffmpeg and vlc media", "type: Object (optional) Settings for the stream. *stream.settings.server* type: String", "file path. *url* type: String (optional) Url. *css* type: String", "type) formatted as a comma-separated list string \"\"\" def __init__(self):", "(0-2, 4-6, 8-10) *bounds.x* type: double (optional) The new width", "`StudioProgram`, or `Multiview` (case insensitive). *monitor* type: int (Optional) Monitor", "type: Array<String> Scene collections list *scene_collections.*.sc_name* type: String Scene collection", "*types.*.caps.hasAudio* type: Boolean True if sources of this type provide", "is enabled. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStudioModeStatus' self.datain['studio-mode']", "None self.datain['rec-timecode'] = None self.datain['preview-only'] = None def getStreaming(self): return", "Defaults to true. \"\"\" def __init__(self, position, release=None): Baserequests.__init__(self) self.name", "direction. *gradient_opacity* type: int Gradient opacity (0-100). *outline* type: boolean", "Studio Mode is enabled. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "text styling flag. `Bold=1, Italic=2, Bold Italic=3, Underline=5, Strikeout=8` *font.size*", "filterEnabled class GetAudioMonitorType(Baserequests): \"\"\"Get the audio monitoring type of the", "Baserequests.__init__(self) self.name = 'SetSceneItemCrop' self.dataout['item'] = item self.dataout['top'] = top", "def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetSourceFilters' self.datain['filters'] = None", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ToggleStudioMode' class GetTransitionList(Baserequests): \"\"\"List", "type: String Name of the source. *align* type: String (optional)", "embedded CEA-608 caption data. :Arguments: *text* type: String Captions text", "top self.dataout['bottom'] = bottom self.dataout['left'] = left self.dataout['right'] = right", "the transform of the specified source item. :Arguments: *scene_name* type:", "= None self.datain['bk_opacity'] = None self.datain['chatlog'] = None self.datain['chatlog_lines'] =", "self.dataout['transitionName'] = transitionName self.dataout['transitionSettings'] = transitionSettings def getTransitionSettings(self): return self.datain['transitionSettings']", "(in milliseconds). \"\"\" def __init__(self, with_transition=None): Baserequests.__init__(self) self.name = 'TransitionToProgram'", "Requires OBS v24.0.4 or newer. :Arguments: *type* type: String (Optional)", "type: int (optional) Gradient color. *gradient_dir* type: float (optional) Gradient", "__init__(self, scene_name): Baserequests.__init__(self) self.name = 'SetCurrentScene' self.dataout['scene-name'] = scene_name class", "or not. *recordTimecode* type: String (optional) Time elapsed since recording", "None def getFilenameFormatting(self): return self.datain['filename-formatting'] class GetStats(Baserequests): \"\"\"Get OBS stats", "boolean Current recording status. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "width. Defaults to the source's base width. *height* type: int", "*filterName* type: String Source filter name :Returns: *enabled* type: Boolean", "None self.datain['fps'] = None self.datain['videoFormat'] = None self.datain['colorSpace'] = None", "to current). *items* type: Array<Scene> Ordered list of objects with", "to switch to. :Returns: *transitionName* type: String Name of the", "disable). *drop_shadow* type: boolean (optional) Drop shadow. *font* type: Object", "or already paused. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'PauseRecording'", "= 'GetVolume' self.datain['name'] = None self.datain['volume'] = None self.datain['muted'] =", "is in progress, the change won't be applied immediately and", "*hotkeyName* type: String Unique name of the hotkey, as defined", "Baserequests.__init__(self) self.name = 'SetSceneItemRender' self.dataout['source'] = source self.dataout['render'] = render", "\"transition\" or \"other\" *types.*.defaultSettings* type: Object Default settings of this", "\"\"\"Stop recording into the Replay Buffer. Will return an `error`", "int The number of pixels cropped off the left of", "type: String Identifier to be choosen by the client *data*", "rotation self.dataout['scale'] = scale self.dataout['crop'] = crop self.dataout['visible'] = visible", "= None self.dataout['sourceName'] = sourceName self.dataout['sourceKind'] = sourceKind self.dataout['sceneName'] =", "recording). *preview_only* type: boolean Always false. Retrocompatibility with OBSRemote. \"\"\"", "Baserequests.__init__(self) self.name = 'GetSceneList' self.datain['current-scene'] = None self.datain['scenes'] = None", "None self.datain['chatlog'] = None self.datain['chatlog_lines'] = None self.datain['color'] = None", "(optional) Indicates whether authentication should be used when connecting to", "use. *local_file* type: String (optional) file path. *url* type: String", "class SetRecordingFolder(Baserequests): \"\"\" Please note: if `SetRecordingFolder` is called while", "is basically the same as triggering the \"Save Replay Buffer\"", "\"\"\"Get the position of the current transition. :Returns: *position* type:", "type: double The y-scale factor of the source. *crop.top* type:", "None self.datain['extents_cx'] = None self.datain['extents_cy'] = None self.datain['file'] = None", "added *filterName* type: String Name of the new filter *filterType*", "or off (depending on the current recording state). \"\"\" def", "*types* type: Array<Object> Array of source types *types.*.typeId* type: String", "= outline_size self.dataout['outline_opacity'] = outline_opacity self.dataout['text'] = text self.dataout['valign'] =", "self.datain['font'] = None self.datain['gradient'] = None self.datain['gradient_color'] = None self.datain['gradient_dir']", "note: these won't be saved to OBS' configuration. *stream.type* type:", "__init__(self, type, settings, save): Baserequests.__init__(self) self.name = 'SetStreamSettings' self.dataout['type'] =", "Name of the transition. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "Outline. *outline_color* type: int Outline color. *outline_size* type: int Outline", "*sourceName* type: String Source name. *monitorType* type: String The monitor", "type: double (optional) The new y position of the source.", "New source name. \"\"\" def __init__(self, sourceName, newName): Baserequests.__init__(self) self.name", "be used when connecting to the streaming server. *stream.settings.username* type:", "= None self.datain['mic-3'] = None def getDesktop1(self): return self.datain['desktop-1'] def", "self.dataout['scene-name'] = scene_name class DeleteSceneItem(Baserequests): \"\"\"Deletes a scene item. :Arguments:", "source. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or", "self.dataout['keyId'] = keyId self.dataout['keyModifiers'] = keyModifiers class PlayPauseMedia(Baserequests): \"\"\"Pause or", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListOutputs' self.datain['outputs'] = None", "clients :Arguments: *realm* type: String Identifier to be choosen by", "object. *settings.server* type: String The publish URL. *settings.key* type: String", "log. *chatlog_lines* type: int (optional) Chat log lines. *color* type:", ":Arguments: *sourceName* type: String Source name. :Returns: *mediaState* type: String", "the scene to preview. \"\"\" def __init__(self, scene_name): Baserequests.__init__(self) self.name", "an error if recording is not active or already paused.", "is not enabled. :Arguments: *with_transition* type: Object (optional) Change the", "type: String Type. Value is one of the following: \"input\",", "type: Object New item info *item.id* type: int New item", "None self.datain['offset'] = None self.dataout['source'] = source def getName(self): return", "(optional) Name of the second Desktop Audio capture source. *mic_1*", "ratio is preserved if only one of these two parameters", "*scene_collections* type: Array<String> Scene collections list *scene_collections.*.sc_name* type: String Scene", "different from `pictureFormat`. Can be a relative path. *fileFormat* type:", "of the scene item. \"\"\" def __init__(self, source, is_local_file=None, local_file=None,", "def getOutline(self): return self.datain['outline'] def getOutline_color(self): return self.datain['outline_color'] def getOutline_size(self):", "type: String Name of the filter to reorder *newIndex* type:", "__init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaState' self.datain['mediaState'] = None self.dataout['sourceName']", "= render class GetSpecialSources(Baserequests): \"\"\"Get configured special sources like Desktop", "item, fromScene=None, toScene=None): Baserequests.__init__(self) self.name = 'DuplicateSceneItem' self.datain['scene'] = None", "*settings.key* type: String The publish key of the stream. *settings.use_auth*", "None self.datain['font'] = None self.datain['gradient'] = None self.datain['gradient_color'] = None", "self.datain['sourceType'] def getSourceSettings(self): return self.datain['sourceSettings'] class SetSourceSettings(Baserequests): \"\"\"Set settings of", "sourceName class GetMediaDuration(Baserequests): \"\"\"Get the length of media in milliseconds.", "self.datain['bk_color'] def getBk_opacity(self): return self.datain['bk_opacity'] def getChatlog(self): return self.datain['chatlog'] def", "source self.dataout['useDecibel'] = useDecibel def getName(self): return self.datain['name'] def getVolume(self):", "Text content to be displayed. *text_file* type: String File path.", "self.datain['desktop-2'] = None self.datain['mic-1'] = None self.datain['mic-2'] = None self.datain['mic-3']", "volume in decibels of attenuation instead of amplitude/mul. :Returns: *name*", "the left. *position.y* type: double The y position of the", "must be between 0.0 and 1.0. *release* type: boolean (optional)", "source. :Arguments: *sourceName* type: String Source name. :Returns: *audioActive* type:", "If not provided, the currently active scene is used. *embedPictureFormat*", "to delete (required) *item.name* type: String Scene Item name (prefer", "type: String (Optional) Name of the source or scene to", "audio monitoring type of the specified source. :Arguments: *sourceName* type:", "EDIT # # (Generated on 2020-12-20 18:26:33.661372) # from .base_classes", "self.dataout['settings'] = settings self.dataout['save'] = save class GetStreamSettings(Baserequests): \"\"\"Get the", "key identifier (e.g. `OBS_KEY_A` for key \"A\"). Available identifiers [here](https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h)", "pixels cropped off the top of the source before scaling.", "return self.datain['sceneName'] def getSceneItems(self): return self.datain['sceneItems'] class GetSceneItemProperties(Baserequests): \"\"\"Gets the", "type: String File path name. *read_from_file* type: boolean Read text", "of the item's parent (if this item belongs to a", "self.name = 'CreateScene' self.dataout['sceneName'] = sceneName class ReorderSceneItems(Baserequests): \"\"\"Changes the", "type: String Source filter name :Returns: *enabled* type: Boolean Filter", "message to all connected WebSocket clients :Arguments: *realm* type: String", "def getGroupChildren(self): return self.datain['groupChildren'] class SetSceneItemProperties(Baserequests): \"\"\"Sets the scene specific", "capabilities *types.*.caps.isAsync* type: Boolean True if source of this type", "(\"top\", \"center\", \"bottom\"). *vertical* type: boolean Vertical text enabled. \"\"\"", "image file as (one of the values provided in the", "= None self.datain['baseHeight'] = None self.datain['outputWidth'] = None self.datain['outputHeight'] =", "File path name. *read_from_file* type: boolean Read text from the", "Outline color. *outline_size* type: int Outline size. *outline_opacity* type: int", "all settings must be specified in the `settings` object or", "the bounding box. *bounds.y* type: double (optional) The new height", "media sources (as of OBS v25.0.8) Note: For some reason,", "(optional) Background color. *bk_opacity* type: int (optional) Background opacity (0-100).", "type: String List of supported formats for features that use", "TransitionToProgram(Baserequests): \"\"\"Transitions the currently previewed scene to the main output.", "belongs to. Defaults to the currently active scene. *source* type:", "These will be merged to the current filter settings. \"\"\"", "String Source name. :Returns: *source* type: String Source name *color1*", "*scene* type: String (optional) Name of the scene to reorder", "class SetTBarPosition(Baserequests): \"\"\" If your code needs to perform multiple", "for a Browser Source. :Arguments: *source* type: String Source name.", "source. States: `none`, `playing`, `opening`, `buffering`, `paused`, `stopped`, `ended`, `error`,", "`use_auth` is `true`. *settings.password* type: String The password to use", "not enabled. :Returns: *name* type: String The name of the", "is visible. *muted* type: bool If the source is muted.", "type: String Transition name *transitionSettings* type: Object Transition settings (they", "key \"A\"). Available identifiers [here](https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h) *keyModifiers* type: Object (Optional) Optional", "= 'SetCurrentScene' self.dataout['scene-name'] = scene_name class GetCurrentScene(Baserequests): \"\"\"Get the current", "*settings.use_auth* type: boolean Indicates whether authentication should be used when", "self.dataout['align'] = align self.dataout['bk_color'] = bk_color self.dataout['bk_opacity'] = bk_opacity self.dataout['chatlog']", "self.datain['salt'] class Authenticate(Baserequests): \"\"\"Attempt to authenticate the client to the", "= None def getBaseWidth(self): return self.datain['baseWidth'] def getBaseHeight(self): return self.datain['baseHeight']", "the streaming service. *save* type: boolean Persist the settings to", "Text GDI Plus source. :Arguments: *source* type: String Source name.", "the source item *sceneItems.*.sourceKind* type: String ID if the scene", "recording state). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopRecording' class", "int The desired audio sync offset (in nanoseconds). \"\"\" def", "Scene collections list *scene_collections.*.sc_name* type: String Scene collection name \"\"\"", "a source into a scene. :Arguments: *sceneName* type: String Name", "def __init__(self, sourceName, sourceKind, sceneName, sourceSettings=None, setVisible=None): Baserequests.__init__(self) self.name =", "Output Output info \"\"\" def __init__(self, outputName): Baserequests.__init__(self) self.name =", "*gradient* type: boolean (optional) Gradient enabled. *gradient_color* type: int (optional)", "filter around in the source's filter chain. Either \"up\", \"down\",", "\"\"\" def __init__(self, sourceName, sourceSettings, sourceType=None): Baserequests.__init__(self) self.name = 'SetSourceSettings'", "type: int The time in milliseconds since the start of", "Baserequests.__init__(self) self.name = 'GetSourceFilterInfo' self.datain['enabled'] = None self.datain['type'] = None", "of the OBS replay buffer. :Returns: *isReplayBufferActive* type: boolean Current", "\"\"\" def __init__(self, sourceName=None, embedPictureFormat=None, saveToFilePath=None, fileFormat=None, compressionQuality=None, width=None, height=None):", "available request types, formatted as a comma-separated list string (e.g.", "the specified source :Arguments: *sourceName* type: String Source name. *sourceType*", "whether the source is muted. \"\"\" def __init__(self, source, useDecibel=None):", "String File path name. *read_from_file* type: boolean Read text from", "gradient_color self.dataout['gradient_dir'] = gradient_dir self.dataout['gradient_opacity'] = gradient_opacity self.dataout['outline'] = outline", "the bottom of the source item. *left* type: int Pixel", "properties of the specified source item. Coordinates are relative to", "the T-Bar gets released automatically after setting its new position", "the source type *types.*.type* type: String Type. Value is one", "of the item. *scale.y* type: double (optional) The new y", "type: double (optional) The new width of the bounding box.", "int Pixel position of the left of the source item.", "type: String The name of the active preview scene. *sources*", "a scene item. :Arguments: *scene_name* type: String (optional) Name of", "local_file self.dataout['url'] = url self.dataout['css'] = css self.dataout['width'] = width", "source name *sources.*.typeId* type: String Non-unique source internal type (a.k.a", "The username for the streaming service. *settings.password* type: String (optional)", "self.datain['gradient_dir'] = None self.datain['gradient_opacity'] = None self.datain['outline'] = None self.datain['outline_color']", "type: int Transition duration. `-1` if no override is set.", "sourceName=None, embedPictureFormat=None, saveToFilePath=None, fileFormat=None, compressionQuality=None, width=None, height=None): Baserequests.__init__(self) self.name =", "class SetSceneItemPosition(Baserequests): \"\"\"Sets the coordinates of a specified source item.", "1.0mul/0.0dB, however OBS actually supports larger values. *useDecibel* type: boolean", "custom message to all connected WebSocket clients :Arguments: *realm* type:", "type: boolean Current recording status. *stream_timecode* type: String (optional) Time", "on file extension. *compressionQuality* type: int (optional) Compression ratio between", "getItemId(self): return self.datain['itemId'] class GetSourcesList(Baserequests): \"\"\"List all sources available in", "type: String (optional) Format of the Data URI encoded picture.", "Baserequests.__init__(self) self.name = 'GetPreviewScene' self.datain['name'] = None self.datain['sources'] = None", "number of pixels cropped off the left of the source", "= None self.datain['scenes'] = None def getCurrentScene(self): return self.datain['current-scene'] def", "to the current duration specified in the UI if there", "self.dataout['stream'] = stream class StopStreaming(Baserequests): \"\"\"Stop streaming. Will return an", "enabled. :Returns: *studio_mode* type: boolean Indicates if Studio Mode is", "= 'GetSceneItemList' self.datain['sceneName'] = None self.datain['sceneItems'] = None self.dataout['sceneName'] =", "styling flag. `Bold=1, Italic=2, Bold Italic=3, Underline=5, Strikeout=8` *font.size* type:", "def getScenes(self): return self.datain['scenes'] class CreateScene(Baserequests): \"\"\"Create a new scene", "cropped off the right of the source before scaling. *visible*", "item self.dataout['scene'] = scene class AddSceneItem(Baserequests): \"\"\"Creates a scene item", "*itemId* type: int Numerical ID of the created scene item", "write the image with. -1 is automatic, 1 is smallest", "recording file (only present if currently recording). \"\"\" def __init__(self):", "type: bool (optional) The new locked status of the source.", "`none`, `playing`, `opening`, `buffering`, `paused`, `stopped`, `ended`, `error`, `unknown` \"\"\"", "OBS replay buffer. :Returns: *isReplayBufferActive* type: boolean Current recording status.", "= source def getSource(self): return self.datain['source'] def getAlign(self): return self.datain['align']", "sourceName): Baserequests.__init__(self) self.name = 'GetMediaState' self.datain['mediaState'] = None self.dataout['sourceName'] =", "self.datain['supported-image-export-formats'] = None def getVersion(self): return self.datain['version'] def getObsWebsocketVersion(self): return", "the scene item's source. Either `input`, `group`, or `scene` \"\"\"", "= realm self.dataout['data'] = data class GetVideoInfo(Baserequests): \"\"\"Get basic OBS", "ID. *position.x* type: double The x position of the source", "def getName(self): return self.datain['name'] def getOffset(self): return self.datain['offset'] class GetSourceSettings(Baserequests):", "self.dataout['auth'] = auth class SetHeartbeat(Baserequests): \"\"\"Enable/disable sending of the Heartbeat", "type: int (optional) Framerate. *shutdown* type: boolean (optional) Indicates whether", "SLIDER PERCENTAGE. :Arguments: *source* type: String Source name. *useDecibel* type:", "class GetTransitionSettings(Baserequests): \"\"\"Get the current settings of a transition :Arguments:", "reach a maximum of 1.0mul/0.0dB, however OBS actually supports larger", "is not enabled. :Arguments: *scene_name* type: String The name of", "self.datain['shutdown'] = None self.dataout['source'] = source def getSource(self): return self.datain['source']", "*font.face* type: String Font face. *font.flags* type: int Font text", "(\"left\", \"center\", \"right\"). *bk_color* type: int (optional) Background color. *bk_opacity*", "def getSource(self): return self.datain['source'] def getAlign(self): return self.datain['align'] def getBk_color(self):", "position of the projector window (only if monitor is -1).", "The type of streaming service configuration. Possible values: 'rtmp_custom' or", "the right of the source before scaling. *visible* type: bool", "int Gradient color. *gradient_dir* type: float Gradient direction. *gradient_opacity* type:", "class GetSpecialSources(Baserequests): \"\"\"Get configured special sources like Desktop Audio and", "self.datain['height'] = None self.datain['parentGroupName'] = None self.datain['groupChildren'] = None self.dataout['item']", "with_transition=None): Baserequests.__init__(self) self.name = 'TransitionToProgram' self.dataout['with-transition'] = with_transition class EnableStudioMode(Baserequests):", "sourceType def getSourceName(self): return self.datain['sourceName'] def getSourceType(self): return self.datain['sourceType'] def", "vertical scaling factor) *parentGroupName* type: String (optional) Name of the", "current override and this value is not given. \"\"\" def", "\"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment* type: int (optional) The", "`image_source` *sceneItems.*.sourceName* type: String Name of the scene item's source", "render=None): Baserequests.__init__(self) self.name = 'SetBrowserSourceProperties' self.dataout['source'] = source self.dataout['is_local_file'] =", "CreateSource(Baserequests): \"\"\"Create a source and add it as a sceneitem", "if `use_auth` is `true`. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "\"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetSourceFilters' self.datain['filters'] =", "(a.k.a `ffmpeg_source` or `vlc_source`) *mediaSources.*.mediaState* type: String The current state", "double Frames rendered per second *videoFormat* type: String Video color", ":Returns: *desktop_1* type: String (optional) Name of the first Desktop", "recording on or off (depending on the current recording state).", "to the current scene. *item* type: String | Object Scene", "visible. *muted* type: bool If the source is muted. *locked*", "getName(self): return self.datain['name'] def getSources(self): return self.datain['sources'] class GetSceneList(Baserequests): \"\"\"Get", "type: int Base (canvas) width *baseHeight* type: int Base (canvas)", "self.datain['sourceName'] def getImg(self): return self.datain['img'] def getImageFile(self): return self.datain['imageFile'] class", "ListOutputs(Baserequests): \"\"\"List existing outputs :Returns: *outputs* type: Array<Output> Outputs list", "*height* type: int Height. *fps* type: int Framerate. *shutdown* type:", "type: String (optional) Name of the first Desktop Audio capture", "type: String Scene Item name. *x* type: double X coordinate.", "the same info as provided in OBS' stats window) :Returns:", "(Optional) Monitor to open the projector on. If -1 or", "self.dataout['enable'] = enable class SetFilenameFormatting(Baserequests): \"\"\"Set the filename formatting string", "function). *from_file* type: boolean (optional) Read text from the specified", "def getDrop_shadow(self): return self.datain['drop_shadow'] def getFont(self): return self.datain['font'] def getFrom_file(self):", "state). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopRecording' class StartRecording(Baserequests):", "Name of the scene to switch to. :Returns: *transitionName* type:", "the `settings` object or an error will occur when starting", "self.dataout['type'] = type self.dataout['monitor'] = monitor self.dataout['geometry'] = geometry self.dataout['name']", "def getBaseWidth(self): return self.datain['baseWidth'] def getBaseHeight(self): return self.datain['baseHeight'] def getOutputWidth(self):", "self.dataout['x'] = x self.dataout['y'] = y self.dataout['scene-name'] = scene_name class", "the client if authentication is required. If so, returns authentication", "playlist. Supports only vlc media source (as of OBS v25.0.8)", "type: String The current state of media for that source.", "text from the specified file. *font* type: Object Holds data", "Name of the desired profile. \"\"\" def __init__(self, profile_name): Baserequests.__init__(self)", "type composite one or more sub-sources *types.*.caps.doNotDuplicate* type: Boolean True", "self.dataout['movementType'] = movementType class SetSourceFilterSettings(Baserequests): \"\"\"Update settings of a filter", "*rotation* type: double The clockwise rotation of the item in", "off the left of the source before scaling. *crop.right* type:", "Source name. *monitorType* type: String The monitor type to use.", "return self.datain['desktop-2'] def getMic1(self): return self.datain['mic-1'] def getMic2(self): return self.datain['mic-2']", "*salt* type: String (optional) \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "Baserequests.__init__(self) self.name = 'BroadcastCustomMessage' self.dataout['realm'] = realm self.dataout['data'] = data", "type: String Scene collection name \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "username for the streaming server. Ignored if `use_auth` is not", "If your code needs to perform multiple successive T-Bar moves", "\"\"\"Set the transform of the specified source item. :Arguments: *scene_name*", "= name class TriggerHotkeyByName(Baserequests): \"\"\"Executes hotkey routine, identified by hotkey", "`use_auth` is not set to `true`. \"\"\" def __init__(self, stream=None):", "the replay buffer). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopReplayBuffer'", "the current streaming server settings to disk. \"\"\" def __init__(self):", "string (e.g. : \"Method1,Method2,Method3\"). *supported_image_export_formats* type: String List of supported", "request is not perfect. The processing rate of this request", "current playing state of a media source. Supports ffmpeg and", "type: String Scene Item name. *itemId* type: int Scene Item", "def getOutputWidth(self): return self.datain['outputWidth'] def getOutputHeight(self): return self.datain['outputHeight'] def getScaleType(self):", "= chatlog_lines self.dataout['color'] = color self.dataout['extents'] = extents self.dataout['extents_cx'] =", "def getStudioMode(self): return self.datain['studio-mode'] class GetPreviewScene(Baserequests): \"\"\"Get the name of", "self.datain['height'] = None self.datain['fps'] = None self.datain['shutdown'] = None self.dataout['source']", "self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['movementType'] = movementType class", "currently enabled. :Returns: *studio_mode* type: boolean Indicates if Studio Mode", "type: String Text content to be displayed. *text_file* type: String", "= sourceName self.dataout['sourceSettings'] = sourceSettings self.dataout['sourceType'] = sourceType def getSourceName(self):", "self.name = 'StopOutput' self.dataout['outputName'] = outputName self.dataout['force'] = force class", "self.dataout['filterEnabled'] = filterEnabled class GetAudioMonitorType(Baserequests): \"\"\"Get the audio monitoring type", "def __init__(self, item, scene_name=None): Baserequests.__init__(self) self.name = 'GetSceneItemProperties' self.datain['name'] =", "timestamp to. \"\"\" def __init__(self, sourceName, timestamp): Baserequests.__init__(self) self.name =", "active or already paused. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "sourceName self.dataout['setVisible'] = setVisible def getItemId(self): return self.datain['itemId'] class DuplicateSceneItem(Baserequests):", "to the current scene if not specified. :Returns: *sceneName* type:", "URL. *stream.settings.key* type: String (optional) The publish key of the", "the transition. *with_transition.duration* type: int (optional) Transition duration (in milliseconds).", "transition. Empty string if no override is set. *transitionDuration* type:", "'SetMute' self.dataout['source'] = source self.dataout['mute'] = mute class ToggleMute(Baserequests): \"\"\"Inverts", "as GetStreamSettings). :Arguments: *type* type: String The type of streaming", "publish URL. *stream.settings.key* type: String (optional) The publish key of", "\"\"\"Get the current properties of a Text Freetype 2 source.", "GetCurrentSceneCollection(Baserequests): \"\"\"Get the name of the current scene collection. :Returns:", "Gradient opacity (0-100). *outline* type: boolean Outline. *outline_color* type: int", "*position* type: double current transition position. This value will be", "self.datain['item'] class SetCurrentScene(Baserequests): \"\"\"Switch to the specified scene. :Arguments: *scene_name*", "self.dataout['item'] = item self.dataout['scene-name'] = scene_name class SetSceneItemRender(Baserequests): \"\"\"Show or", "scene *items.*.id* type: int (optional) Id of a specific scene", "self.name = 'TransitionToProgram' self.dataout['with-transition'] = with_transition class EnableStudioMode(Baserequests): \"\"\"Enables Studio", "the active transition. :Arguments: *transition_name* type: String The name of", "filters applied to a source :Arguments: *sourceName* type: String Source", "hidden \"\"\" def __init__(self, source, render, scene_name=None): Baserequests.__init__(self) self.name =", "the specified filter is removed *filterName* type: String Name of", "formats for features that use image export (like the TakeSourceScreenshot", "String Source name. :Returns: *monitorType* type: String The monitor type", "Boolean field. *stream.settings* type: Object (optional) Settings for the stream.", "OBS instance :Returns: *sources* type: Array<Object> Array of sources *sources.*.name*", "the main output. Will return an `error` if Studio Mode", "1.0. *release* type: boolean (optional) Whether or not the T-Bar", "__init__(self): Baserequests.__init__(self) self.name = 'GetSpecialSources' self.datain['desktop-1'] = None self.datain['desktop-2'] =", "'StartStopStreaming' class StartStreaming(Baserequests): \"\"\"Start streaming. Will return an `error` if", ":Arguments: *sourceName* type: String Source name. *newName* type: String New", "= 'GetVersion' self.datain['version'] = None self.datain['obs-websocket-version'] = None self.datain['obs-studio-version'] =", "class Authenticate(Baserequests): \"\"\"Attempt to authenticate the client to the server.", "def getAudioActive(self): return self.datain['audioActive'] class SetSourceName(Baserequests): \"\"\" Note: If the", "sourceType=None): Baserequests.__init__(self) self.name = 'SetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType'] =", "*word_wrap* type: boolean (optional) Word wrap. \"\"\" def __init__(self, source,", "the left of the source before scaling. *visible* type: bool", "volume of the specified source. Default response uses mul format,", "*gradient_color* type: int (optional) Gradient color. *gradient_dir* type: float (optional)", "possible *types.*.caps.isComposite* type: Boolean True if sources of this type", "Buffer\" hotkey. Will return an `error` if the Replay Buffer", "sourceKind, sceneName, sourceSettings=None, setVisible=None): Baserequests.__init__(self) self.name = 'CreateSource' self.datain['itemId'] =", "the scene to reorder (defaults to current). *items* type: Array<Scene>", "type: String Type of the scene item's source. Either `input`,", "String Source name. *useDecibel* type: boolean (optional) Output volume in", "return self.datain['from_file'] def getLog_mode(self): return self.datain['log_mode'] def getOutline(self): return self.datain['outline']", "path. *fileFormat* type: String (optional) Format to save the image", "2 source. :Arguments: *source* type: String Source name. :Returns: *source*", "= 'MoveSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['movementType'] =", "return self.datain['imageFile'] class ListOutputs(Baserequests): \"\"\"List existing outputs :Returns: *outputs* type:", "= stream class StopStreaming(Baserequests): \"\"\"Stop streaming. Will return an `error`", "The x position of the source from the left. *position.y*", "(optional) Font text styling flag. `Bold=1, Italic=2, Bold Italic=3, Underline=5,", "(optional) NAme of the third Mic/Aux input source. \"\"\" def", "return self.datain['name'] def getSources(self): return self.datain['sources'] class GetSceneList(Baserequests): \"\"\"Get a", "the current scene. *item* type: String Scene Item name. *x*", "return self.datain['sceneItems'] class GetSceneItemProperties(Baserequests): \"\"\"Gets the scene specific properties of", "name of the currently selected transition in the frontend's dropdown", "present if currently recording). *recordingFilename* type: String (optional) Absolute path", "*keyModifiers.command* type: boolean Trigger Command Key (Mac) \"\"\" def __init__(self,", "Encoded in Base64 using [Qt's geometry encoding](https://doc.qt.io/qt-5/qwidget.html#saveGeometry). Corresponds to OBS's", "return self.datain['chatlog_lines'] def getColor(self): return self.datain['color'] def getExtents(self): return self.datain['extents']", "\"\"\"Get the current properties of a Text GDI Plus source.", "to the specified scene. :Arguments: *scene_name* type: String Name of", "specified file. *log_mode* type: boolean Chat log. *outline* type: boolean", "muted. *locked* type: bool If the source's transform is locked.", "\"\"\"Enable/disable sending of the Heartbeat event :Arguments: *enable* type: boolean", "String Font face. *font.flags* type: int Font text styling flag.", "getPosition(self): return self.datain['position'] class GetTransitionSettings(Baserequests): \"\"\"Get the current settings of", "Custom width (0 to disable). *drop_shadow* type: boolean Drop shadow.", "properties of a Text GDI Plus source. :Arguments: *source* type:", "an error. :Arguments: *sourceName* type: String Source name. *newName* type:", "Source name. *volume* type: double Desired volume. Must be between", "None self.datain['sourceHeight'] = None self.datain['width'] = None self.datain['height'] = None", "self.dataout['bk_opacity'] = bk_opacity self.dataout['chatlog'] = chatlog self.dataout['chatlog_lines'] = chatlog_lines self.dataout['color']", "self.dataout['sourceName'] = sourceName def getFilters(self): return self.datain['filters'] class GetSourceFilterInfo(Baserequests): \"\"\"List", "getBaseWidth(self): return self.datain['baseWidth'] def getBaseHeight(self): return self.datain['baseHeight'] def getOutputWidth(self): return", "type: int (optional) Extents cy. *file* type: String (optional) File", "getSupportedImageExportFormats(self): return self.datain['supported-image-export-formats'] class GetAuthRequired(Baserequests): \"\"\"Tells the client if authentication", "largest file/least compression. Varies with image type. *width* type: int", "of the source. 'true' shows source, 'false' hides source. *locked*", "def getMonitorType(self): return self.datain['monitorType'] class SetAudioMonitorType(Baserequests): \"\"\"Set the audio monitoring", "= None self.datain['extents'] = None self.datain['extents_cx'] = None self.datain['extents_cy'] =", "filter belongs *filterName* type: String Name of the filter to", "Special stream configuration. Please note: these won't be saved to", "v25.0.8) :Arguments: *sourceName* type: String Source name. *timestamp* type: int", "String (optional) Format to save the image file as (one", "scene to create. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name =", "(0 to disable). *drop_shadow* type: boolean (optional) Drop shadow. *font*", "self.dataout['filterName'] = filterName self.dataout['filterEnabled'] = filterEnabled class GetAudioMonitorType(Baserequests): \"\"\"Get the", "source on which the filter is added *filterName* type: String", "status (enabled or not) *filters.*.type* type: String Filter type *filters.*.name*", "self.datain['enabled'] def getType(self): return self.datain['type'] def getName(self): return self.datain['name'] def", "getDesktop1(self): return self.datain['desktop-1'] def getDesktop2(self): return self.datain['desktop-2'] def getMic1(self): return", "triggering the \"Save Replay Buffer\" hotkey. Will return an `error`", "*sceneName* type: String Name of the scene to create the", "the client to the server. :Arguments: *auth* type: String Response", "getBaseHeight(self): return self.datain['baseHeight'] def getOutputWidth(self): return self.datain['outputWidth'] def getOutputHeight(self): return", "width multiplied by the horizontal scaling factor) *height* type: double", "of pixels cropped off the top of the source before", "y position of the source. *position.alignment* type: int (optional) The", "return self.datain['enabled'] def getType(self): return self.datain['type'] def getName(self): return self.datain['name']", "a local file is in use. *local_file* type: String (optional)", "self.dataout['scene-name'] = scene_name self.dataout['position'] = position self.dataout['rotation'] = rotation self.dataout['scale']", "\"\"\"Scrub media using a supplied offset. Supports ffmpeg and vlc", "program version. *available_requests* type: String List of available request types,", "the second Mic/Aux input source. *mic_3* type: String (optional) NAme", "source): Baserequests.__init__(self) self.name = 'GetTextGDIPlusProperties' self.datain['source'] = None self.datain['align'] =", "= filterSettings class SetSourceFilterVisibility(Baserequests): \"\"\"Change the visibility/enabled state of a", "currently active scene is used. *embedPictureFormat* type: String (optional) Format", "= 'GetBrowserSourceProperties' self.datain['source'] = None self.datain['is_local_file'] = None self.datain['local_file'] =", "type: double (optional) The new y scale of the item.", "sourceName def getMonitorType(self): return self.datain['monitorType'] class SetAudioMonitorType(Baserequests): \"\"\"Set the audio", "class PlayPauseMedia(Baserequests): \"\"\"Pause or play a media source. Supports ffmpeg", "(Ctrl) Key *keyModifiers.command* type: boolean Trigger Command Key (Mac) \"\"\"", "self.name = 'GetSceneItemList' self.datain['sceneName'] = None self.datain['sceneItems'] = None self.dataout['sceneName']", "current duration specified in the UI if there is no", "def __init__(self, hotkeyName): Baserequests.__init__(self) self.name = 'TriggerHotkeyByName' self.dataout['hotkeyName'] = hotkeyName", "None self.datain['local_file'] = None self.datain['url'] = None self.datain['css'] = None", "boolean Indicates whether authentication is required. *challenge* type: String (optional)", "the scene to create the item in. Defaults to the", "Whether or not the T-Bar gets released automatically after setting", "= 'StopReplayBuffer' class SaveReplayBuffer(Baserequests): \"\"\"Flush and save the contents of", "type: String Name of the transition to use. *transitionDuration* type:", "*challenge* type: String (optional) *salt* type: String (optional) \"\"\" def", "scaling factor) *parentGroupName* type: String (optional) Name of the item's", "the current scene. *item* type: Object Scene item to delete", "self.dataout['text'] = text self.dataout['text_file'] = text_file self.dataout['word_wrap'] = word_wrap class", "error will occur when starting the stream. *stream.metadata* type: Object", "outline=None, outline_color=None, outline_size=None, outline_opacity=None, text=None, valign=None, vertical=None, render=None): Baserequests.__init__(self) self.name", "'GetBrowserSourceProperties' self.datain['source'] = None self.datain['is_local_file'] = None self.datain['local_file'] = None", "StopOutput(Baserequests): \"\"\" Note: Controlling outputs is an experimental feature of", "`unknown` \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetMediaSourcesList' self.datain['mediaSources'] =", "of the values provided in the `supported-image-export-formats` response field of", "name of the currently previewed scene and its list of", "on or off (depending on the current recording state). \"\"\"", "type: String Source name. *monitorType* type: String The monitor type", "self.datain['colorRange'] class OpenProjector(Baserequests): \"\"\"Open a projector window or create a", "= None self.datain['volume'] = None self.datain['muted'] = None self.dataout['source'] =", "of the source or scene to be displayed (ignored for", "def __init__(self): Baserequests.__init__(self) self.name = 'ListOutputs' self.datain['outputs'] = None def", "the actual source's type. *sourceSettings* type: Object Source settings (varies", "URI (if `embedPictureFormat` was specified in the request) *imageFile* type:", "*current_scene* type: String Name of the currently active scene. *scenes*", "Object Filter settings \"\"\" def __init__(self, sourceName, filterName): Baserequests.__init__(self) self.name", "= scene class SetSceneTransitionOverride(Baserequests): \"\"\"Set a scene to use a", "clockwise rotation of the item in degrees. *scale.x* type: double", "= 'GetFilenameFormatting' self.datain['filename-formatting'] = None def getFilenameFormatting(self): return self.datain['filename-formatting'] class", "the `release` parameter set to `false`.* \"\"\" def __init__(self): Baserequests.__init__(self)", "username for the streaming service. *settings.password* type: String (optional) The", "source, color1=None, color2=None, custom_width=None, drop_shadow=None, font=None, from_file=None, log_mode=None, outline=None, text=None,", "the auth challenge (see \"Authentication\" for more information). \"\"\" def", "settings \"\"\" def __init__(self, transitionName): Baserequests.__init__(self) self.name = 'GetTransitionSettings' self.datain['transitionSettings']", "a transition :Arguments: *transitionName* type: String Transition name *transitionSettings* type:", "def getExtents_cy(self): return self.datain['extents_cy'] def getFile(self): return self.datain['file'] def getRead_from_file(self):", "Baserequests.__init__(self) self.name = 'SetCurrentTransition' self.dataout['transition-name'] = transition_name class SetTransitionDuration(Baserequests): \"\"\"Set", "getAuthRequired(self): return self.datain['authRequired'] def getChallenge(self): return self.datain['challenge'] def getSalt(self): return", "recording status. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetReplayBufferStatus' self.datain['isReplayBufferActive']", "def getAvailableRequests(self): return self.datain['available-requests'] def getSupportedImageExportFormats(self): return self.datain['supported-image-export-formats'] class GetAuthRequired(Baserequests):", "or not paused. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ResumeRecording'", "type: String Text vertical alignment (\"top\", \"center\", \"bottom\"). *vertical* type:", "*baseWidth* type: int Base (canvas) width *baseHeight* type: int Base", "return self.datain['mic-3'] class GetSourceFilters(Baserequests): \"\"\"List filters applied to a source", "return self.datain['supported-image-export-formats'] class GetAuthRequired(Baserequests): \"\"\"Tells the client if authentication is", "type: String Source name :Returns: *filters* type: Array<Object> List of", "- DO NOT EDIT # # (Generated on 2020-12-20 18:26:33.661372)", "GetStreamSettings). :Arguments: *type* type: String The type of streaming service", "(0-100). *chatlog* type: boolean (optional) Chat log. *chatlog_lines* type: int", "def getMuted(self): return self.datain['muted'] def getLocked(self): return self.datain['locked'] def getBounds(self):", "__init__(self): Baserequests.__init__(self) self.name = 'GetCurrentTransition' self.datain['name'] = None self.datain['duration'] =", "ListProfiles(Baserequests): \"\"\"Get a list of available profiles. :Returns: *profiles* type:", "timestamp of a media source. Supports ffmpeg and vlc media", "transition in the frontend's dropdown menu. :Returns: *name* type: String", "amount of pixels cropped off the bottom of the source", "`scene` \"\"\" def __init__(self, sceneName=None): Baserequests.__init__(self) self.name = 'GetSceneItemList' self.datain['sceneName']", "= transitionName self.dataout['transitionSettings'] = transitionSettings def getTransitionSettings(self): return self.datain['transitionSettings'] class", "\"\"\"Deletes a scene item. :Arguments: *scene* type: String (optional) Name", "return self.datain['scale'] def getCrop(self): return self.datain['crop'] def getVisible(self): return self.datain['visible']", "settings. Setting this hotkey is mandatory, even when triggering saves", "of the stream (the same as GetStreamSettings). :Arguments: *type* type:", "self.datain['outline'] def getText(self): return self.datain['text'] def getText_file(self): return self.datain['text_file'] def", "getProfiles(self): return self.datain['profiles'] class GetRecordingStatus(Baserequests): \"\"\"Get current recording status. :Returns:", "the currently configured stream type does not match the given", "type: String Name of the source on which the filter", "= None def getIsReplayBufferActive(self): return self.datain['isReplayBufferActive'] class StartStopReplayBuffer(Baserequests): \"\"\"Toggle the", "= log_mode self.dataout['outline'] = outline self.dataout['text'] = text self.dataout['text_file'] =", "'GetRecordingStatus' self.datain['isRecording'] = None self.datain['isRecordingPaused'] = None self.datain['recordTimecode'] = None", "of the specified source *sourceSettings* type: Object Source settings (varies", "effective on the next recording. :Arguments: *rec_folder* type: String Path", "int (optional) Outline size. *outline_opacity* type: int (optional) Outline opacity", "String (optional) Format of the Data URI encoded picture. Can", "Extents cy. *file* type: String File path name. *read_from_file* type:", "of the source item. *right* type: int Pixel position of", "= sourceName self.dataout['newName'] = newName class SetSyncOffset(Baserequests): \"\"\"Set the audio", "Url. *css* type: String CSS to inject. *width* type: int", "types, formatted as a comma-separated list string (e.g. : \"Method1,Method2,Method3\").", "*vertical* type: boolean (optional) Vertical text enabled. *render* type: boolean", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopStreaming' class SetStreamSettings(Baserequests): \"\"\"Sets", "Frames rendered per second *videoFormat* type: String Video color format", "Baserequests.__init__(self) self.name = 'SetTextGDIPlusProperties' self.dataout['source'] = source self.dataout['align'] = align", "= None self.datain['img'] = None self.datain['imageFile'] = None self.dataout['sourceName'] =", "Scene item height (base source height multiplied by the vertical", "getGradient_opacity(self): return self.datain['gradient_opacity'] def getOutline(self): return self.datain['outline'] def getOutline_color(self): return", "= source self.dataout['useDecibel'] = useDecibel def getName(self): return self.datain['name'] def", "next recording. :Arguments: *rec_folder* type: String Path of the recording", "current media position. \"\"\" def __init__(self, sourceName, timeOffset): Baserequests.__init__(self) self.name", "return self.datain['filters'] class GetSourceFilterInfo(Baserequests): \"\"\"List filters applied to a source", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSceneList' self.datain['current-scene'] = None", "*audioActive* type: boolean Audio active status of the source. \"\"\"", "def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaState' self.datain['mediaState'] = None", "active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopRecording' class PauseRecording(Baserequests):", "return self.datain['transitionName'] def getTransitionDuration(self): return self.datain['transitionDuration'] class GetStreamingStatus(Baserequests): \"\"\"Get current", "file as (one of the values provided in the `supported-image-export-formats`", "def getType(self): return self.datain['type'] def getSettings(self): return self.datain['settings'] class SaveStreamSettings(Baserequests):", "type: int The number of pixels cropped off the bottom", "String Filename formatting string to set. \"\"\" def __init__(self, filename_formatting):", "Transition name :Returns: *transitionSettings* type: Object Current transition settings \"\"\"", "getText(self): return self.datain['text'] def getText_file(self): return self.datain['text_file'] def getWord_wrap(self): return", "request) \"\"\" def __init__(self, sourceName=None, embedPictureFormat=None, saveToFilePath=None, fileFormat=None, compressionQuality=None, width=None,", "position. This value must be between 0.0 and 1.0. *release*", "created scene item \"\"\" def __init__(self, sceneName, sourceName, setVisible): Baserequests.__init__(self)", "type: String Name of the new filter *filterType* type: String", "self.name = 'GetVersion' self.datain['version'] = None self.datain['obs-websocket-version'] = None self.datain['obs-studio-version']", "was created *item* type: Object New item info *item.id* type:", "class GetAudioActive(Baserequests): \"\"\"Get the audio's active status of a specified", "return self.datain['source'] def getColor1(self): return self.datain['color1'] def getColor2(self): return self.datain['color2']", "of the left of the source item. *right* type: int", "\"down\", \"top\" or \"bottom\". \"\"\" def __init__(self, sourceName, filterName, movementType):", "self.datain['position'] def getRotation(self): return self.datain['rotation'] def getScale(self): return self.datain['scale'] def", "*filters.*.settings* type: Object Filter settings \"\"\" def __init__(self, sourceName): Baserequests.__init__(self)", "filter in the chain (absolute index positioning) :Arguments: *sourceName* type:", "return self.datain['version'] def getObsWebsocketVersion(self): return self.datain['obs-websocket-version'] def getObsStudioVersion(self): return self.datain['obs-studio-version']", "save the image file as (one of the values provided", "coordinate. \"\"\" def __init__(self, item, x, y, scene_name=None): Baserequests.__init__(self) self.name", "the top of the source before scaling. *crop.right* type: int", "self.name = 'GetTextGDIPlusProperties' self.datain['source'] = None self.datain['align'] = None self.datain['bk_color']", "scene_name=None): Baserequests.__init__(self) self.name = 'GetSceneItemProperties' self.datain['name'] = None self.datain['itemId'] =", "Pixel position of the top of the source item. *bottom*", "if the Replay Buffer is not active. \"\"\" def __init__(self):", "= 'ToggleMute' self.dataout['source'] = source class GetAudioActive(Baserequests): \"\"\"Get the audio's", "__init__(self): Baserequests.__init__(self) self.name = 'ListProfiles' self.datain['profiles'] = None def getProfiles(self):", "amplitude/mul. \"\"\" def __init__(self, source, volume, useDecibel=None): Baserequests.__init__(self) self.name =", "\"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetMute' self.datain['name'] =", "color. *outline_size* type: int Outline size. *outline_opacity* type: int Outline", "supported by Qt's Image module) *saveToFilePath* type: String (optional) Full", "class ListSceneCollections(Baserequests): \"\"\"List available scene collections :Returns: *scene_collections* type: Array<String>", "self.datain['timestamp'] = None self.dataout['sourceName'] = sourceName def getTimestamp(self): return self.datain['timestamp']", "Qt's Image module) *saveToFilePath* type: String (optional) Full file path", "self.datain['outputs'] class GetOutputInfo(Baserequests): \"\"\"Get information about a single output :Arguments:", "String (optional) Name of the item's parent (if this item", "present if currently streaming). *rec_timecode* type: String (optional) Time elapsed", "String Name of the source. *is_local_file* type: boolean (optional) Indicates", "None self.datain['chatlog_lines'] = None self.datain['color'] = None self.datain['extents'] = None", "wrap. \"\"\" def __init__(self, source, color1=None, color2=None, custom_width=None, drop_shadow=None, font=None,", "name. *offset* type: int The desired audio sync offset (in", "Array<Output> Outputs list \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListOutputs'", "of the current streaming server settings. Any options not passed", "*font* type: Object (optional) Holds data for the font. Ex:", "(optional) Id of a specific scene item. Unique on a", "specific properties of a source. Unspecified properties will remain unchanged.", "top of the source before scaling. *crop.bottom* type: int (optional)", "SetSceneItemTransform(Baserequests): \"\"\"Set the transform of the specified source item. :Arguments:", "= 'ReorderSceneItems' self.dataout['items'] = items self.dataout['scene'] = scene class SetSceneTransitionOverride(Baserequests):", "true :Returns: *itemId* type: int ID of the SceneItem in", "return self.datain['sourceType'] def getSourceSettings(self): return self.datain['sourceSettings'] class GetTextGDIPlusProperties(Baserequests): \"\"\"Get the", "int The total length of media in milliseconds.. \"\"\" def", "def getItemId(self): return self.datain['itemId'] def getPosition(self): return self.datain['position'] def getRotation(self):", "*rec_timecode* type: String (optional) Time elapsed since recording started (only", "self.dataout['filterName'] = filterName self.dataout['movementType'] = movementType class SetSourceFilterSettings(Baserequests): \"\"\"Update settings", "Scene item width (base source width multiplied by the horizontal", "ToggleStudioMode(Baserequests): \"\"\"Toggles Studio Mode (depending on the current state of", "return self.datain['read_from_file'] def getFont(self): return self.datain['font'] def getGradient(self): return self.datain['gradient']", "= 'SetSceneItemProperties' self.dataout['item'] = item self.dataout['scene-name'] = scene_name self.dataout['position'] =", "self.datain['gradient_opacity'] def getOutline(self): return self.datain['outline'] def getOutline_color(self): return self.datain['outline_color'] def", "item self.dataout['x-scale'] = x_scale self.dataout['y-scale'] = y_scale self.dataout['rotation'] = rotation", "for a Browser Source. :Arguments: *source* type: String Name of", "*item.name* type: String New item name \"\"\" def __init__(self, item,", "Base (canvas) height *outputWidth* type: int Output width *outputHeight* type:", "active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopReplayBuffer' class SaveReplayBuffer(Baserequests):", "getRecTimecode(self): return self.datain['rec-timecode'] def getPreviewOnly(self): return self.datain['preview-only'] class StartStopStreaming(Baserequests): \"\"\"Toggle", "Name of the second Mic/Aux input source. *mic_3* type: String", "sourceSettings=None, setVisible=None): Baserequests.__init__(self) self.name = 'CreateSource' self.datain['itemId'] = None self.dataout['sourceName']", "*text* type: String Captions text \"\"\" def __init__(self, text): Baserequests.__init__(self)", "Italic=2, Bold Italic=3, Underline=5, Strikeout=8` *font.size* type: int Font text", "path. *word_wrap* type: boolean Word wrap. \"\"\" def __init__(self, source):", "information about a single output :Arguments: *outputName* type: String Output", "loop if it's audio is monitored and shouldn't be \"\"\"", "the source. 'true' shows source, 'false' hides source. *locked* type:", "def getItem(self): return self.datain['item'] class SetCurrentScene(Baserequests): \"\"\"Switch to the specified", "self.datain['outline'] = None self.datain['outline_color'] = None self.datain['outline_size'] = None self.datain['outline_opacity']", "and under 26.0 for dB. OBS will interpret dB values", "self.name = 'BroadcastCustomMessage' self.dataout['realm'] = realm self.dataout['data'] = data class", "None self.datain['drop_shadow'] = None self.datain['font'] = None self.datain['from_file'] = None", "*crop.bottom* type: int (optional) The new amount of pixels cropped", "between `0.0` and `20.0` for mul, and under 26.0 for", "connecting to the streaming server. *settings.username* type: String The username", "error. :Arguments: *sourceName* type: String Source name. *newName* type: String", "self.dataout['duration'] = duration class GetTransitionDuration(Baserequests): \"\"\"Get the duration of the", "nanoseconds). \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetSyncOffset' self.datain['name']", "collections list *scene_collections.*.sc_name* type: String Scene collection name \"\"\" def", "recording is already active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "left. *position.y* type: double The y position of the source", "\"\"\"Sets one or more attributes of the current streaming server", "Starts/Stops emitting heartbeat messages \"\"\" def __init__(self, enable): Baserequests.__init__(self) self.name", "None self.datain['obs-websocket-version'] = None self.datain['obs-studio-version'] = None self.datain['available-requests'] = None", "values provided in the `supported-image-export-formats` response field of `GetVersion`). If", "def getName(self): return self.datain['name'] def getItemId(self): return self.datain['itemId'] def getPosition(self):", "be off by upwards of 50ms. :Arguments: *sourceName* type: String", "current overriding transition. Empty string if no override is set.", "type *name* type: String Filter name *settings* type: Object Filter", "item id of the source item *sceneItems.*.sourceKind* type: String ID", "None def getType(self): return self.datain['type'] def getSettings(self): return self.datain['settings'] class", "GetStreamingStatus(Baserequests): \"\"\"Get current streaming and recording status. :Returns: *streaming* type:", "class TransitionToProgram(Baserequests): \"\"\"Transitions the currently previewed scene to the main", "self.name = 'GetMediaTime' self.datain['timestamp'] = None self.dataout['sourceName'] = sourceName def", "\"\"\" def __init__(self, item, x_scale, y_scale, rotation, scene_name=None): Baserequests.__init__(self) self.name", ":Returns: *source* type: String Source name *color1* type: int Gradient", "the source. *align* type: String (optional) Text Alignment (\"left\", \"center\",", "'GetSpecialSources' self.datain['desktop-1'] = None self.datain['desktop-2'] = None self.datain['mic-1'] = None", "Ignored if `use_auth` is not set to `true`. \"\"\" def", "*sourceHeight* type: int Base source (without scaling) of the source", "= with_transition class EnableStudioMode(Baserequests): \"\"\"Enables Studio Mode. \"\"\" def __init__(self):", "self.dataout['is_local_file'] = is_local_file self.dataout['local_file'] = local_file self.dataout['url'] = url self.dataout['css']", "scene item. :Arguments: *scene* type: String (optional) Name of the", "*stream.settings.username* type: String (optional) If authentication is enabled, the username", "*settings* type: Object Filter settings \"\"\" def __init__(self, sourceName, filterName):", "scene collection. :Arguments: *sc_name* type: String Name of the desired", "= transitionDuration class RemoveSceneTransitionOverride(Baserequests): \"\"\"Remove any transition override on a", "GetAudioActive(Baserequests): \"\"\"Get the audio's active status of a specified source.", "def getProfiles(self): return self.datain['profiles'] class GetRecordingStatus(Baserequests): \"\"\"Get current recording status.", "sc_name): Baserequests.__init__(self) self.name = 'SetCurrentSceneCollection' self.dataout['sc-name'] = sc_name class GetCurrentSceneCollection(Baserequests):", "of all available sources types :Returns: *types* type: Array<Object> Array", "self.datain['transitionSettings'] = None self.dataout['transitionName'] = transitionName def getTransitionSettings(self): return self.datain['transitionSettings']", "Output volume in decibels of attenuation instead of amplitude/mul. :Returns:", "String List of available request types, formatted as a comma-separated", "milliseconds) if supported by the transition. \"\"\" def __init__(self): Baserequests.__init__(self)", "color. *bk_opacity* type: int (optional) Background opacity (0-100). *chatlog* type:", "if sources of this type provide audio *types.*.caps.canInteract* type: Boolean", "type: String Type of the specified source *sourceSettings* type: Object", "type: int (optional) Gradient opacity (0-100). *outline* type: boolean (optional)", "\"\"\"Set settings of the specified source. :Arguments: *sourceName* type: String", "'GetSceneItemProperties' self.datain['name'] = None self.datain['itemId'] = None self.datain['position'] = None", "def __init__(self, source): Baserequests.__init__(self) self.name = 'ToggleMute' self.dataout['source'] = source", "sum of 1=Left or 2=Right, and 4=Top or 8=Bottom, or", "is manipulated from. The sum of 1=Left or 2=Right, and", "Baserequests.__init__(self) self.name = 'GetSyncOffset' self.datain['name'] = None self.datain['offset'] = None", "about the streaming. May be any String, Numeric, or Boolean", "right of the source before scaling. *visible* type: bool (optional)", "= 'GetCurrentSceneCollection' self.datain['sc-name'] = None def getScName(self): return self.datain['sc-name'] class", "None self.dataout['sourceName'] = sourceName self.dataout['sourceKind'] = sourceKind self.dataout['sceneName'] = sceneName", "def __init__(self, sc_name): Baserequests.__init__(self) self.name = 'SetCurrentSceneCollection' self.dataout['sc-name'] = sc_name", "to disable). *drop_shadow* type: boolean Drop shadow. *font* type: Object", "type: double Width scale factor. *y_scale* type: double Height scale", "useDecibel def getName(self): return self.datain['name'] def getVolume(self): return self.datain['volume'] def", "Name of the source on which the filter is added", "monitorType): Baserequests.__init__(self) self.name = 'SetAudioMonitorType' self.dataout['sourceName'] = sourceName self.dataout['monitorType'] =", "can be off by upwards of 50ms. :Arguments: *sourceName* type:", "current state of media for that source. States: `none`, `playing`,", "type of stream matches the given type (usually 'rtmp_custom' or", "Transition duration (in milliseconds) if supported by the transition. \"\"\"", "be displayed. *text_file* type: String File path. *word_wrap* type: boolean", "The sum of 1=Left or 2=Right, and 4=Top or 8=Bottom,", "Type of the specified source. Useful for type-checking if you", "String The publish key of the stream. *settings.use_auth* type: boolean", "to create. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'CreateScene'", "(optional) Font Style (unknown function). *from_file* type: boolean (optional) Read", "boolean Current streaming status. *recording* type: boolean Current recording status.", "length of media in milliseconds. Supports ffmpeg and vlc media", "of the source from which the specified filter is removed", "content to be displayed. *valign* type: String Text vertical alignment", "created SceneItem as visible or not. Defaults to true :Returns:", "specified file. *font* type: Object (optional) Holds data for the", "Name of the selected transition. *duration* type: int (optional) Transition", "def __init__(self, enable): Baserequests.__init__(self) self.name = 'SetHeartbeat' self.dataout['enable'] = enable", "return self.datain['align'] def getBk_color(self): return self.datain['bk_color'] def getBk_opacity(self): return self.datain['bk_opacity']", "= filterName self.dataout['filterEnabled'] = filterEnabled class GetAudioMonitorType(Baserequests): \"\"\"Get the audio", ":Arguments: *source* type: String Source name. *volume* type: double Desired", "image is to be saved. Can be in a format", "getSources(self): return self.datain['sources'] class GetSceneList(Baserequests): \"\"\"Get a list of scenes", "set the timestamp to. \"\"\" def __init__(self, sourceName, timestamp): Baserequests.__init__(self)", "name. :Returns: *name* type: String Source name. *offset* type: int", "of this type provide frames asynchronously *types.*.caps.hasVideo* type: Boolean True", "= color self.dataout['extents'] = extents self.dataout['extents_cx'] = extents_cx self.dataout['extents_cy'] =", "type: String (optional) File path. *word_wrap* type: boolean (optional) Word", "def getTransitionSettings(self): return self.datain['transitionSettings'] class ReleaseTBar(Baserequests): \"\"\"Release the T-Bar (like", "class ListOutputs(Baserequests): \"\"\"List existing outputs :Returns: *outputs* type: Array<Output> Outputs", "return self.datain['profiles'] class GetRecordingStatus(Baserequests): \"\"\"Get current recording status. :Returns: *isRecording*", "String Source name *filterName* type: String Source filter name :Returns:", "source. :Arguments: *source* type: String Source name. *color1* type: int", "to the previous media item in the playlist. Supports only", "def getFps(self): return self.datain['fps'] def getShutdown(self): return self.datain['shutdown'] class SetBrowserSourceProperties(Baserequests):", "transitionName self.dataout['transitionSettings'] = transitionSettings def getTransitionSettings(self): return self.datain['transitionSettings'] class ReleaseTBar(Baserequests):", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetFilenameFormatting' self.datain['filename-formatting'] = None", "the current profile. :Returns: *profile_name* type: String Name of the", "int Scene Item ID. *position.x* type: double The x position", "None self.datain['fps'] = None self.datain['shutdown'] = None self.dataout['source'] = source", "Scene Item name. *x_scale* type: double Width scale factor. *y_scale*", "to duplicate from the source scene (required) *item.name* type: String", "WebSocket clients :Arguments: *realm* type: String Identifier to be choosen", "sourceName self.dataout['filterName'] = filterName class ReorderSourceFilter(Baserequests): \"\"\"Move a filter in", "self.dataout['render'] = render class GetSpecialSources(Baserequests): \"\"\"Get configured special sources like", "y_scale self.dataout['rotation'] = rotation self.dataout['scene-name'] = scene_name class SetSceneItemCrop(Baserequests): \"\"\"Sets", "String (optional) The username for the streaming service. *settings.password* type:", "getSettings(self): return self.datain['settings'] class SaveStreamSettings(Baserequests): \"\"\"Save the current streaming server", "be displayed. *valign* type: String (optional) Text vertical alignment (\"top\",", "gradient_opacity=None, outline=None, outline_color=None, outline_size=None, outline_opacity=None, text=None, valign=None, vertical=None, render=None): Baserequests.__init__(self)", "Extents cy. *file* type: String (optional) File path name. *read_from_file*", "scene_name=None): Baserequests.__init__(self) self.name = 'ResetSceneItem' self.dataout['item'] = item self.dataout['scene-name'] =", "the first Mic/Aux input source. *mic_2* type: String (optional) Name", "streaming is not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "None self.datain['is_local_file'] = None self.datain['local_file'] = None self.datain['url'] = None", "`use_auth` is `true`. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStreamSettings'", "= None self.datain['visible'] = None self.datain['muted'] = None self.datain['locked'] =", "type: String (optional) Name of the scene the scene item", "duration): Baserequests.__init__(self) self.name = 'SetTransitionDuration' self.dataout['duration'] = duration class GetTransitionDuration(Baserequests):", "service configuration, usually `rtmp_custom` or `rtmp_common`. *settings* type: Object The", "def getColorRange(self): return self.datain['colorRange'] class OpenProjector(Baserequests): \"\"\"Open a projector window", "None self.datain['parentGroupName'] = None self.datain['groupChildren'] = None self.dataout['item'] = item", "= 'GetCurrentProfile' self.datain['profile-name'] = None def getProfileName(self): return self.datain['profile-name'] class", "sourceName self.dataout['sourceType'] = sourceType def getSourceName(self): return self.datain['sourceName'] def getSourceType(self):", "*render* type: boolean true = shown ; false = hidden", "String (optional) If authentication is enabled, the username for the", ":Arguments: *with_transition* type: Object (optional) Change the active transition before", "of the source. *crop.top* type: int The number of pixels", "getOutline(self): return self.datain['outline'] def getOutline_color(self): return self.datain['outline_color'] def getOutline_size(self): return", "*recording* type: boolean Current recording status. *stream_timecode* type: String (optional)", "the next media item in the playlist. Supports only vlc", "amount of pixels cropped off the right of the source", "stop (default: false) \"\"\" def __init__(self, outputName, force=None): Baserequests.__init__(self) self.name", "Defaults to the current scene if not specified. :Returns: *sceneName*", "of a scene item. Sufficiently unique if no scene items", "__init__(self, sourceName, monitorType): Baserequests.__init__(self) self.name = 'SetAudioMonitorType' self.dataout['sourceName'] = sourceName", "are required. Returns the full settings of the stream (the", "Unique source name *mediaSources.*.sourceKind* type: String Unique source internal type", "GetBrowserSourceProperties(Baserequests): \"\"\"Get current properties for a Browser Source. :Arguments: *source*", "collections :Returns: *scene_collections* type: Array<String> Scene collections list *scene_collections.*.sc_name* type:", "dB. OBS will interpret dB values under -100.0 as Inf.", "source types *types.*.typeId* type: String Non-unique internal source type ID", "Image module) *saveToFilePath* type: String (optional) Full file path (file", "def getOutputs(self): return self.datain['outputs'] class GetOutputInfo(Baserequests): \"\"\"Get information about a", "to. *transitionName* type: String Name of the transition to use.", "and this value is not given. \"\"\" def __init__(self, sceneName,", "internal type (a.k.a kind) *sources.*.type* type: String Source type. Value", "manually if you set `release` to false. Defaults to true.", "*fromScene* type: String (optional) Name of the scene to copy", "a string) or specification (if it is an object). *item.name*", "video information :Returns: *baseWidth* type: int Base (canvas) width *baseHeight*", "its new position (like a user releasing their mouse button", "new locked status of the source. 'true' keeps it in", "type: String The password to use when accessing the streaming", "def getTransitionDuration(self): return self.datain['transitionDuration'] class GetStreamingStatus(Baserequests): \"\"\"Get current streaming and", "scene_name class TransitionToProgram(Baserequests): \"\"\"Transitions the currently previewed scene to the", "from the specified file. *font* type: Object Holds data for", "Available source types along with their settings properties are available", "be shutdown when not visible. *render* type: boolean (optional) Visibility", "type: bool (optional) The new visibility of the source. 'true'", "def getUrl(self): return self.datain['url'] def getCss(self): return self.datain['css'] def getWidth(self):", "*outline* type: boolean Outline. *text* type: String Text content to", "type: Array<Output> Outputs list \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "'SetSceneItemRender' self.dataout['source'] = source self.dataout['render'] = render self.dataout['scene-name'] = scene_name", "position of the filter in the chain \"\"\" def __init__(self,", "the currently previewed scene to the main output. Will return", "= None def getSceneCollections(self): return self.datain['scene-collections'] class GetSceneItemList(Baserequests): \"\"\"Get a", "GetMute(Baserequests): \"\"\"Get the mute status of a specified source. :Arguments:", "self.datain['baseWidth'] def getBaseHeight(self): return self.datain['baseHeight'] def getOutputWidth(self): return self.datain['outputWidth'] def", "specified ensures the type of stream matches the given type", "type: int (Optional) Monitor to open the projector on. If", "type: Integer Desired position of the filter in the chain", "__init__(self, sceneName): Baserequests.__init__(self) self.name = 'GetSceneTransitionOverride' self.datain['transitionName'] = None self.datain['transitionDuration']", "type: String Filter type *filters.*.name* type: String Filter name *filters.*.settings*", "the captured image is to be saved. Can be in", "__init__(self): Baserequests.__init__(self) self.name = 'GetTransitionPosition' self.datain['position'] = None def getPosition(self):", "seconds that the media is playing, the total duration can", "self.datain['extents_cy'] def getFile(self): return self.datain['file'] def getRead_from_file(self): return self.datain['read_from_file'] def", "def getFps(self): return self.datain['fps'] def getVideoFormat(self): return self.datain['videoFormat'] def getColorSpace(self):", "chain. Either \"up\", \"down\", \"top\" or \"bottom\". \"\"\" def __init__(self,", "String (optional) Name of the first Mic/Aux input source. *mic_2*", "OBS stats (almost the same info as provided in OBS'", "\"\"\"Get the path of the current recording folder. :Returns: *rec_folder*", "= 'SetHeartbeat' self.dataout['enable'] = enable class SetFilenameFormatting(Baserequests): \"\"\"Set the filename", "type: double X coordinate. *y* type: double Y coordinate. \"\"\"", "password for the streaming service. *save* type: boolean Persist the", "String Name of the selected transition. *duration* type: int (optional)", "sync offset (in nanoseconds). \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name", "Transition settings (they can be partial) :Returns: *transitionSettings* type: Object", "int Gradient top color. *color2* type: int Gradient bottom color.", "__init__(self, sourceName, filterName, filterType, filterSettings): Baserequests.__init__(self) self.name = 'AddFilterToSource' self.dataout['sourceName']", "objects with name and/or id specified. Id preferred due to", "`0.0` and `20.0` if using mul, under `26.0` if using", "def getExtents_cx(self): return self.datain['extents_cx'] def getExtents_cy(self): return self.datain['extents_cy'] def getFile(self):", "\"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'RestartMedia' self.dataout['sourceName'] =", "= 'ScrubMedia' self.dataout['sourceName'] = sourceName self.dataout['timeOffset'] = timeOffset class GetMediaState(Baserequests):", "the provided source. States: `none`, `playing`, `opening`, `buffering`, `paused`, `stopped`,", "__init__(self, source, mute): Baserequests.__init__(self) self.name = 'SetMute' self.dataout['source'] = source", "Background opacity (0-100). *chatlog* type: boolean Chat log. *chatlog_lines* type:", "= 'GetRecordingStatus' self.datain['isRecording'] = None self.datain['isRecordingPaused'] = None self.datain['recordTimecode'] =", "Underline=5, Strikeout=8` *font.size* type: int Font text size. *font.style* type:", "self.dataout['rotation'] = rotation self.dataout['scene-name'] = scene_name class SetSceneItemCrop(Baserequests): \"\"\"Sets the", "Name of the current overriding transition. Empty string if no", "this type composite one or more sub-sources *types.*.caps.doNotDuplicate* type: Boolean", "self.datain['recording'] def getStreamTimecode(self): return self.datain['stream-timecode'] def getRecTimecode(self): return self.datain['rec-timecode'] def", "= 'TransitionToProgram' self.dataout['with-transition'] = with_transition class EnableStudioMode(Baserequests): \"\"\"Enables Studio Mode.", "settings to disk. \"\"\" def __init__(self, type, settings, save): Baserequests.__init__(self)", "= source def getName(self): return self.datain['name'] def getOffset(self): return self.datain['offset']", "'ReleaseTBar' class SetTBarPosition(Baserequests): \"\"\" If your code needs to perform", "int (optional) Outline color. *outline_size* type: int (optional) Outline size.", "on a scene by scene basis. *items.*.name* type: String (optional)", "active scene collection. :Arguments: *sc_name* type: String Name of the", "including both is acceptable). *item.id* type: int Scene Item ID.", "drop_shadow=None, font=None, from_file=None, log_mode=None, outline=None, text=None, text_file=None, word_wrap=None): Baserequests.__init__(self) self.name", "def getCrop(self): return self.datain['crop'] def getVisible(self): return self.datain['visible'] def getMuted(self):", "Base source (without scaling) of the source *width* type: double", "'rtmp_common'). If the currently configured stream type does not match", "Array<Scene> Ordered list of the current profile's scenes (See [GetCurrentScene](#getcurrentscene)", "color. *color2* type: int (optional) Gradient bottom color. *custom_width* type:", "__init__(self, keyId, keyModifiers): Baserequests.__init__(self) self.name = 'TriggerHotkeyBySequence' self.dataout['keyId'] = keyId", "the source or scene to be displayed (ignored for other", "currently active profile. :Returns: *current_scene* type: String Name of the", "Source name *filterName* type: String Source filter name :Returns: *enabled*", "String Text vertical alignment (\"top\", \"center\", \"bottom\"). *vertical* type: boolean", "The new y scale of the item. *crop.top* type: int", "name. *sourceKind* type: String Source kind, Eg. `vlc_source`. *sceneName* type:", "streaming server. *settings.username* type: String (optional) The username for the", "Buffer is not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "type: String The name of the transition. \"\"\" def __init__(self,", "current scene. *item* type: String Scene Item name. *top* type:", "be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\" or \"OBS_BOUNDS_NONE\". *bounds.alignment*", "right of the source before scaling. *crop.bottom* type: int The", "def __init__(self): Baserequests.__init__(self) self.name = 'StopStreaming' class SetStreamSettings(Baserequests): \"\"\"Sets one", "boolean Indicates whether the source is muted. \"\"\" def __init__(self,", "sources (as of OBS v25.0.8) :Arguments: *sourceName* type: String Source", "\"\"\"Set the audio monitoring type of the specified source. :Arguments:", "the media state of all media sources (vlc and media", "= 'StartStopReplayBuffer' class StartReplayBuffer(Baserequests): \"\"\"Start recording into the Replay Buffer.", "current profile. :Returns: *profile_name* type: String Name of the currently", "scene where the new item was created *item* type: Object", "will return an error. :Arguments: *sourceName* type: String Source name.", "Returns an error if recording is not active or not", "int Milliseconds to set the timestamp to. \"\"\" def __init__(self,", "__init__(self, item, scene=None): Baserequests.__init__(self) self.name = 'DeleteSceneItem' self.dataout['item'] = item", "as a sceneitem to a scene. :Arguments: *sourceName* type: String", "Boolean Filter status (enabled or not) *type* type: String Filter", "__init__(self, sceneName): Baserequests.__init__(self) self.name = 'CreateScene' self.dataout['sceneName'] = sceneName class", "def getParentGroupName(self): return self.datain['parentGroupName'] def getGroupChildren(self): return self.datain['groupChildren'] class SetSceneItemProperties(Baserequests):", "properly when they are controlled in this way. :Arguments: *outputName*", "\"\"\" def __init__(self, sourceName, playPause): Baserequests.__init__(self) self.name = 'PlayPauseMedia' self.dataout['sourceName']", ":Returns: *isRecording* type: boolean Current recording status. *isRecordingPaused* type: boolean", "None self.dataout['sourceName'] = sourceName def getAudioActive(self): return self.datain['audioActive'] class SetSourceName(Baserequests):", "value will be between 0.0 and 1.0. Note: Transition returns", "*item.id* type: int Scene Item ID. \"\"\" def __init__(self, item,", "called while a recording is in progress, the change won't", "(optional) The password for the streaming service. *save* type: boolean", "not) *type* type: String Filter type *name* type: String Filter", "self.datain['color2'] = None self.datain['custom_width'] = None self.datain['drop_shadow'] = None self.datain['font']", "None self.datain['custom_width'] = None self.datain['drop_shadow'] = None self.datain['font'] = None", "paused). Returns an error if recording is not active or", "of the currently active scene. *scenes* type: Array<Scene> Ordered list", "scaling. *crop.left* type: int The number of pixels cropped off", "of the bounding box. *bounds.x* type: double Width of the", "def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionList' self.datain['current-transition'] = None self.datain['transitions']", "New item info *item.id* type: int New item ID *item.name*", "source): Baserequests.__init__(self) self.name = 'GetTextFreetype2Properties' self.datain['source'] = None self.datain['color1'] =", "\"\"\" def __init__(self, scene_name): Baserequests.__init__(self) self.name = 'SetCurrentScene' self.dataout['scene-name'] =", "is required. If so, returns authentication parameters `challenge` and `salt`", "None self.datain['volume'] = None self.datain['muted'] = None self.dataout['source'] = source", "\"filter\", \"transition\", \"scene\" or \"unknown\" \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "fixed. Defaults to the current duration specified in the UI", "getStats(self): return self.datain['stats'] class BroadcastCustomMessage(Baserequests): \"\"\"Broadcast custom message to all", "double The x-scale factor of the source. *scale.y* type: double", "\"\"\" def __init__(self, realm, data): Baserequests.__init__(self) self.name = 'BroadcastCustomMessage' self.dataout['realm']", "Baserequests.__init__(self) self.name = 'GetSourcesList' self.datain['sources'] = None def getSources(self): return", "the requested (or current) scene *sceneItems* type: Array<Object> Array of", "of bounding box. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\",", "top, bottom, left, right, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemCrop' self.dataout['item']", "in your User Interface), set `release` to false and call", "self.datain['studio-mode'] = None def getStudioMode(self): return self.datain['studio-mode'] class GetPreviewScene(Baserequests): \"\"\"Get", "type: boolean (optional) Interperet `volume` data as decibels instead of", "URL. *settings.key* type: String The publish key of the stream.", "(optional) Compression ratio between -1 and 100 to write the", "String (optional) Name of the scene to reorder (defaults to", "Baserequests.__init__(self) self.name = 'RestartMedia' self.dataout['sourceName'] = sourceName class StopMedia(Baserequests): \"\"\"Stop", "class GetSourceFilterInfo(Baserequests): \"\"\"List filters applied to a source :Arguments: *sourceName*", ":Arguments: *profile_name* type: String Name of the desired profile. \"\"\"", "not function properly when they are controlled in this way.", "getPreviewOnly(self): return self.datain['preview-only'] class StartStopStreaming(Baserequests): \"\"\"Toggle streaming on or off", "*filterName* type: String Name of the filter to reconfigure *filterSettings*", "y scale of the item. *crop.top* type: int (optional) The", "\"\"\" def __init__(self, transition_name): Baserequests.__init__(self) self.name = 'SetCurrentTransition' self.dataout['transition-name'] =", "States: `none`, `playing`, `opening`, `buffering`, `paused`, `stopped`, `ended`, `error`, `unknown`", "to disk. \"\"\" def __init__(self, type, settings, save): Baserequests.__init__(self) self.name", "self.dataout['outline_color'] = outline_color self.dataout['outline_size'] = outline_size self.dataout['outline_opacity'] = outline_opacity self.dataout['text']", "= settings self.dataout['save'] = save class GetStreamSettings(Baserequests): \"\"\"Get the current", "None self.datain['transitionDuration'] = None self.dataout['sceneName'] = sceneName def getTransitionName(self): return", "\"input\", \"filter\", \"transition\", \"scene\" or \"unknown\" \"\"\" def __init__(self): Baserequests.__init__(self)", "of the bounding box. \"\"\" def __init__(self, item, scene_name=None, position=None,", "class GetSceneItemProperties(Baserequests): \"\"\"Gets the scene specific properties of the specified", "class ScrubMedia(Baserequests): \"\"\"Scrub media using a supplied offset. Supports ffmpeg", "def __init__(self): Baserequests.__init__(self) self.name = 'GetFilenameFormatting' self.datain['filename-formatting'] = None def", "self.datain['audioActive'] class SetSourceName(Baserequests): \"\"\" Note: If the new name already", "active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'SaveReplayBuffer' class SetCurrentSceneCollection(Baserequests):", "'SaveReplayBuffer' class SetCurrentSceneCollection(Baserequests): \"\"\"Change the active scene collection. :Arguments: *sc_name*", "source. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSpecialSources' self.datain['desktop-1'] =", "identified by hotkey unique name :Arguments: *hotkeyName* type: String Unique", "item self.dataout['x'] = x self.dataout['y'] = y self.dataout['scene-name'] = scene_name", "*sourceName* type: String Source name. *playPause* type: boolean Whether to", "self.datain['drop_shadow'] def getFont(self): return self.datain['font'] def getFrom_file(self): return self.datain['from_file'] def", "return self.datain['isReplayBufferActive'] class StartStopReplayBuffer(Baserequests): \"\"\"Toggle the Replay Buffer on/off (depending", "align self.dataout['bk_color'] = bk_color self.dataout['bk_opacity'] = bk_opacity self.dataout['chatlog'] = chatlog", "def getAlign(self): return self.datain['align'] def getBk_color(self): return self.datain['bk_color'] def getBk_opacity(self):", "to a user moving a T-Bar control in your User", "name *color1* type: int Gradient top color. *color2* type: int", "This is basically the same as triggering the \"Save Replay", "to be displayed (ignored for other projector types). \"\"\" def", "The new x scale of the item. *scale.y* type: double", "of the current transition (in milliseconds). \"\"\" def __init__(self): Baserequests.__init__(self)", "self.name = 'ToggleStudioMode' class GetTransitionList(Baserequests): \"\"\"List of all transitions available", "saveToFilePath self.dataout['fileFormat'] = fileFormat self.dataout['compressionQuality'] = compressionQuality self.dataout['width'] = width", "type: double Y coordinate. \"\"\" def __init__(self, item, x, y,", "= 'StopStreaming' class SetStreamSettings(Baserequests): \"\"\"Sets one or more attributes of", "'true' shows source, 'false' hides source. *locked* type: bool (optional)", "return self.datain['position'] def getRotation(self): return self.datain['rotation'] def getScale(self): return self.datain['scale']", "None self.dataout['item'] = item self.dataout['scene-name'] = scene_name def getName(self): return", "Y coordinate. \"\"\" def __init__(self, item, x, y, scene_name=None): Baserequests.__init__(self)", "is muted. *locked* type: bool If the source's transform is", "= None self.datain['offset'] = None self.dataout['source'] = source def getName(self):", "source, is_local_file=None, local_file=None, url=None, css=None, width=None, height=None, fps=None, shutdown=None, render=None):", "a monitor. Requires OBS v24.0.4 or newer. :Arguments: *type* type:", "self.name = 'DisableStudioMode' class ToggleStudioMode(Baserequests): \"\"\"Toggles Studio Mode (depending on", "__init__(self): Baserequests.__init__(self) self.name = 'ListOutputs' self.datain['outputs'] = None def getOutputs(self):", "type: String (optional) Name of the first Mic/Aux input source.", "alignment of the bounding box. (0-2, 4-6, 8-10) *bounds.x* type:", "self.datain['bk_opacity'] = None self.datain['chatlog'] = None self.datain['chatlog_lines'] = None self.datain['color']", "captured image is to be saved. Can be in a", "*outline* type: boolean (optional) Outline. *outline_color* type: int (optional) Outline", "source type *types.*.type* type: String Type. Value is one of", "as provided in OBS' stats window) :Returns: *stats* type: OBSStats", "Baserequests.__init__(self) self.name = 'GetTransitionList' self.datain['current-transition'] = None self.datain['transitions'] = None", "Baserequests.__init__(self) self.name = 'SetHeartbeat' self.dataout['enable'] = enable class SetFilenameFormatting(Baserequests): \"\"\"Set", "self.datain['outline_opacity'] def getText(self): return self.datain['text'] def getValign(self): return self.datain['valign'] def", "server. Ignored if `use_auth` is not set to `true`. \"\"\"", "*bounds.y* type: double (optional) The new height of the bounding", "for more information). :Returns: *authRequired* type: boolean Indicates whether authentication", "Interface), set `release` to false and call `ReleaseTBar` later once", "the source before scaling. *crop.left* type: int (optional) The new", "type: bool If the source is visible. *muted* type: bool", "guess based on file extension. *compressionQuality* type: int (optional) Compression", "properties for a Browser Source. :Arguments: *source* type: String Source", "= None self.datain['outline'] = None self.datain['outline_color'] = None self.datain['outline_size'] =", "return self.datain['shutdown'] class SetBrowserSourceProperties(Baserequests): \"\"\"Set current properties for a Browser", "self.datain['authRequired'] = None self.datain['challenge'] = None self.datain['salt'] = None def", "streaming server. Ignored if `use_auth` is not set to `true`.", "of the source *width* type: double Scene item width (base", "*outputInfo* type: Output Output info \"\"\" def __init__(self, outputName): Baserequests.__init__(self)", "DeleteSceneItem(Baserequests): \"\"\"Deletes a scene item. :Arguments: *scene* type: String (optional)", "\"\"\"Remove a filter from a source :Arguments: *sourceName* type: String", "self.dataout['data'] = data class GetVideoInfo(Baserequests): \"\"\"Get basic OBS video information", "GetOutputInfo(Baserequests): \"\"\"Get information about a single output :Arguments: *outputName* type:", "Size and position of the projector window (only if monitor", "\"\"\" def __init__(self, source, is_local_file=None, local_file=None, url=None, css=None, width=None, height=None,", "streaming. Will return an `error` if streaming is not active.", "class SetSourceFilterSettings(Baserequests): \"\"\"Update settings of a filter :Arguments: *sourceName* type:", "not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopRecording' class", "= None self.datain['scaleType'] = None self.datain['fps'] = None self.datain['videoFormat'] =", "this type provide frames asynchronously *types.*.caps.hasVideo* type: Boolean True if", "entries can be ommitted *keyModifiers.shift* type: boolean Trigger Shift Key", "SetVolume(Baserequests): \"\"\"Set the volume of the specified source. Default request", "(optional) Chat log. *outline* type: boolean (optional) Outline. *text* type:", "def __init__(self): Baserequests.__init__(self) self.name = 'GetReplayBufferStatus' self.datain['isReplayBufferActive'] = None def", ":Returns: *itemId* type: int Numerical ID of the created scene", "current streaming and recording status. :Returns: *streaming* type: boolean Current", "def __init__(self): Baserequests.__init__(self) self.name = 'GetSourcesList' self.datain['sources'] = None def", "Item ID (if the `item` field is an object) *position.x*", "def getLocked(self): return self.datain['locked'] def getBounds(self): return self.datain['bounds'] def getSourceWidth(self):", "`20.0` for mul, and under 26.0 for dB. OBS will", "authentication is enabled, the password for the streaming server. Ignored", "*chatlog* type: boolean Chat log. *chatlog_lines* type: int Chat log", "to make the sceneitem visible on creation or not. Default", "'StopStreaming' class SetStreamSettings(Baserequests): \"\"\"Sets one or more attributes of the", "class SetTransitionDuration(Baserequests): \"\"\"Set the duration of the currently selected transition", "Baserequests.__init__(self) self.name = 'SetPreviewScene' self.dataout['scene-name'] = scene_name class TransitionToProgram(Baserequests): \"\"\"Transitions", "type: int Desired duration of the transition (in milliseconds). \"\"\"", "item width (base source width multiplied by the horizontal scaling", "request has also not been tested. :Arguments: *sourceName* type: String", "\"\"\"Get the status of the OBS replay buffer. :Returns: *isReplayBufferActive*", "*bk_opacity* type: int (optional) Background opacity (0-100). *chatlog* type: boolean", "type: int Output width *outputHeight* type: int Output height *scaleType*", "SetTBarPosition(Baserequests): \"\"\" If your code needs to perform multiple successive", "OBS v25.0.8) :Arguments: *sourceName* type: String Source name. *playPause* type:", "vertical alignment (\"top\", \"center\", \"bottom\"). *vertical* type: boolean (optional) Vertical", "def __init__(self): Baserequests.__init__(self) self.name = 'GetRecordingStatus' self.datain['isRecording'] = None self.datain['isRecordingPaused']", "the current streaming server settings. :Returns: *type* type: String The", "overriding transition. Empty string if no override is set. *transitionDuration*", "sceneName def getTransitionName(self): return self.datain['transitionName'] def getTransitionDuration(self): return self.datain['transitionDuration'] class", "height *outputWidth* type: int Output width *outputHeight* type: int Output", "v25.0.8) :Arguments: *sourceName* type: String Source name. \"\"\" def __init__(self,", "String Source name. :Returns: *timestamp* type: int The time in", "Source name. :Returns: *source* type: String Source name. *is_local_file* type:", "false = hidden \"\"\" def __init__(self, source, render, scene_name=None): Baserequests.__init__(self)", "def __init__(self, source, useDecibel=None): Baserequests.__init__(self) self.name = 'GetVolume' self.datain['name'] =", "= 'GetStreamSettings' self.datain['type'] = None self.datain['settings'] = None def getType(self):", "\"\"\" def __init__(self, item, fromScene=None, toScene=None): Baserequests.__init__(self) self.name = 'DuplicateSceneItem'", "getAvailableRequests(self): return self.datain['available-requests'] def getSupportedImageExportFormats(self): return self.datain['supported-image-export-formats'] class GetAuthRequired(Baserequests): \"\"\"Tells", "'DeleteSceneItem' self.dataout['item'] = item self.dataout['scene'] = scene class AddSceneItem(Baserequests): \"\"\"Creates", "self.dataout['source'] = source class GetAudioActive(Baserequests): \"\"\"Get the audio's active status", "bool If the source's transform is locked. *bounds.type* type: String", "the volume of the specified source. Default request format uses", "type: int The audio sync offset (in nanoseconds). \"\"\" def", "server settings to disk. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "sourceName): Baserequests.__init__(self) self.name = 'GetAudioMonitorType' self.datain['monitorType'] = None self.dataout['sourceName'] =", "*name* type: String (Optional) Name of the source or scene", "string :Returns: *filename_formatting* type: String Current filename formatting string. \"\"\"", "Visibility of the scene item. \"\"\" def __init__(self, source, align=None,", "current scene if not specified. :Returns: *sceneName* type: String Name", "def getPosition(self): return self.datain['position'] def getRotation(self): return self.datain['rotation'] def getScale(self):", "self.datain['position'] = None def getPosition(self): return self.datain['position'] class GetTransitionSettings(Baserequests): \"\"\"Get", "return self.datain['sourceSettings'] class GetTextGDIPlusProperties(Baserequests): \"\"\"Get the current properties of a", "self.datain['crop'] def getVisible(self): return self.datain['visible'] def getMuted(self): return self.datain['muted'] def", "any other value supported by Qt's Image module) *saveToFilePath* type:", "type: int Text color. *extents* type: boolean Extents wrap. *extents_cx*", "self.name = 'PauseRecording' class ResumeRecording(Baserequests): \"\"\"Resume/unpause the current recording (if", "Word wrap. \"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetTextFreetype2Properties'", "(optional) If authentication is enabled, the username for the streaming", "None self.datain['shutdown'] = None self.dataout['source'] = source def getSource(self): return", "self.dataout['sourceName'] = sourceName def getMediaState(self): return self.datain['mediaState'] class GetMediaSourcesList(Baserequests): \"\"\"List", "getSource(self): return self.datain['source'] def getAlign(self): return self.datain['align'] def getBk_color(self): return", "__init__(self, item, scene_name=None): Baserequests.__init__(self) self.name = 'GetSceneItemProperties' self.datain['name'] = None", "String, Numeric, or Boolean field. *stream.settings* type: Object (optional) Settings", "The y position of the source from the top. *position.alignment*", "List of supported formats for features that use image export", "belongs to. Defaults to the current scene. *item* type: Object", "new width of the bounding box. *bounds.y* type: double (optional)", "String Name of the currently active transition. *transitions* type: Array<Object>", "self.dataout['y-scale'] = y_scale self.dataout['rotation'] = rotation self.dataout['scene-name'] = scene_name class", "to switch to. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name =", "for mul, and under 26.0 for dB. OBS will interpret", "type: boolean Read text from the specified file. *font* type:", "self.datain['muted'] def getLocked(self): return self.datain['locked'] def getBounds(self): return self.datain['bounds'] def", "of the source before scaling. *crop.bottom* type: int The number", "self.dataout['url'] = url self.dataout['css'] = css self.dataout['width'] = width self.dataout['height']", "String Source name. :Returns: *name* type: String Source name. *muted*", "scene item belongs to. Defaults to the current scene. *item*", ":Arguments: *sc_name* type: String Name of the desired scene collection.", "int Numerical ID of the created scene item \"\"\" def", "of the replay buffer). \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "class GetFilenameFormatting(Baserequests): \"\"\"Get the filename formatting string :Returns: *filename_formatting* type:", "be displayed. *text_file* type: String (optional) File path. *word_wrap* type:", "box. *bounds.y* type: double (optional) The new height of the", "double (optional) The new y position of the source. *position.alignment*", "the Replay Buffer to disk. This is basically the same", "of the scene to switch to. *transitionName* type: String Name", "self.name = 'EnableStudioMode' class DisableStudioMode(Baserequests): \"\"\"Disables Studio Mode. \"\"\" def", "def getValign(self): return self.datain['valign'] def getVertical(self): return self.datain['vertical'] class SetTextGDIPlusProperties(Baserequests):", "\"\"\" def __init__(self, sourceName, timeOffset): Baserequests.__init__(self) self.name = 'ScrubMedia' self.dataout['sourceName']", "type: String The monitor type to use. Options: `none`, `monitorOnly`,", "recording folder. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetRecordingFolder' self.datain['rec-folder']", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'PauseRecording' class ResumeRecording(Baserequests): \"\"\"Resume/unpause", "type: String Scene Item name. *x_scale* type: double Width scale", "by the transition. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentTransition'", "Updated transition settings \"\"\" def __init__(self, transitionName, transitionSettings): Baserequests.__init__(self) self.name", "hotkeyName class TriggerHotkeyBySequence(Baserequests): \"\"\"Executes hotkey routine, identified by bound combination", "the current properties of a Text GDI Plus source. :Arguments:", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetVideoInfo' self.datain['baseWidth'] = None", "it belongs to). :Arguments: *scene_name* type: String (optional) Name of", "type: Object Stream settings object. *settings.server* type: String The publish", "type: String Name of the scene item's source *sceneItems.*.sourceType* type:", "= 'SetTextGDIPlusProperties' self.dataout['source'] = source self.dataout['align'] = align self.dataout['bk_color'] =", "Visibility of the scene item. \"\"\" def __init__(self, source, is_local_file=None,", "Name of the second Desktop Audio capture source. *mic_1* type:", "source *sceneItems.*.sourceType* type: String Type of the scene item's source.", "(in milliseconds). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionDuration' self.datain['transition-duration']", "*transitionSettings* type: Object Transition settings (they can be partial) :Returns:", "from which the specified filter is removed *filterName* type: String", "so, returns authentication parameters `challenge` and `salt` (see \"Authentication\" for", "Desktop Audio and Mic/Aux sources. :Returns: *desktop_1* type: String (optional)", "def getBounds(self): return self.datain['bounds'] def getSourceWidth(self): return self.datain['sourceWidth'] def getSourceHeight(self):", "bounding box. *bounds.x* type: double Width of the bounding box.", "Boolean True if sources of this type composite one or", "int (optional) Scene Item ID (if the `item` field is", "type: boolean (optional) Indicates whether authentication should be used when", "*name* type: String Scene Item name. *itemId* type: int Scene", "The new x position of the source. *position.y* type: double", "(0 to disable). *drop_shadow* type: boolean Drop shadow. *font* type:", "self.dataout['monitorType'] = monitorType class TakeSourceScreenshot(Baserequests): \"\"\" At least `embedPictureFormat` or", "(optional) Type of the specified source. Useful for type-checking to", "source *sourceHeight* type: int Base source (without scaling) of the", "since recording started (only present if currently recording). *recordingFilename* type:", "they are controlled in this way. :Arguments: *outputName* type: String", "= sourceName class StopMedia(Baserequests): \"\"\"Stop a media source. Supports ffmpeg", "Useful for type-checking to avoid settings a set of settings", "= position self.dataout['rotation'] = rotation self.dataout['scale'] = scale self.dataout['crop'] =", "transitions. *transitions.*.name* type: String Name of the transition. \"\"\" def", "String (Optional) Type of projector: `Preview` (default), `Source`, `Scene`, `StudioProgram`,", "type: String Source name. :Returns: *source* type: String Source name.", "= 'StartStopStreaming' class StartStreaming(Baserequests): \"\"\"Start streaming. Will return an `error`", "status. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetReplayBufferStatus' self.datain['isReplayBufferActive'] =", "self.dataout['vertical'] = vertical self.dataout['render'] = render class GetTextFreetype2Properties(Baserequests): \"\"\"Get the", "ResumeRecording(Baserequests): \"\"\"Resume/unpause the current recording (if paused). Returns an error", "rec_folder): Baserequests.__init__(self) self.name = 'SetRecordingFolder' self.dataout['rec-folder'] = rec_folder class GetRecordingFolder(Baserequests):", "self.datain['vertical'] class SetTextGDIPlusProperties(Baserequests): \"\"\"Set the current properties of a Text", "this way. :Arguments: *outputName* type: String Output name \"\"\" def", "= 'SetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName'] = transitionName self.dataout['transitionSettings'] =", "position of the source from the top. *position.alignment* type: int", "__init__(self, source, is_local_file=None, local_file=None, url=None, css=None, width=None, height=None, fps=None, shutdown=None,", "self.datain['version'] = None self.datain['obs-websocket-version'] = None self.datain['obs-studio-version'] = None self.datain['available-requests']", "with the `release` parameter set to `false`.* \"\"\" def __init__(self):", "(optional) Settings for the stream. *stream.settings.server* type: String (optional) The", "__init__(self, source, color1=None, color2=None, custom_width=None, drop_shadow=None, font=None, from_file=None, log_mode=None, outline=None,", "type: int Font text size. *font.style* type: String Font Style", "self.dataout['extents_cy'] = extents_cy self.dataout['file'] = file self.dataout['read_from_file'] = read_from_file self.dataout['font']", "for play, `true` for pause. \"\"\" def __init__(self, sourceName, playPause):", "Baserequests.__init__(self) self.name = 'ResetSceneItem' self.dataout['item'] = item self.dataout['scene-name'] = scene_name", "name *filterEnabled* type: Boolean New filter state \"\"\" def __init__(self,", "(optional) Height. *fps* type: int (optional) Framerate. *shutdown* type: boolean", "*log_mode* type: boolean Chat log. *outline* type: boolean Outline. *text*", "(optional) Read text from the specified file. *log_mode* type: boolean", "if the scene item's source. For example `vlc_source` or `image_source`", "self.datain['current-scene'] def getScenes(self): return self.datain['scenes'] class CreateScene(Baserequests): \"\"\"Create a new", "Filter settings \"\"\" def __init__(self, sourceName, filterName): Baserequests.__init__(self) self.name =", "kind, Eg. `vlc_source`. *sceneName* type: String Scene to add the", "name. *read_from_file* type: boolean Read text from the specified file.", "Will return an `error` if the Replay Buffer is not", "settings \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetSourceFilters' self.datain['filters']", "larger values. *useDecibel* type: boolean (optional) Interperet `volume` data as", "GetSourceFilters(Baserequests): \"\"\"List filters applied to a source :Arguments: *sourceName* type:", "currently selected transition in the frontend's dropdown menu. :Returns: *name*", "type: Array<Scene> Ordered list of objects with name and/or id", "to 1.1 for retrocompatibility. *obs_websocket_version* type: String obs-websocket plugin version.", "float (optional) Gradient direction. *gradient_opacity* type: int (optional) Gradient opacity", "a Browser Source. :Arguments: *source* type: String Name of the", "false. Retrocompatibility with OBSRemote. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "source): Baserequests.__init__(self) self.name = 'ToggleMute' self.dataout['source'] = source class GetAudioActive(Baserequests):", "authentication is enabled, the username for the streaming server. Ignored", "type: String (optional) Text Alignment (\"left\", \"center\", \"right\"). *bk_color* type:", "def getOutline_color(self): return self.datain['outline_color'] def getOutline_size(self): return self.datain['outline_size'] def getOutline_opacity(self):", "None self.datain['sourceWidth'] = None self.datain['sourceHeight'] = None self.datain['width'] = None", "of a filter :Arguments: *sourceName* type: String Source name *filterName*", "int Extents cy. *file* type: String File path name. *read_from_file*", "type: int Duration of the current transition (in milliseconds). \"\"\"", "transition if supported. :Arguments: *duration* type: int Desired duration of", "The new amount of pixels cropped off the right of", "class SetSourceName(Baserequests): \"\"\" Note: If the new name already exists", "to pass data to the RTMP service about the streaming.", "creation or not. Default `true` :Returns: *itemId* type: int Numerical", "box. *bounds.x* type: double Width of the bounding box. *bounds.y*", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStreamSettings' self.datain['type'] = None", "\"bottom\". \"\"\" def __init__(self, sourceName, filterName, movementType): Baserequests.__init__(self) self.name =", "boolean Persist the settings to disk. \"\"\" def __init__(self, type,", "self.datain['baseWidth'] = None self.datain['baseHeight'] = None self.datain['outputWidth'] = None self.datain['outputHeight']", "Outline size. *outline_opacity* type: int (optional) Outline opacity (0-100). *text*", "the same as triggering the \"Save Replay Buffer\" hotkey. Will", ":Returns: *transitionSettings* type: Object Current transition settings \"\"\" def __init__(self,", "Baserequests.__init__(self) self.name = 'PlayPauseMedia' self.dataout['sourceName'] = sourceName self.dataout['playPause'] = playPause", ":Arguments: *source* type: String Name of the source. *is_local_file* type:", "Baserequests.__init__(self) self.name = 'StartReplayBuffer' class StopReplayBuffer(Baserequests): \"\"\"Stop recording into the", "String (optional) Full file path (file extension included) where the", "*streaming* type: boolean Current streaming status. *recording* type: boolean Current", "sceneName self.dataout['sourceSettings'] = sourceSettings self.dataout['setVisible'] = setVisible def getItemId(self): return", "if currently streaming). *rec_timecode* type: String (optional) Time elapsed since", "a specified scene. :Arguments: *scene_name* type: String (optional) Name of", "self.name = 'GetStats' self.datain['stats'] = None def getStats(self): return self.datain['stats']", "self.name = 'TakeSourceScreenshot' self.datain['sourceName'] = None self.datain['img'] = None self.datain['imageFile']", "Current recording status. *stream_timecode* type: String (optional) Time elapsed since", "scenes. Defaults to the active transition. *with_transition.name* type: String Name", "the currently active scene. *source* type: String Scene Item name.", "self.datain['font'] def getGradient(self): return self.datain['gradient'] def getGradient_color(self): return self.datain['gradient_color'] def", "the type of stream matches the given type (usually 'rtmp_custom'", "= type self.dataout['monitor'] = monitor self.dataout['geometry'] = geometry self.dataout['name'] =", "for the font. Ex: `\"font\": { \"face\": \"Arial\", \"flags\": 0,", "'PlayPauseMedia' self.dataout['sourceName'] = sourceName self.dataout['playPause'] = playPause class RestartMedia(Baserequests): \"\"\"Restart", "RemoveSceneTransitionOverride(Baserequests): \"\"\"Remove any transition override on a scene. :Arguments: *sceneName*", "Source name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'StopMedia'", "None self.datain['gradient_opacity'] = None self.datain['outline'] = None self.datain['outline_color'] = None", "applied immediately and will be effective on the next recording.", "1.0 when not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "#!/usr/bin/env python # -*- coding: utf-8 -*- # THIS FILE", "is a string) or specification (if it is an object).", "*keyModifiers* type: Object (Optional) Optional key modifiers object. False entries", "source height multiplied by the vertical scaling factor) *parentGroupName* type:", "self.dataout['sceneName'] = sceneName self.dataout['sourceSettings'] = sourceSettings self.dataout['setVisible'] = setVisible def", "self.name = 'StartStreaming' self.dataout['stream'] = stream class StopStreaming(Baserequests): \"\"\"Stop streaming.", "bk_opacity=None, chatlog=None, chatlog_lines=None, color=None, extents=None, extents_cx=None, extents_cy=None, file=None, read_from_file=None, font=None,", "and 100 to write the image with. -1 is automatic,", "__init__(self, source, volume, useDecibel=None): Baserequests.__init__(self) self.name = 'SetVolume' self.dataout['source'] =", "(or current) scene *sceneItems* type: Array<Object> Array of scene items", "self.datain['width'] = None self.datain['height'] = None self.datain['parentGroupName'] = None self.datain['groupChildren']", "Ordered list of objects with name and/or id specified. Id", "mul, and under 26.0 for dB. OBS will interpret dB", "__init__(self, sceneName, sourceName, setVisible): Baserequests.__init__(self) self.name = 'AddSceneItem' self.datain['itemId'] =", "active preview scene. Will return an `error` if Studio Mode", "projector window (only if monitor is -1). Encoded in Base64", "String Transition name :Returns: *transitionSettings* type: Object Current transition settings", "\"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetBrowserSourceProperties' self.datain['source'] =", "scene item's source. For example `vlc_source` or `image_source` *sceneItems.*.sourceName* type:", "off (depending on the current recording state). \"\"\" def __init__(self):", "if streaming is not active. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "boolean (optional) Drop shadow. *font* type: Object (optional) Holds data", "self.name = 'GetBrowserSourceProperties' self.datain['source'] = None self.datain['is_local_file'] = None self.datain['local_file']", "'DuplicateSceneItem' self.datain['scene'] = None self.datain['item'] = None self.dataout['item'] = item", "the specified source *sourceSettings* type: Object Source settings (varies between", "None self.dataout['sourceName'] = sourceName self.dataout['sourceType'] = sourceType def getSourceName(self): return", "*item* type: Object Scene Item to duplicate from the source", "\"\"\" def __init__(self, with_transition=None): Baserequests.__init__(self) self.name = 'TransitionToProgram' self.dataout['with-transition'] =", "Source name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'RestartMedia'", "return self.datain['sc-name'] class ListSceneCollections(Baserequests): \"\"\"List available scene collections :Returns: *scene_collections*", "scene_name class GetCurrentScene(Baserequests): \"\"\"Get the current scene's name and source", "enabled. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStudioModeStatus' self.datain['studio-mode'] =", "None self.datain['mic-1'] = None self.datain['mic-2'] = None self.datain['mic-3'] = None", "class EnableStudioMode(Baserequests): \"\"\"Enables Studio Mode. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "None self.dataout['sourceName'] = sourceName self.dataout['embedPictureFormat'] = embedPictureFormat self.dataout['saveToFilePath'] = saveToFilePath", "profile. :Returns: *profile_name* type: String Name of the currently active", "the bottom of the source before scaling. *crop.left* type: int", "Baserequests.__init__(self) self.name = 'GetStats' self.datain['stats'] = None def getStats(self): return", "buffer). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopReplayBuffer' class StartReplayBuffer(Baserequests):", "url=None, css=None, width=None, height=None, fps=None, shutdown=None, render=None): Baserequests.__init__(self) self.name =", "the filter belongs *filterName* type: String Name of the filter", "version. *obs_studio_version* type: String OBS Studio program version. *available_requests* type:", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'SaveStreamSettings' class SendCaptions(Baserequests): \"\"\"Send", "self.datain['url'] def getCss(self): return self.datain['css'] def getWidth(self): return self.datain['width'] def", "class GetSceneList(Baserequests): \"\"\"Get a list of scenes in the currently", "more attributes of the current streaming server settings. Any options", "if supported. :Arguments: *duration* type: int Desired duration of the", "return self.datain['extents_cx'] def getExtents_cy(self): return self.datain['extents_cy'] def getFile(self): return self.datain['file']", "(optional) The new height of the bounding box. \"\"\" def", "Baserequests.__init__(self) self.name = 'ToggleStudioMode' class GetTransitionList(Baserequests): \"\"\"List of all transitions", "= sc_name class GetCurrentSceneCollection(Baserequests): \"\"\"Get the name of the current", "to `true`. \"\"\" def __init__(self, stream=None): Baserequests.__init__(self) self.name = 'StartStreaming'", "type capabilities *types.*.caps.isAsync* type: Boolean True if source of this", "lines. *color* type: int Text color. *extents* type: boolean Extents", "type: String (optional) The username for the streaming service. *settings.password*", "settings. These will be merged to the current filter settings.", "auth class SetHeartbeat(Baserequests): \"\"\"Enable/disable sending of the Heartbeat event :Arguments:", "= None self.datain['sceneItems'] = None self.dataout['sceneName'] = sceneName def getSceneName(self):", "Array<Object> List of available profiles. *profiles.*.profile_name* type: String Filter name", "to the streaming server. *settings.username* type: String The username to", "Key *keyModifiers.control* type: boolean Trigger Control (Ctrl) Key *keyModifiers.command* type:", "type (a.k.a `ffmpeg_source` or `vlc_source`) *mediaSources.*.mediaState* type: String The current", "first 5 or so seconds that the media is playing,", "`true`. *settings.password* type: String The password to use when accessing", "self.dataout['rotation'] = rotation self.dataout['scale'] = scale self.dataout['crop'] = crop self.dataout['visible']", "= is_local_file self.dataout['local_file'] = local_file self.dataout['url'] = url self.dataout['css'] =", "off the bottom of the source before scaling. *crop.left* type:", "Mode is not enabled. :Returns: *name* type: String The name", "a specific settings schema. :Returns: *sourceName* type: String Source name", "when they are controlled in this way. :Arguments: *outputName* type:", "is in use. *local_file* type: String file path. *url* type:", "encoding](https://doc.qt.io/qt-5/qwidget.html#saveGeometry). Corresponds to OBS's saved projectors. *name* type: String (Optional)", "self.datain['text'] def getText_file(self): return self.datain['text_file'] def getWord_wrap(self): return self.datain['word_wrap'] class", "bottom of the source before scaling. *crop.left* type: int (optional)", "defined when registering the hotkey (e.g. \"ReplayBuffer.Save\") \"\"\" def __init__(self,", "type: int Numerical ID of the created scene item \"\"\"", "= sourceName def getMediaDuration(self): return self.datain['mediaDuration'] class GetMediaTime(Baserequests): \"\"\"Get the", "sourceName, newName): Baserequests.__init__(self) self.name = 'SetSourceName' self.dataout['sourceName'] = sourceName self.dataout['newName']", "\"\"\" def __init__(self, items, scene=None): Baserequests.__init__(self) self.name = 'ReorderSceneItems' self.dataout['items']", "source. :Arguments: *source* type: String Name of the source. *align*", "Freetype 2 source. :Arguments: *source* type: String Source name. *color1*", "custom_width self.dataout['drop_shadow'] = drop_shadow self.dataout['font'] = font self.dataout['from_file'] = from_file", "will be merged to the current filter settings. \"\"\" def", "Font text styling flag. `Bold=1, Italic=2, Bold Italic=3, Underline=5, Strikeout=8`", "by the client *data* type: Object User-defined data \"\"\" def", "Outline. *text* type: String Text content to be displayed. *text_file*", "height. :Returns: *sourceName* type: String Source name *img* type: String", "the source should be shutdown when not visible. \"\"\" def", "duration specified in the UI if there is no current", "int Scene Item ID. \"\"\" def __init__(self, item, scene=None): Baserequests.__init__(self)", "around in the source's filter chain. Either \"up\", \"down\", \"top\"", "name :Returns: *outputInfo* type: Output Output info \"\"\" def __init__(self,", "Background color. *bk_opacity* type: int (optional) Background opacity (0-100). *chatlog*", "transform of the specified source item. :Arguments: *scene_name* type: String", "Object (Optional) Optional key modifiers object. False entries can be", "is not fixed. Defaults to the current duration specified in", "the specified file. *log_mode* type: boolean Chat log. *outline* type:", "String New item name \"\"\" def __init__(self, item, fromScene=None, toScene=None):", "class SetBrowserSourceProperties(Baserequests): \"\"\"Set current properties for a Browser Source. :Arguments:", "of the filter in the chain \"\"\" def __init__(self, sourceName,", "(optional) Extents cy. *file* type: String (optional) File path name.", "boolean Drop shadow. *font* type: Object Holds data for the", "the current scene collection. :Returns: *sc_name* type: String Name of", "String (optional) If specified ensures the type of stream matches", "File path. *word_wrap* type: boolean Word wrap. \"\"\" def __init__(self,", "SetTransitionDuration(Baserequests): \"\"\"Set the duration of the currently selected transition if", "self.dataout['font'] = font self.dataout['from_file'] = from_file self.dataout['log_mode'] = log_mode self.dataout['outline']", "`error` if Studio Mode is not enabled. :Returns: *name* type:", "None def getCurrentScene(self): return self.datain['current-scene'] def getScenes(self): return self.datain['scenes'] class", "At least `embedPictureFormat` or `saveToFilePath` must be specified. Clients can", "self.dataout['sceneName'] = sceneName self.dataout['sourceName'] = sourceName self.dataout['setVisible'] = setVisible def", "String Font Style (unknown function). *from_file* type: boolean Read text", "*gradient_opacity* type: int Gradient opacity (0-100). *outline* type: boolean Outline.", "full settings of the stream (the same as GetStreamSettings). :Arguments:", "Mic/Aux sources. :Returns: *desktop_1* type: String (optional) Name of the", "= 'SetTextFreetype2Properties' self.dataout['source'] = source self.dataout['color1'] = color1 self.dataout['color2'] =", "'Authenticate' self.dataout['auth'] = auth class SetHeartbeat(Baserequests): \"\"\"Enable/disable sending of the", "even when triggering saves only through obs-websocket. \"\"\" def __init__(self):", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetSourceTypesList' self.datain['types'] = None", "Name of the scene the source item belongs to. Defaults", "Object Scene item to delete (required) *item.name* type: String Scene", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ReleaseTBar' class SetTBarPosition(Baserequests): \"\"\"", "user releasing their mouse button after moving it). *YOU MUST", "*render* type: boolean (optional) Visibility of the scene item. \"\"\"", "reason, for the first 5 or so seconds that the", "scenes in the currently active profile. :Returns: *current_scene* type: String", "*enable* type: boolean Starts/Stops emitting heartbeat messages \"\"\" def __init__(self,", "Baserequests.__init__(self) self.name = 'PreviousMedia' self.dataout['sourceName'] = sourceName class GetMediaDuration(Baserequests): \"\"\"Get", "The monitor type in use. Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\"", "Object (optional) Change the active transition before switching scenes. Defaults", "self.dataout['source'] = source self.dataout['align'] = align self.dataout['bk_color'] = bk_color self.dataout['bk_opacity']", "\"\"\"Creates a scene item in a scene. In other words,", "`id`, including both is acceptable). *item.id* type: int Scene Item", "version of the plugin and the API. :Returns: *version* type:", "Filter settings \"\"\" def __init__(self, sourceName, filterName, filterType, filterSettings): Baserequests.__init__(self)", "String Name of the scene to create. \"\"\" def __init__(self,", "Current transition settings \"\"\" def __init__(self, transitionName): Baserequests.__init__(self) self.name =", "bounding box. *sourceWidth* type: int Base width (without scaling) of", "*profile_name* type: String Name of the currently active profile. \"\"\"", "timestamp of media in milliseconds. Supports ffmpeg and vlc media", "= 'ReorderSourceFilter' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['newIndex'] =", "this item is a group) \"\"\" def __init__(self, item, scene_name=None):", "getVideoFormat(self): return self.datain['videoFormat'] def getColorSpace(self): return self.datain['colorSpace'] def getColorRange(self): return", "*width* type: int (optional) Screenshot width. Defaults to the source's", "of the filter to reorder *movementType* type: String How to", "\"\"\"Get current recording status. :Returns: *isRecording* type: boolean Current recording", "applied to a source :Arguments: *sourceName* type: String Source name", "return self.datain['name'] def getDuration(self): return self.datain['duration'] class SetCurrentTransition(Baserequests): \"\"\"Set the", "\"\"\"Get the filename formatting string :Returns: *filename_formatting* type: String Current", "type: String Name of the scene to switch to. *transitionName*", "provided in the `supported-image-export-formats` response field of `GetVersion`). If not", "Desktop Audio capture source. *mic_1* type: String (optional) Name of", "the current stream state). \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "Whether to make the sceneitem visible on creation or not.", "not specified, tries to guess based on file extension. *compressionQuality*", "add it as a sceneitem to a scene. :Arguments: *sourceName*", "True if sources of this type provide audio *types.*.caps.canInteract* type:", "self.dataout['valign'] = valign self.dataout['vertical'] = vertical self.dataout['render'] = render class", "None self.datain['color1'] = None self.datain['color2'] = None self.datain['custom_width'] = None", "in degrees around the point of alignment. *scale.x* type: double", "request format uses mul, NOT SLIDER PERCENTAGE. :Arguments: *source* type:", "__init__(self, sourceName, filterName): Baserequests.__init__(self) self.name = 'RemoveFilterFromSource' self.dataout['sourceName'] = sourceName", "cropped off the left of the source before scaling. *crop.right*", "self.dataout['keyModifiers'] = keyModifiers class PlayPauseMedia(Baserequests): \"\"\"Pause or play a media", "progress, the change won't be applied immediately and will be", "'false' hides source. *locked* type: bool (optional) The new locked", "*align* type: String (optional) Text Alignment (\"left\", \"center\", \"right\"). *bk_color*", "__init__(self, sourceName, newName): Baserequests.__init__(self) self.name = 'SetSourceName' self.dataout['sourceName'] = sourceName", "self.name = 'ScrubMedia' self.dataout['sourceName'] = sourceName self.dataout['timeOffset'] = timeOffset class", "around the point of alignment. *scale.x* type: double The x-scale", "of the scene to preview. \"\"\" def __init__(self, scene_name): Baserequests.__init__(self)", "SetRecordingFolder(Baserequests): \"\"\" Please note: if `SetRecordingFolder` is called while a", "transition (in milliseconds). \"\"\" def __init__(self, duration): Baserequests.__init__(self) self.name =", "Mic/Aux input source. *mic_3* type: String (optional) NAme of the", "with this sources of this type is possible *types.*.caps.isComposite* type:", "SLIDER PERCENTAGE. :Arguments: *source* type: String Source name. *volume* type:", "Baserequests.__init__(self) self.name = 'GetStudioModeStatus' self.datain['studio-mode'] = None def getStudioMode(self): return", "Name of the source or scene to be displayed (ignored", "*text* type: String (optional) Text content to be displayed. *valign*", "return self.datain['fps'] def getVideoFormat(self): return self.datain['videoFormat'] def getColorSpace(self): return self.datain['colorSpace']", "def __init__(self, item, x, y, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemPosition'", "= hidden \"\"\" def __init__(self, source, render, scene_name=None): Baserequests.__init__(self) self.name", "stream. *stream.settings.use_auth* type: boolean (optional) Indicates whether authentication should be", "int Desired duration of the transition (in milliseconds). \"\"\" def", "__init__(self, outputName): Baserequests.__init__(self) self.name = 'StartOutput' self.dataout['outputName'] = outputName class", "None def getStreaming(self): return self.datain['streaming'] def getRecording(self): return self.datain['recording'] def", "new visibility of the source. 'true' shows source, 'false' hides", "can be ommitted *keyModifiers.shift* type: boolean Trigger Shift Key *keyModifiers.alt*", "return self.datain['offset'] class GetSourceSettings(Baserequests): \"\"\"Get settings of the specified source", "visibility of the source. 'true' shows source, 'false' hides source.", "ID. \"\"\" def __init__(self, item, scene=None): Baserequests.__init__(self) self.name = 'DeleteSceneItem'", ":Arguments: *realm* type: String Identifier to be choosen by the", "around). :Returns: *sourceName* type: String Source name *sourceType* type: String", "class SetAudioMonitorType(Baserequests): \"\"\"Set the audio monitoring type of the specified", "The publish URL. *stream.settings.key* type: String (optional) The publish key", "is to be saved. Can be in a format different", "since scenes are also sources, you can also provide a", "Scene item to delete (required) *item.name* type: String Scene Item", "def __init__(self, sourceName=None, embedPictureFormat=None, saveToFilePath=None, fileFormat=None, compressionQuality=None, width=None, height=None): Baserequests.__init__(self)", "Chat log lines. *color* type: int (optional) Text color. *extents*", "enabled, the password for the streaming server. Ignored if `use_auth`", "Baserequests.__init__(self) self.name = 'SetSceneTransitionOverride' self.dataout['sceneName'] = sceneName self.dataout['transitionName'] = transitionName", "if Studio Mode is not enabled. :Arguments: *scene_name* type: String", "the stream. *settings.server* type: String (optional) The publish URL. *settings.key*", "= None self.dataout['sourceName'] = sourceName def getAudioActive(self): return self.datain['audioActive'] class", "self.dataout['top'] = top self.dataout['bottom'] = bottom self.dataout['left'] = left self.dataout['right']", "\"\"\"Get OBS stats (almost the same info as provided in", "content to be displayed. *text_file* type: String (optional) File path.", "getSource(self): return self.datain['source'] def getIs_local_file(self): return self.datain['is_local_file'] def getLocal_file(self): return", "in a format different from `pictureFormat`. Can be a relative", "if supported by the transition. \"\"\" def __init__(self): Baserequests.__init__(self) self.name", "def __init__(self): Baserequests.__init__(self) self.name = 'ToggleStudioMode' class GetTransitionList(Baserequests): \"\"\"List of", "self.datain['scale'] def getCrop(self): return self.datain['crop'] def getVisible(self): return self.datain['visible'] def", "class SaveReplayBuffer(Baserequests): \"\"\"Flush and save the contents of the Replay", "def __init__(self, item, x_scale, y_scale, rotation, scene_name=None): Baserequests.__init__(self) self.name =", "SetSourceFilterVisibility(Baserequests): \"\"\"Change the visibility/enabled state of a filter :Arguments: *sourceName*", "of the source item *sceneItems.*.sourceKind* type: String ID if the", "not) *filters.*.type* type: String Filter type *filters.*.name* type: String Filter", "= scene_name def getName(self): return self.datain['name'] def getItemId(self): return self.datain['itemId']", "the timestamp of a media source. Supports ffmpeg and vlc", "bottom, left, right, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemCrop' self.dataout['item'] =", "String Source name. :Returns: *source* type: String Source name. *is_local_file*", "keyId, keyModifiers): Baserequests.__init__(self) self.name = 'TriggerHotkeyBySequence' self.dataout['keyId'] = keyId self.dataout['keyModifiers']", "recording status. *stream_timecode* type: String (optional) Time elapsed since streaming", "(optional) Scene Item ID (if the `item` field is an", "*with_transition.duration* type: int (optional) Transition duration (in milliseconds). \"\"\" def", "x position of the source from the left. *position.y* type:", "sourceName, sourceKind, sceneName, sourceSettings=None, setVisible=None): Baserequests.__init__(self) self.name = 'CreateSource' self.datain['itemId']", "Read text from the specified file. *log_mode* type: boolean Chat", "the request) *imageFile* type: String Absolute path to the saved", "audio is monitored and shouldn't be \"\"\" def __init__(self): Baserequests.__init__(self)", "How to move the filter around in the source's filter", "self.name = 'SetMediaTime' self.dataout['sourceName'] = sourceName self.dataout['timestamp'] = timestamp class", "the currently active profile. :Arguments: *profile_name* type: String Name of", "duplicate from the source scene (required) *item.name* type: String Scene", "vlc media source (as of OBS v25.0.8) :Arguments: *sourceName* type:", "The audio sync offset (in nanoseconds). \"\"\" def __init__(self, source):", "= None self.datain['outline'] = None self.datain['text'] = None self.datain['text_file'] =", "source before scaling. *crop.right* type: int The number of pixels", "not specified. :Returns: *sceneName* type: String Name of the requested", "active status of the source. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self)", "of 1=Left or 2=Right, and 4=Top or 8=Bottom, or omit", "StopMedia(Baserequests): \"\"\"Stop a media source. Supports ffmpeg and vlc media", ":Returns: *audioActive* type: boolean Audio active status of the source.", "scene collection. :Returns: *sc_name* type: String Name of the currently", "Item ID (if the `item` field is an object) \"\"\"", "properties will remain unchanged. Coordinates are relative to the item's", "'SetHeartbeat' self.dataout['enable'] = enable class SetFilenameFormatting(Baserequests): \"\"\"Set the filename formatting", "(usually 'rtmp_custom' or 'rtmp_common'). If the currently configured stream type", "__init__(self): Baserequests.__init__(self) self.name = 'ToggleStudioMode' class GetTransitionList(Baserequests): \"\"\"List of all", "new source to. *sourceSettings* type: Object (optional) Source settings data.", "*width* type: int Width. *height* type: int Height. *fps* type:", "publish URL. *settings.key* type: String (optional) The publish key. *settings.use_auth*", "\"Method1,Method2,Method3\"). *supported_image_export_formats* type: String List of supported formats for features", "Chat log. *chatlog_lines* type: int Chat log lines. *color* type:", "type: String Source name. *sourceType* type: String (optional) Type of", "hotkey routine, identified by hotkey unique name :Arguments: *hotkeyName* type:", "more information). :Returns: *authRequired* type: boolean Indicates whether authentication is", "self.datain['mic-2'] def getMic3(self): return self.datain['mic-3'] class GetSourceFilters(Baserequests): \"\"\"List filters applied", "'StartStopRecording' class StartRecording(Baserequests): \"\"\"Start recording. Will return an `error` if", "new amount of pixels cropped off the left of the", "size. *outline_opacity* type: int (optional) Outline opacity (0-100). *text* type:", "def getName(self): return self.datain['name'] def getSettings(self): return self.datain['settings'] class AddFilterToSource(Baserequests):", "= sourceName def getMediaState(self): return self.datain['mediaState'] class GetMediaSourcesList(Baserequests): \"\"\"List the", "String Type of the specified source *sourceSettings* type: Object Source", "Buffer on/off (depending on the current state of the replay", "Baserequests.__init__(self) self.name = 'SetSyncOffset' self.dataout['source'] = source self.dataout['offset'] = offset", "None self.datain['duration'] = None def getName(self): return self.datain['name'] def getDuration(self):", "String Name of the source to which the filter belongs", "def getRecTimecode(self): return self.datain['rec-timecode'] def getPreviewOnly(self): return self.datain['preview-only'] class StartStopStreaming(Baserequests):", "Pixel position of the left of the source item. *right*", "*outline_color* type: int Outline color. *outline_size* type: int Outline size.", "return self.datain['gradient_dir'] def getGradient_opacity(self): return self.datain['gradient_opacity'] def getOutline(self): return self.datain['outline']", "the filter in the chain \"\"\" def __init__(self, sourceName, filterName,", "def getType(self): return self.datain['type'] def getName(self): return self.datain['name'] def getSettings(self):", "def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetAudioMonitorType' self.datain['monitorType'] = None", "__init__(self, sourceName=None, embedPictureFormat=None, saveToFilePath=None, fileFormat=None, compressionQuality=None, width=None, height=None): Baserequests.__init__(self) self.name", "(optional) Name of the scene to create the item in.", "\"\"\"Get a list of available profiles. :Returns: *profiles* type: Array<Object>", "= items self.dataout['scene'] = scene class SetSceneTransitionOverride(Baserequests): \"\"\"Set a scene", "= None self.datain['valign'] = None self.datain['vertical'] = None self.dataout['source'] =", "Source name. *color1* type: int (optional) Gradient top color. *color2*", "Name of the scene to create the item in. Defaults", "of the currently active scene. *sources* type: Array<SceneItem> Ordered list", "boolean Whether the recording is paused or not. *recordTimecode* type:", "self.datain['mic-2'] = None self.datain['mic-3'] = None def getDesktop1(self): return self.datain['desktop-1']", "mute status. \"\"\" def __init__(self, source, mute): Baserequests.__init__(self) self.name =", "source from the left. *position.y* type: double The y position", "= bounds class ResetSceneItem(Baserequests): \"\"\"Reset a scene item. :Arguments: *scene_name*", "configuration. Possible values: 'rtmp_custom' or 'rtmp_common'. *settings* type: Object Stream", "source): Baserequests.__init__(self) self.name = 'GetSyncOffset' self.datain['name'] = None self.datain['offset'] =", "if sources of this type provide video *types.*.caps.hasAudio* type: Boolean", "*stream.settings.password* type: String (optional) If authentication is enabled, the password", "add a source into a scene. :Arguments: *sceneName* type: String", "int Output height *scaleType* type: String Scaling method used if", "transitionName def getTransitionSettings(self): return self.datain['transitionSettings'] class SetTransitionSettings(Baserequests): \"\"\"Change the current", "= chatlog self.dataout['chatlog_lines'] = chatlog_lines self.dataout['color'] = color self.dataout['extents'] =", "`embedPictureFormat` or `saveToFilePath` must be specified. Clients can specify `width`", "the current recording folder. :Returns: *rec_folder* type: String Path of", "*font.face* type: String (optional) Font face. *font.flags* type: int (optional)", "the currently active transition. *transitions* type: Array<Object> List of transitions.", "of the desired scene collection. \"\"\" def __init__(self, sc_name): Baserequests.__init__(self)", "\"flags\": 0, \"size\": 150, \"style\": \"\" }` *font.face* type: String", "height multiplied by the vertical scaling factor) *parentGroupName* type: String", "= None def getStats(self): return self.datain['stats'] class BroadcastCustomMessage(Baserequests): \"\"\"Broadcast custom", "self.datain['outputHeight'] def getScaleType(self): return self.datain['scaleType'] def getFps(self): return self.datain['fps'] def", "type: String Source kind, Eg. `vlc_source`. *sceneName* type: String Scene", "self.dataout['sceneName'] = sceneName class GetSceneTransitionOverride(Baserequests): \"\"\"Get the current scene transition", "outputName def getOutputInfo(self): return self.datain['outputInfo'] class StartOutput(Baserequests): \"\"\" Note: Controlling", "boolean (optional) Chat log. *chatlog_lines* type: int (optional) Chat log", "of the filter to reorder *newIndex* type: Integer Desired position", "*rec_folder* type: String Path of the recording folder. \"\"\" def", "a set of settings incompatible with the actual source's type.", "self.datain['source'] def getIs_local_file(self): return self.datain['is_local_file'] def getLocal_file(self): return self.datain['local_file'] def", "source class GetAudioActive(Baserequests): \"\"\"Get the audio's active status of a", "self.datain['desktop-2'] def getMic1(self): return self.datain['mic-1'] def getMic2(self): return self.datain['mic-2'] def", "self.datain['challenge'] = None self.datain['salt'] = None def getAuthRequired(self): return self.datain['authRequired']", "key. *settings.use_auth* type: boolean (optional) Indicates whether authentication should be", "*from_file* type: boolean Read text from the specified file. *log_mode*", "right self.dataout['scene-name'] = scene_name class DeleteSceneItem(Baserequests): \"\"\"Deletes a scene item.", "recording. Returns an error if recording is not active or", "class GetVolume(Baserequests): \"\"\"Get the volume of the specified source. Default", "self.dataout['filterType'] = filterType self.dataout['filterSettings'] = filterSettings class RemoveFilterFromSource(Baserequests): \"\"\"Remove a", "Baserequests.__init__(self) self.name = 'SetSourceFilterVisibility' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName", "name. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'PreviousMedia' self.dataout['sourceName']", "Response to the auth challenge (see \"Authentication\" for more information).", "type: String Source name. *offset* type: int The audio sync", "= type self.dataout['settings'] = settings self.dataout['save'] = save class GetStreamSettings(Baserequests):", "self.datain['visible'] = None self.datain['muted'] = None self.datain['locked'] = None self.datain['bounds']", "int New item ID *item.name* type: String New item name", "source items. :Returns: *name* type: String Name of the currently", "sourceName self.dataout['filterName'] = filterName self.dataout['movementType'] = movementType class SetSourceFilterSettings(Baserequests): \"\"\"Update", "__init__(self): Baserequests.__init__(self) self.name = 'StartStopReplayBuffer' class StartReplayBuffer(Baserequests): \"\"\"Start recording into", "'ScrubMedia' self.dataout['sourceName'] = sourceName self.dataout['timeOffset'] = timeOffset class GetMediaState(Baserequests): \"\"\"Get", "authenticate the client to the server. :Arguments: *auth* type: String", "ID of the created scene item \"\"\" def __init__(self, sceneName,", "Indicates that a local file is in use. *local_file* type:", "Studio Mode is not enabled. :Arguments: *scene_name* type: String The", "filter *filterType* type: String Filter type *filterSettings* type: Object Filter", "of the following: \"input\", \"filter\", \"transition\" or \"other\" *types.*.defaultSettings* type:", "key combination might trigger multiple hotkey routines depending on user", "self.datain['sourceName'] = None self.datain['sourceType'] = None self.datain['sourceSettings'] = None self.dataout['sourceName']", "self.dataout['width'] = width self.dataout['height'] = height self.dataout['fps'] = fps self.dataout['shutdown']", "getSourceWidth(self): return self.datain['sourceWidth'] def getSourceHeight(self): return self.datain['sourceHeight'] def getWidth(self): return", "Baserequests.__init__(self) self.name = 'GetMediaState' self.datain['mediaState'] = None self.dataout['sourceName'] = sourceName", "Please note: these won't be saved to OBS' configuration. *stream.type*", "the created SceneItem as visible or not. Defaults to true", "Settings for the stream. *stream.settings.server* type: String (optional) The publish", "self.name = 'GetVideoInfo' self.datain['baseWidth'] = None self.datain['baseHeight'] = None self.datain['outputWidth']", "specified source *sourceSettings* type: Object Source settings (varies between source", "example `vlc_source` or `image_source` *sceneItems.*.sourceName* type: String Name of the", "of projector: `Preview` (default), `Source`, `Scene`, `StudioProgram`, or `Multiview` (case", "\"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'ToggleMute' self.dataout['source'] =", "source should be shutdown when not visible. \"\"\" def __init__(self,", "(optional) The new y scale of the item. *crop.top* type:", "def __init__(self, transitionName): Baserequests.__init__(self) self.name = 'GetTransitionSettings' self.datain['transitionSettings'] = None", "settings \"\"\" def __init__(self, transitionName, transitionSettings): Baserequests.__init__(self) self.name = 'SetTransitionSettings'", "StartStreaming(Baserequests): \"\"\"Start streaming. Will return an `error` if streaming is", "return self.datain['extents_cy'] def getFile(self): return self.datain['file'] def getRead_from_file(self): return self.datain['read_from_file']", "type *types.*.caps* type: Object Source type capabilities *types.*.caps.isAsync* type: Boolean", "should be used when connecting to the streaming server. *settings.username*", "= sceneName class GetSceneTransitionOverride(Baserequests): \"\"\"Get the current scene transition override.", "user moving a T-Bar control in your User Interface), set", "duration (in milliseconds) if supported by the transition. \"\"\" def", "\"\"\"Set the filename formatting string :Arguments: *filename_formatting* type: String Filename", "in the playlist. Supports only vlc media source (as of", "String Source kind, Eg. `vlc_source`. *sceneName* type: String Scene to", "type: String Source name *filterName* type: String Source filter name", "Baserequests.__init__(self) self.name = 'TakeSourceScreenshot' self.datain['sourceName'] = None self.datain['img'] = None", "the full settings of the stream (the same as GetStreamSettings).", "source self.dataout['is_local_file'] = is_local_file self.dataout['local_file'] = local_file self.dataout['url'] = url", "Force stop (default: false) \"\"\" def __init__(self, outputName, force=None): Baserequests.__init__(self)", "(optional) The new amount of pixels cropped off the left", "so seconds that the media is playing, the total duration", "sourceName self.dataout['filterName'] = filterName self.dataout['newIndex'] = newIndex class MoveSourceFilter(Baserequests): \"\"\"Move", "and the API. :Returns: *version* type: double OBSRemote compatible API", "a sceneitem to a scene. :Arguments: *sourceName* type: String Source", "to reorder (defaults to current). *items* type: Array<Scene> Ordered list", "= 'SetPreviewScene' self.dataout['scene-name'] = scene_name class TransitionToProgram(Baserequests): \"\"\"Transitions the currently", "return self.datain['width'] def getHeight(self): return self.datain['height'] def getParentGroupName(self): return self.datain['parentGroupName']", "items, scene=None): Baserequests.__init__(self) self.name = 'ReorderSceneItems' self.dataout['items'] = items self.dataout['scene']", "getLog_mode(self): return self.datain['log_mode'] def getOutline(self): return self.datain['outline'] def getText(self): return", "self.name = 'GetTransitionSettings' self.datain['transitionSettings'] = None self.dataout['transitionName'] = transitionName def", "self.datain['stats'] = None def getStats(self): return self.datain['stats'] class BroadcastCustomMessage(Baserequests): \"\"\"Broadcast", "type: String Source name. *align* type: String Text Alignment (\"left\",", "*font.size* type: int Font text size. *font.style* type: String Font", "hide a specified source item in a specified scene. :Arguments:", "def __init__(self, sourceName, timeOffset): Baserequests.__init__(self) self.name = 'ScrubMedia' self.dataout['sourceName'] =", "String Name of the currently active scene. *sources* type: Array<SceneItem>", "(file extension included) where the captured image is to be", "= fromScene self.dataout['toScene'] = toScene def getScene(self): return self.datain['scene'] def", "String (optional) If authentication is enabled, the password for the", "Baserequests.__init__(self) self.name = 'OpenProjector' self.dataout['type'] = type self.dataout['monitor'] = monitor", "incompatible with the actual source's type. *sourceSettings* type: Object Source", "self.datain['bk_opacity'] def getChatlog(self): return self.datain['chatlog'] def getChatlog_lines(self): return self.datain['chatlog_lines'] def", "the password for the streaming server. Ignored if `use_auth` is", "scaling. *crop.left* type: int (optional) The new amount of pixels", "the scene item. \"\"\" def __init__(self, source, align=None, bk_color=None, bk_opacity=None,", "buffer. :Returns: *isReplayBufferActive* type: boolean Current recording status. \"\"\" def", "= None self.datain['name'] = None self.datain['settings'] = None self.dataout['sourceName'] =", "previous media item in the playlist. Supports only vlc media", "playPause class RestartMedia(Baserequests): \"\"\"Restart a media source. Supports ffmpeg and", "from the specified file. *log_mode* type: boolean (optional) Chat log.", "String Name of the scene to switch to. :Returns: *transitionName*", "server. Only present if `use_auth` is `true`. *settings.password* type: String", "Alt Key *keyModifiers.control* type: boolean Trigger Control (Ctrl) Key *keyModifiers.command*", "Baserequests.__init__(self) self.name = 'GetSceneTransitionOverride' self.datain['transitionName'] = None self.datain['transitionDuration'] = None", "'rtmp_common'. *settings* type: Object Stream settings object. *settings.server* type: String", "ffmpeg and vlc media sources (as of OBS v25.0.8) :Arguments:", "Source filter name :Returns: *enabled* type: Boolean Filter status (enabled", "is smallest file/most compression, 100 is largest file/least compression. Varies", "Array of sources *sources.*.name* type: String Unique source name *sources.*.typeId*", "scene class AddSceneItem(Baserequests): \"\"\"Creates a scene item in a scene.", "color. *custom_width* type: int (optional) Custom width (0 to disable).", "0.0 and 1.0. *release* type: boolean (optional) Whether or not", "None self.datain['text_file'] = None self.datain['word_wrap'] = None self.dataout['source'] = source", "some probing around). \"\"\" def __init__(self, sourceName, sourceType=None): Baserequests.__init__(self) self.name", "return self.datain['sourceHeight'] def getWidth(self): return self.datain['width'] def getHeight(self): return self.datain['height']", "None def getPosition(self): return self.datain['position'] class GetTransitionSettings(Baserequests): \"\"\"Get the current", "file/most compression, 100 is largest file/least compression. Varies with image", "if currently recording). *preview_only* type: boolean Always false. Retrocompatibility with", ":Returns: *name* type: String Scene Item name. *itemId* type: int", "= y self.dataout['scene-name'] = scene_name class SetSceneItemTransform(Baserequests): \"\"\"Set the transform", "String (optional) Font face. *font.flags* type: int (optional) Font text", "a comma-separated list string (e.g. : \"Method1,Method2,Method3\"). *supported_image_export_formats* type: String", ":Returns: *type* type: String The type of streaming service configuration.", "*sceneName* type: String Name of the requested (or current) scene", "(optional) Transition duration (in milliseconds) if supported by the transition.", "(see \"Authentication\" for more information). :Returns: *authRequired* type: boolean Indicates", "Id of a specific scene item. Unique on a scene", "for the specified source *filters.*.enabled* type: Boolean Filter status (enabled", "specified. Id preferred due to uniqueness per scene *items.*.id* type:", "of the hotkey, as defined when registering the hotkey (e.g.", "= None self.datain['color2'] = None self.datain['custom_width'] = None self.datain['drop_shadow'] =", "Object Filter settings \"\"\" def __init__(self, sourceName, filterName, filterType, filterSettings):", "Filename formatting string to set. \"\"\" def __init__(self, filename_formatting): Baserequests.__init__(self)", "def getObsStudioVersion(self): return self.datain['obs-studio-version'] def getAvailableRequests(self): return self.datain['available-requests'] def getSupportedImageExportFormats(self):", "height. Defaults to the source's base height. :Returns: *sourceName* type:", "\"right\"). *bk_color* type: int Background color. *bk_opacity* type: int Background", "The time in milliseconds since the start of the media.", "type: String (optional) Name of the second Mic/Aux input source.", "\"\"\"Move a filter in the chain (relative positioning) :Arguments: *sourceName*", "self.datain['transition-duration'] class GetTransitionPosition(Baserequests): \"\"\"Get the position of the current transition.", "self.datain['outline_size'] = None self.datain['outline_opacity'] = None self.datain['text'] = None self.datain['valign']", "Source name. *newName* type: String New source name. \"\"\" def", "type: String Source name. :Returns: *mediaState* type: String The media", "type: String Source name. *muted* type: boolean Mute status of", "__init__(self, sourceName, filterName, filterSettings): Baserequests.__init__(self) self.name = 'SetSourceFilterSettings' self.dataout['sourceName'] =", "source. :Arguments: *source* type: String Source name. :Returns: *name* type:", "In other words, this is how you add a source", "Baserequests.__init__(self) self.name = 'SetBrowserSourceProperties' self.dataout['source'] = source self.dataout['is_local_file'] = is_local_file", "playPause): Baserequests.__init__(self) self.name = 'PlayPauseMedia' self.dataout['sourceName'] = sourceName self.dataout['playPause'] =", "monitor self.dataout['geometry'] = geometry self.dataout['name'] = name class TriggerHotkeyByName(Baserequests): \"\"\"Executes", "None self.datain['preview-only'] = None def getStreaming(self): return self.datain['streaming'] def getRecording(self):", "(a.k.a kind) *sources.*.type* type: String Source type. Value is one", "stream. Used to pass data to the RTMP service about", "SaveReplayBuffer(Baserequests): \"\"\"Flush and save the contents of the Replay Buffer", "the source. *rotation* type: double (optional) The new clockwise rotation", "*text_file* type: String (optional) File path. *word_wrap* type: boolean (optional)", "def __init__(self, source): Baserequests.__init__(self) self.name = 'GetMute' self.datain['name'] = None", "def __init__(self, sourceName, timestamp): Baserequests.__init__(self) self.name = 'SetMediaTime' self.dataout['sourceName'] =", "source. *position.y* type: double (optional) The new y position of", "using a supplied offset. Supports ffmpeg and vlc media sources", "collection name \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ListSceneCollections' self.datain['scene-collections']", "\"\"\"Release the T-Bar (like a user releasing their mouse button", "name): Baserequests.__init__(self) self.name = 'OpenProjector' self.dataout['type'] = type self.dataout['monitor'] =", "item, top, bottom, left, right, scene_name=None): Baserequests.__init__(self) self.name = 'SetSceneItemCrop'", "current scene's source items. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "`true`. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStreamSettings' self.datain['type'] =", ":Arguments: *sceneName* type: String Name of the scene to create", "int (Optional) Duration in milliseconds of the transition if transition", "*sourceName* type: String Name of the source to which the", "source is muted. *locked* type: bool If the source's transform", "None self.datain['gradient'] = None self.datain['gradient_color'] = None self.datain['gradient_dir'] = None", "return self.datain['locked'] def getBounds(self): return self.datain['bounds'] def getSourceWidth(self): return self.datain['sourceWidth']", "keyId self.dataout['keyModifiers'] = keyModifiers class PlayPauseMedia(Baserequests): \"\"\"Pause or play a", "before scaling. *crop.bottom* type: int The number of pixels cropped", "int Font text size. *font.style* type: String Font Style (unknown", "getMediaDuration(self): return self.datain['mediaDuration'] class GetMediaTime(Baserequests): \"\"\"Get the current timestamp of", "*scene_name* type: String (optional) Name of the scene the source", "*item.name* type: String Scene Item name (prefer `id`, including both", "scene. *scenes* type: Array<Scene> Ordered list of the current profile's", "two parameters is specified. :Arguments: *sourceName* type: String (optional) Source", "`error` if recording is already active. \"\"\" def __init__(self): Baserequests.__init__(self)", "currently active transition. *transitions* type: Array<Object> List of transitions. *transitions.*.name*", "to the current scene. *item* type: Object Scene Item to", "__init__(self, sceneName): Baserequests.__init__(self) self.name = 'RemoveSceneTransitionOverride' self.dataout['sceneName'] = sceneName class", "*outline_size* type: int Outline size. *outline_opacity* type: int Outline opacity", "*crop.left* type: int (optional) The new amount of pixels cropped", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StopReplayBuffer' class SaveReplayBuffer(Baserequests): \"\"\"Flush", "self.datain['name'] = None self.datain['duration'] = None def getName(self): return self.datain['name']", "self.name = 'SetVolume' self.dataout['source'] = source self.dataout['volume'] = volume self.dataout['useDecibel']", "type: int (optional) Text color. *extents* type: boolean (optional) Extents", "type: boolean (optional) Vertical text enabled. *render* type: boolean (optional)", "currently active profile. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetCurrentProfile'", "unique name :Arguments: *hotkeyName* type: String Unique name of the", "String (optional) Name of the scene to create the item", "*items* type: Array<Scene> Ordered list of objects with name and/or", "\"\"\" def __init__(self, sourceName, filterName): Baserequests.__init__(self) self.name = 'RemoveFilterFromSource' self.dataout['sourceName']", "GetCurrentTransition(Baserequests): \"\"\"Get the name of the currently selected transition in", "position of the right of the source item. \"\"\" def", "Baserequests.__init__(self) self.name = 'GetCurrentSceneCollection' self.datain['sc-name'] = None def getScName(self): return", "list of scenes in the currently active profile. :Returns: *current_scene*", "GetRecordingFolder(Baserequests): \"\"\"Get the path of the current recording folder. :Returns:", "class StartReplayBuffer(Baserequests): \"\"\"Start recording into the Replay Buffer. Will return", "state of a media source. Supports ffmpeg and vlc media", "Object New item info *item.id* type: int New item ID", "or off (depending on the current stream state). \"\"\" def", "= None self.datain['item'] = None self.dataout['item'] = item self.dataout['fromScene'] =", "getScenes(self): return self.datain['scenes'] class CreateScene(Baserequests): \"\"\"Create a new scene scene.", "getObsStudioVersion(self): return self.datain['obs-studio-version'] def getAvailableRequests(self): return self.datain['available-requests'] def getSupportedImageExportFormats(self): return", "None self.datain['supported-image-export-formats'] = None def getVersion(self): return self.datain['version'] def getObsWebsocketVersion(self):", "the playlist. Supports only vlc media source (as of OBS", "type: int Gradient bottom color. *custom_width* type: int Custom width", "self.datain['bounds'] def getSourceWidth(self): return self.datain['sourceWidth'] def getSourceHeight(self): return self.datain['sourceHeight'] def", "None def getDesktop1(self): return self.datain['desktop-1'] def getDesktop2(self): return self.datain['desktop-2'] def", "scale self.dataout['crop'] = crop self.dataout['visible'] = visible self.dataout['locked'] = locked", "of `GetVersion`). If not specified, tries to guess based on", "the next recording. :Arguments: *rec_folder* type: String Path of the", "= filterType self.dataout['filterSettings'] = filterSettings class RemoveFilterFromSource(Baserequests): \"\"\"Remove a filter", "scene name. If not provided, the currently active scene is", "current filter settings. \"\"\" def __init__(self, sourceName, filterName, filterSettings): Baserequests.__init__(self)", "projector on a monitor. Requires OBS v24.0.4 or newer. :Arguments:", "type: double Source item rotation (in degrees). \"\"\" def __init__(self,", "is not enabled. :Returns: *name* type: String The name of", "*name* type: String Filter name *settings* type: Object Filter settings", "= timeOffset class GetMediaState(Baserequests): \"\"\"Get the current playing state of", "\"\"\" def __init__(self, sourceName, sourceType=None): Baserequests.__init__(self) self.name = 'GetSourceSettings' self.datain['sourceName']", ":Returns: *timestamp* type: int The time in milliseconds since the", "`opening`, `buffering`, `paused`, `stopped`, `ended`, `error`, `unknown` \"\"\" def __init__(self,", "the scene item. \"\"\" def __init__(self, source, is_local_file=None, local_file=None, url=None,", "self.datain['height'] def getParentGroupName(self): return self.datain['parentGroupName'] def getGroupChildren(self): return self.datain['groupChildren'] class", "version. *available_requests* type: String List of available request types, formatted", "getItemId(self): return self.datain['itemId'] def getPosition(self): return self.datain['position'] def getRotation(self): return", "no override is set. *transitionDuration* type: int Transition duration. `-1`", "like Desktop Audio and Mic/Aux sources. :Returns: *desktop_1* type: String", "Extents wrap. *extents_cx* type: int Extents cx. *extents_cy* type: int", "(optional) Absolute path to the recording file (only present if", "OBS may not function properly when they are controlled in", "The new clockwise rotation of the item in degrees. *scale.x*", "stream type does not match the given stream type, all", "double The y position of the source from the top.", "self.datain['css'] = None self.datain['width'] = None self.datain['height'] = None self.datain['fps']", "Buffer. Will return an `error` if the Replay Buffer is", "if the \"Save Replay Buffer\" hotkey is not set in", "transition is not fixed. Defaults to the current duration specified", "both is acceptable). *item.id* type: int Scene Item ID. :Returns:", "= None self.datain['sources'] = None def getName(self): return self.datain['name'] def", "(optional) Change the active transition before switching scenes. Defaults to", "contents of the Replay Buffer to disk. This is basically", "self.name = 'SetTextGDIPlusProperties' self.dataout['source'] = source self.dataout['align'] = align self.dataout['bk_color']", "String Source name. *align* type: String Text Alignment (\"left\", \"center\",", "unchanged. Returns the updated settings in response. If 'type' is", "= shown ; false = hidden \"\"\" def __init__(self, source,", "*offset* type: int The audio sync offset (in nanoseconds). \"\"\"", "new y position of the source. *position.alignment* type: int (optional)", "getType(self): return self.datain['type'] def getName(self): return self.datain['name'] def getSettings(self): return", "a user releasing their mouse button after moving the T-Bar).", "object) *item.id* type: int (optional) Scene Item ID (if the", "Baserequests.__init__(self) self.name = 'SetSceneItemPosition' self.dataout['item'] = item self.dataout['x'] = x", "name of the source type *types.*.type* type: String Type. Value", "def getImageFile(self): return self.datain['imageFile'] class ListOutputs(Baserequests): \"\"\"List existing outputs :Returns:", "type: int Scene Item ID. \"\"\" def __init__(self, item, scene=None):", "*bk_opacity* type: int Background opacity (0-100). *chatlog* type: boolean Chat", "recording status. :Returns: *streaming* type: boolean Current streaming status. *recording*", "= text_file self.dataout['word_wrap'] = word_wrap class GetBrowserSourceProperties(Baserequests): \"\"\"Get current properties", "for type-checking if you expect a specific settings schema. :Returns:", "settings of the specified source :Arguments: *sourceName* type: String Source", "cy. *file* type: String (optional) File path name. *read_from_file* type:", "self.name = 'StartStopRecording' class StartRecording(Baserequests): \"\"\"Start recording. Will return an", "self.datain['text'] def getValign(self): return self.datain['valign'] def getVertical(self): return self.datain['vertical'] class", "*sources* type: Array<Object> Array of sources *sources.*.name* type: String Unique", "= None self.datain['sourceSettings'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceSettings'] =", ":Arguments: *filename_formatting* type: String Filename formatting string to set. \"\"\"", "source. Supports ffmpeg and vlc media sources (as of OBS", "\"\"\"Broadcast custom message to all connected WebSocket clients :Arguments: *realm*", "*is_local_file* type: boolean Indicates that a local file is in", "the specified source. Useful for type-checking if you expect a", "= None self.datain['mic-1'] = None self.datain['mic-2'] = None self.datain['mic-3'] =", "the `item` field is an object) :Returns: *name* type: String", "current profile's scenes (See [GetCurrentScene](#getcurrentscene) for more information). \"\"\" def", "`group`, or `scene` \"\"\" def __init__(self, sceneName=None): Baserequests.__init__(self) self.name =", "getDuration(self): return self.datain['duration'] class SetCurrentTransition(Baserequests): \"\"\"Set the active transition. :Arguments:", "volume sliders only reach a maximum of 1.0mul/0.0dB, however OBS", "int (optional) The new alignment of the source. *rotation* type:", "the scene specific properties of a source. Unspecified properties will", "self.dataout['type'] = type self.dataout['settings'] = settings self.dataout['save'] = save class", "type is possible *types.*.caps.isComposite* type: Boolean True if sources of", "= 'OpenProjector' self.dataout['type'] = type self.dataout['monitor'] = monitor self.dataout['geometry'] =", "is one of the following: \"input\", \"filter\", \"transition\" or \"other\"", "scene if not specified. :Returns: *sceneName* type: String Name of", "int Outline opacity (0-100). *text* type: String Text content to", "def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetMediaDuration' self.datain['mediaDuration'] = None", "*bounds.alignment* type: int (optional) The new alignment of the bounding", "self.datain['type'] = None self.datain['name'] = None self.datain['settings'] = None self.dataout['sourceName']", "(the same as GetStreamSettings). :Arguments: *type* type: String The type", "the source's base width. *height* type: int (optional) Screenshot height.", "active or not paused. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "Format of the Data URI encoded picture. Can be \"png\",", "self.dataout['outline'] = outline self.dataout['text'] = text self.dataout['text_file'] = text_file self.dataout['word_wrap']", "scene to preview. \"\"\" def __init__(self, scene_name): Baserequests.__init__(self) self.name =", "__init__(self): Baserequests.__init__(self) self.name = 'ResumeRecording' class SetRecordingFolder(Baserequests): \"\"\" Please note:", "the left of the source before scaling. *crop.right* type: int", "= monitorType class TakeSourceScreenshot(Baserequests): \"\"\" At least `embedPictureFormat` or `saveToFilePath`", "source. *locked* type: bool (optional) The new locked status of", "an object) *position.x* type: double (optional) The new x position", "the source. Can be \"OBS_BOUNDS_STRETCH\", \"OBS_BOUNDS_SCALE_INNER\", \"OBS_BOUNDS_SCALE_OUTER\", \"OBS_BOUNDS_SCALE_TO_WIDTH\", \"OBS_BOUNDS_SCALE_TO_HEIGHT\", \"OBS_BOUNDS_MAX_ONLY\"", "height def getSourceName(self): return self.datain['sourceName'] def getImg(self): return self.datain['img'] def", "of the right of the source item. \"\"\" def __init__(self,", "a scene name. If not provided, the currently active scene", "__init__(self): Baserequests.__init__(self) self.name = 'GetVideoInfo' self.datain['baseWidth'] = None self.datain['baseHeight'] =", ":Arguments: *sourceName* type: String Source name. *timeOffset* type: int Millisecond", "remain unchanged. Coordinates are relative to the item's parent (the", "None self.datain['mic-3'] = None def getDesktop1(self): return self.datain['desktop-1'] def getDesktop2(self):", "scene to get the list of scene items from. Defaults", "Name of the scene item's source *sceneItems.*.sourceType* type: String Type", "RTMP service about the streaming. May be any String, Numeric,", "the top. *position.alignment* type: int The point on the source", "of the specified source. :Arguments: *sourceName* type: String Source name.", "hotkey, as defined when registering the hotkey (e.g. \"ReplayBuffer.Save\") \"\"\"", "CSS to inject. *width* type: int (optional) Width. *height* type:", "*bottom* type: int Pixel position of the bottom of the", "sourceName, filterName, filterSettings): Baserequests.__init__(self) self.name = 'SetSourceFilterSettings' self.dataout['sourceName'] = sourceName", "String Path of the recording folder. \"\"\" def __init__(self): Baserequests.__init__(self)", "return self.datain['source'] def getAlign(self): return self.datain['align'] def getBk_color(self): return self.datain['bk_color']", "\"\"\"Pause or play a media source. Supports ffmpeg and vlc", "the 'key' of the RTMP stream. Used to pass data", "selected transition. *duration* type: int (optional) Transition duration (in milliseconds)", "the current scene if not specified. :Returns: *sceneName* type: String", "Between `0.0` and `20.0` if using mul, under `26.0` if", "class SetSourceFilterVisibility(Baserequests): \"\"\"Change the visibility/enabled state of a filter :Arguments:", "media item in the playlist. Supports only vlc media source", "settings data. *setVisible* type: boolean (optional) Set the created SceneItem", "source's base height. :Returns: *sourceName* type: String Source name *img*", "moves (e.g. : in an animation, or in response to", "color. *custom_width* type: int Custom width (0 to disable). *drop_shadow*", "self.dataout['sceneName'] = sceneName class ReorderSceneItems(Baserequests): \"\"\"Changes the order of scene", "self.datain['locked'] = None self.datain['bounds'] = None self.datain['sourceWidth'] = None self.datain['sourceHeight']", "# -*- coding: utf-8 -*- # THIS FILE WAS GENERATED", "uses mul, NOT SLIDER PERCENTAGE. :Arguments: *source* type: String Source", "= gradient_opacity self.dataout['outline'] = outline self.dataout['outline_color'] = outline_color self.dataout['outline_size'] =", "username to use when accessing the streaming server. Only present", "type: Boolean True if sources of this type should not", "Object User-defined data \"\"\" def __init__(self, realm, data): Baserequests.__init__(self) self.name", "scene. :Arguments: *scene_name* type: String (optional) Name of the scene", "\"\"\"Indicates if Studio Mode is currently enabled. :Returns: *studio_mode* type:", "getLocal_file(self): return self.datain['local_file'] def getUrl(self): return self.datain['url'] def getCss(self): return", "def __init__(self, profile_name): Baserequests.__init__(self) self.name = 'SetCurrentProfile' self.dataout['profile-name'] = profile_name", "type: boolean Always false. Retrocompatibility with OBSRemote. \"\"\" def __init__(self):", "*crop.bottom* type: int The number of pixels cropped off the", "GetSceneItemList(Baserequests): \"\"\"Get a list of all scene items in a", "self.datain['color'] def getExtents(self): return self.datain['extents'] def getExtents_cx(self): return self.datain['extents_cx'] def", "self.datain['current-scene'] = None self.datain['scenes'] = None def getCurrentScene(self): return self.datain['current-scene']", "= 'TriggerHotkeyByName' self.dataout['hotkeyName'] = hotkeyName class TriggerHotkeyBySequence(Baserequests): \"\"\"Executes hotkey routine,", "name of the current scene collection. :Returns: *sc_name* type: String", "Text GDI Plus source. :Arguments: *source* type: String Name of", "scaling) of the source *width* type: double Scene item width", "id of the source item *sceneItems.*.sourceKind* type: String ID if", "double Height of the bounding box. *sourceWidth* type: int Base", "width (0 to disable). *drop_shadow* type: boolean (optional) Drop shadow.", "boolean (optional) Indicates whether the source should be shutdown when", "= source self.dataout['offset'] = offset class GetSyncOffset(Baserequests): \"\"\"Get the audio", "the name of the current scene collection. :Returns: *sc_name* type:", "type: bool If the source is muted. *locked* type: bool", "position of the left of the source item. *right* type:", "source def getName(self): return self.datain['name'] def getOffset(self): return self.datain['offset'] class", "should be shutdown when not visible. *render* type: boolean (optional)", "`vlc_source`. *sceneName* type: String Scene to add the new source", "to. Defaults to the current scene. *item* type: String |", "shadow. *font* type: Object Holds data for the font. Ex:", "type: String Name of the transition. \"\"\" def __init__(self): Baserequests.__init__(self)", "'ToggleMute' self.dataout['source'] = source class GetAudioActive(Baserequests): \"\"\"Get the audio's active", "# # (Generated on 2020-12-20 18:26:33.661372) # from .base_classes import", "*sources.*.typeId* type: String Non-unique source internal type (a.k.a kind) *sources.*.type*", "new filter *filterType* type: String Filter type *filterSettings* type: Object", "GetRecordingStatus(Baserequests): \"\"\"Get current recording status. :Returns: *isRecording* type: boolean Current", "in Base64 using [Qt's geometry encoding](https://doc.qt.io/qt-5/qwidget.html#saveGeometry). Corresponds to OBS's saved", "self.datain['sourceType'] = None self.datain['sourceSettings'] = None self.dataout['sourceName'] = sourceName self.dataout['sourceSettings']", "return self.datain['isRecordingPaused'] def getRecordTimecode(self): return self.datain['recordTimecode'] def getRecordingFilename(self): return self.datain['recordingFilename']", "a transition :Arguments: *transitionName* type: String Transition name :Returns: *transitionSettings*", "int (optional) Transition duration (in milliseconds) if supported by the", "outline_color=None, outline_size=None, outline_opacity=None, text=None, valign=None, vertical=None, render=None): Baserequests.__init__(self) self.name =", "Monitor to open the projector on. If -1 or omitted,", "profile. :Returns: *current_scene* type: String Name of the currently active", "multiplied by the horizontal scaling factor) *height* type: double Scene", "type: Object Filter settings \"\"\" def __init__(self, sourceName, filterName): Baserequests.__init__(self)", "recording is not active or not paused. \"\"\" def __init__(self):", "ID *types.*.displayName* type: String Display name of the source type", "= 'SetCurrentSceneCollection' self.dataout['sc-name'] = sc_name class GetCurrentSceneCollection(Baserequests): \"\"\"Get the name", "self.name = 'GetMediaState' self.datain['mediaState'] = None self.dataout['sourceName'] = sourceName def", "*sceneItems.*.sourceKind* type: String ID if the scene item's source. For", "self.name = 'AddSceneItem' self.datain['itemId'] = None self.dataout['sceneName'] = sceneName self.dataout['sourceName']", "\"\"\"Open a projector window or create a projector on a", "current stream state). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopStreaming'", "registering the hotkey (e.g. \"ReplayBuffer.Save\") \"\"\" def __init__(self, hotkeyName): Baserequests.__init__(self)", "transitionSettings def getTransitionSettings(self): return self.datain['transitionSettings'] class ReleaseTBar(Baserequests): \"\"\"Release the T-Bar", "= scene_name self.dataout['position'] = position self.dataout['rotation'] = rotation self.dataout['scale'] =", "type: int (optional) Id of a specific scene item. Unique", "some probing around). :Returns: *sourceName* type: String Source name *sourceType*", "local_file=None, url=None, css=None, width=None, height=None, fps=None, shutdown=None, render=None): Baserequests.__init__(self) self.name", "\"\"\"Stop streaming. Will return an `error` if streaming is not", "String (optional) Url. *css* type: String (optional) CSS to inject.", "None self.datain['vertical'] = None self.dataout['source'] = source def getSource(self): return", "getCurrentTransition(self): return self.datain['current-transition'] def getTransitions(self): return self.datain['transitions'] class GetCurrentTransition(Baserequests): \"\"\"Get", "mouse button after moving the T-Bar). Call `ReleaseTBar` manually if", "on that axis. *rotation* type: double The clockwise rotation of", "getName(self): return self.datain['name'] def getDuration(self): return self.datain['duration'] class SetCurrentTransition(Baserequests): \"\"\"Set", "provide a scene name. If not provided, the currently active", "available scene collections :Returns: *scene_collections* type: Array<String> Scene collections list", "Scene Item ID. *position.x* type: double The x position of", "item is manipulated from. The sum of 1=Left or 2=Right,", "String Source name. *timeOffset* type: int Millisecond offset (positive or", "Baserequests.__init__(self) self.name = 'GetSpecialSources' self.datain['desktop-1'] = None self.datain['desktop-2'] = None", "timeOffset): Baserequests.__init__(self) self.name = 'ScrubMedia' self.dataout['sourceName'] = sourceName self.dataout['timeOffset'] =", "__init__(self, sourceName, sourceKind, sceneName, sourceSettings=None, setVisible=None): Baserequests.__init__(self) self.name = 'CreateSource'", "getOutline_opacity(self): return self.datain['outline_opacity'] def getText(self): return self.datain['text'] def getValign(self): return", "= item self.dataout['x-scale'] = x_scale self.dataout['y-scale'] = y_scale self.dataout['rotation'] =", "extents=None, extents_cx=None, extents_cy=None, file=None, read_from_file=None, font=None, gradient=None, gradient_color=None, gradient_dir=None, gradient_opacity=None,", "Studio Mode is not enabled. :Arguments: *with_transition* type: Object (optional)", "None self.datain['position'] = None self.datain['rotation'] = None self.datain['scale'] = None", "self.datain['type'] = None self.datain['settings'] = None def getType(self): return self.datain['type']", "return self.datain['rotation'] def getScale(self): return self.datain['scale'] def getCrop(self): return self.datain['crop']", "\"\"\" def __init__(self, source): Baserequests.__init__(self) self.name = 'GetTextGDIPlusProperties' self.datain['source'] =", "Key *keyModifiers.alt* type: boolean Trigger Alt Key *keyModifiers.control* type: boolean", "bool (optional) The new visibility of the source. 'true' shows", "filter :Arguments: *sourceName* type: String Source name *filterName* type: String", "the scene item's source *sceneItems.*.sourceType* type: String Type of the", "def getSourceWidth(self): return self.datain['sourceWidth'] def getSourceHeight(self): return self.datain['sourceHeight'] def getWidth(self):", "the current media position. \"\"\" def __init__(self, sourceName, timeOffset): Baserequests.__init__(self)", "source and add it as a sceneitem to a scene.", "and its list of sources. Will return an `error` if", "filterName self.dataout['newIndex'] = newIndex class MoveSourceFilter(Baserequests): \"\"\"Move a filter in", "this sources of this type is possible *types.*.caps.isComposite* type: Boolean", "top color. *color2* type: int Gradient bottom color. *custom_width* type:", "self.dataout['saveToFilePath'] = saveToFilePath self.dataout['fileFormat'] = fileFormat self.dataout['compressionQuality'] = compressionQuality self.dataout['width']", "(optional) If specified ensures the type of stream matches the", "studio mode). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'ToggleStudioMode' class", "some reason, for the first 5 or so seconds that", "source def getSource(self): return self.datain['source'] def getColor1(self): return self.datain['color1'] def", "self.name = 'GetAuthRequired' self.datain['authRequired'] = None self.datain['challenge'] = None self.datain['salt']", "list of all scene items in a scene. :Arguments: *sceneName*", "def getBk_opacity(self): return self.datain['bk_opacity'] def getChatlog(self): return self.datain['chatlog'] def getChatlog_lines(self):", "new amount of pixels cropped off the bottom of the", "*sourceSettings* type: Object (optional) Source settings data. *setVisible* type: boolean", "pixels cropped off the left of the source before scaling.", "self.name = 'SetAudioMonitorType' self.dataout['sourceName'] = sourceName self.dataout['monitorType'] = monitorType class", "\"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'CreateScene' self.dataout['sceneName'] =", "None self.dataout['source'] = source def getSource(self): return self.datain['source'] def getColor1(self):", "Unique source internal type (a.k.a `ffmpeg_source` or `vlc_source`) *mediaSources.*.mediaState* type:", "\"\"\" def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'RemoveSceneTransitionOverride' self.dataout['sceneName'] =", "Source name :Returns: *filters* type: Array<Object> List of filters for", "is over. :Arguments: *position* type: double T-Bar position. This value", "Baserequests class GetVersion(Baserequests): \"\"\"Returns the latest version of the plugin", "return self.datain['type'] def getName(self): return self.datain['name'] def getSettings(self): return self.datain['settings']", "*item.id* type: int New item ID *item.name* type: String New", "status. :Returns: *streaming* type: boolean Current streaming status. *recording* type:", "the specified file. *log_mode* type: boolean (optional) Chat log. *outline*", "`Bold=1, Italic=2, Bold Italic=3, Underline=5, Strikeout=8` *font.size* type: int Font", "insensitive). *monitor* type: int (Optional) Monitor to open the projector", "self.name = 'SetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType'] = None self.datain['sourceSettings']", "previewed scene and its list of sources. Will return an", "*sceneItems* type: Array<Object> Array of scene items *sceneItems.*.itemId* type: int", "String (optional) Text content to be displayed. *valign* type: String", "type: String Name of the desired profile. \"\"\" def __init__(self,", "def getBk_color(self): return self.datain['bk_color'] def getBk_opacity(self): return self.datain['bk_opacity'] def getChatlog(self):", "the item in degrees. *scale.x* type: double (optional) The new", "type: String Name of the scene to switch to. :Returns:", "= render class GetTextFreetype2Properties(Baserequests): \"\"\"Get the current properties of a", "muted. \"\"\" def __init__(self, source, useDecibel=None): Baserequests.__init__(self) self.name = 'GetVolume'", "return self.datain['crop'] def getVisible(self): return self.datain['visible'] def getMuted(self): return self.datain['muted']", "Only present if `use_auth` is `true`. \"\"\" def __init__(self): Baserequests.__init__(self)", "\"center\", \"right\"). *bk_color* type: int (optional) Background color. *bk_opacity* type:", "= None def getScName(self): return self.datain['sc-name'] class ListSceneCollections(Baserequests): \"\"\"List available", "def getItemId(self): return self.datain['itemId'] class GetSourcesList(Baserequests): \"\"\"List all sources available", "after moving the T-Bar). Call `ReleaseTBar` manually if you set", "\"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStats' self.datain['stats'] = None", "= movementType class SetSourceFilterSettings(Baserequests): \"\"\"Update settings of a filter :Arguments:", "type: boolean (optional) Chat log. *chatlog_lines* type: int (optional) Chat", "(optional) Scene Item name (if the `item` field is an", "= enable class SetFilenameFormatting(Baserequests): \"\"\"Set the filename formatting string :Arguments:", "Scaling method used if output size differs from base size", "Time elapsed since recording started (only present if currently recording).", "(ignored for other projector types). \"\"\" def __init__(self, type, monitor,", "Baserequests.__init__(self) self.name = 'GetBrowserSourceProperties' self.datain['source'] = None self.datain['is_local_file'] = None", "sourceName): Baserequests.__init__(self) self.name = 'GetMediaTime' self.datain['timestamp'] = None self.dataout['sourceName'] =", "None self.dataout['sourceName'] = sourceName def getMonitorType(self): return self.datain['monitorType'] class SetAudioMonitorType(Baserequests):", "T-Bar position. This value must be between 0.0 and 1.0.", ":Returns: *mediaDuration* type: int The total length of media in", "int Pixel position of the top of the source item.", "the transition if transition is not fixed. Defaults to the", "pixels cropped off the bottom of the source before scaling.", "and vlc media sources (as of OBS v25.0.8) :Arguments: *sourceName*", "function). *from_file* type: boolean Read text from the specified file.", "def __init__(self, sceneName): Baserequests.__init__(self) self.name = 'CreateScene' self.dataout['sceneName'] = sceneName", "The publish URL. *settings.key* type: String The publish key of", ":Returns: *name* type: String Name of the selected transition. *duration*", "data for the font. Ex: `\"font\": { \"face\": \"Arial\", \"flags\":", "= None self.datain['muted'] = None self.dataout['source'] = source self.dataout['useDecibel'] =", "The name of the scene to preview. \"\"\" def __init__(self,", "if it's audio is monitored and shouldn't be \"\"\" def", "previewed scene to the main output. Will return an `error`", "the current state of the replay buffer). \"\"\" def __init__(self):", "return self.datain['bk_opacity'] def getChatlog(self): return self.datain['chatlog'] def getChatlog_lines(self): return self.datain['chatlog_lines']", "state of studio mode). \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "sceneitem to a scene. :Arguments: *sourceName* type: String Source name.", "MoveSourceFilter(Baserequests): \"\"\"Move a filter in the chain (relative positioning) :Arguments:", "GetSceneList(Baserequests): \"\"\"Get a list of scenes in the currently active", "def getText(self): return self.datain['text'] def getValign(self): return self.datain['valign'] def getVertical(self):", "self.datain['baseHeight'] = None self.datain['outputWidth'] = None self.datain['outputHeight'] = None self.datain['scaleType']", "Scene Item ID (if the `item` field is an object)", "__init__(self, sourceName, sourceSettings, sourceType=None): Baserequests.__init__(self) self.name = 'SetSourceSettings' self.datain['sourceName'] =", "dropdown menu. :Returns: *current_transition* type: String Name of the currently", "def getText(self): return self.datain['text'] def getText_file(self): return self.datain['text_file'] def getWord_wrap(self):", "an object) *item.id* type: int (optional) Scene Item ID (if", "(without scaling) of the source *width* type: double Scene item", "= None self.datain['groupChildren'] = None self.dataout['item'] = item self.dataout['scene-name'] =", "publish URL. *settings.key* type: String The publish key of the", "= 'GetTransitionList' self.datain['current-transition'] = None self.datain['transitions'] = None def getCurrentTransition(self):", "of the desired profile. \"\"\" def __init__(self, profile_name): Baserequests.__init__(self) self.name", "String (Optional) Size and position of the projector window (only", "type: String (optional) File path name. *read_from_file* type: boolean (optional)", "name *sourceType* type: String Type of the specified source *sourceSettings*", "media state of all media sources (vlc and media source)", "the scene to switch to. \"\"\" def __init__(self, sceneName): Baserequests.__init__(self)", "self.dataout['source'] = source self.dataout['color1'] = color1 self.dataout['color2'] = color2 self.dataout['custom_width']", "the item from. Defaults to the current scene. *toScene* type:", "(unknown function). *from_file* type: boolean Read text from the specified", "scene_name=None, position=None, rotation=None, scale=None, crop=None, visible=None, locked=None, bounds=None): Baserequests.__init__(self) self.name", "__init__(self): Baserequests.__init__(self) self.name = 'SaveReplayBuffer' class SetCurrentSceneCollection(Baserequests): \"\"\"Change the active", "class SetTextFreetype2Properties(Baserequests): \"\"\"Set the current properties of a Text Freetype", "the plugin and the API. :Returns: *version* type: double OBSRemote", "partial) \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetVideoInfo' self.datain['baseWidth'] =", "int Extents cx. *extents_cy* type: int Extents cy. *file* type:", "with OBSRemote. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStreamingStatus' self.datain['streaming']", "name. :Returns: *mediaState* type: String The media state of the", "from the left. *position.y* type: double The y position of", "self.dataout['read_from_file'] = read_from_file self.dataout['font'] = font self.dataout['gradient'] = gradient self.dataout['gradient_color']", "Type of the specified source *sourceSettings* type: Object Updated source", "Retrocompatibility with OBSRemote. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetStreamingStatus'", "*crop.top* type: int (optional) The new amount of pixels cropped", "__init__(self, sourceName): Baserequests.__init__(self) self.name = 'GetAudioMonitorType' self.datain['monitorType'] = None self.dataout['sourceName']", "name. *color1* type: int (optional) Gradient top color. *color2* type:", "the source before scaling. *visible* type: bool If the source", "def __init__(self, sourceName, newName): Baserequests.__init__(self) self.name = 'SetSourceName' self.dataout['sourceName'] =", "*sourceKind* type: String Source kind, Eg. `vlc_source`. *sceneName* type: String", "as a comma-separated list string (e.g. : \"Method1,Method2,Method3\"). *supported_image_export_formats* type:", "Baserequests.__init__(self) self.name = 'SetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType'] = None", "= 'SetSourceFilterVisibility' self.dataout['sourceName'] = sourceName self.dataout['filterName'] = filterName self.dataout['filterEnabled'] =", "be displayed (ignored for other projector types). \"\"\" def __init__(self,", "*monitorType* type: String The monitor type in use. Options: `none`,", "available in the running OBS instance :Returns: *sources* type: Array<Object>", "delays, this request is not perfect. The processing rate of", "\"\"\" def __init__(self, sourceName): Baserequests.__init__(self) self.name = 'NextMedia' self.dataout['sourceName'] =", "name \"\"\" def __init__(self, item, fromScene=None, toScene=None): Baserequests.__init__(self) self.name =", "*source* type: String Name of the source. *align* type: String", "__init__(self, sourceName, filterName): Baserequests.__init__(self) self.name = 'GetSourceFilterInfo' self.datain['enabled'] = None", "of available profiles. *profiles.*.profile_name* type: String Filter name \"\"\" def", "= None def getRecFolder(self): return self.datain['rec-folder'] class GetReplayBufferStatus(Baserequests): \"\"\"Get the", "The total length of media in milliseconds.. \"\"\" def __init__(self,", "int Base source (without scaling) of the source *width* type:", "compression, 100 is largest file/least compression. Varies with image type.", "type: String New source name. \"\"\" def __init__(self, sourceName, newName):", "Baserequests.__init__(self) self.name = 'ListProfiles' self.datain['profiles'] = None def getProfiles(self): return", "for type-checking to avoid settings a set of settings incompatible", "getDesktop2(self): return self.datain['desktop-2'] def getMic1(self): return self.datain['mic-1'] def getMic2(self): return", "type: String Source filter name *filterEnabled* type: Boolean New filter", "size. *font.style* type: String (optional) Font Style (unknown function). *from_file*", "\"\"\"Send the provided text as embedded CEA-608 caption data. :Arguments:", "*scale.x* type: double The x-scale factor of the source. *scale.y*", "sourceSettings, sourceType=None): Baserequests.__init__(self) self.name = 'SetSourceSettings' self.datain['sourceName'] = None self.datain['sourceType']", "filterName, filterSettings): Baserequests.__init__(self) self.name = 'SetSourceFilterSettings' self.dataout['sourceName'] = sourceName self.dataout['filterName']", "a Text Freetype 2 source. :Arguments: *source* type: String Source", "type provide audio *types.*.caps.canInteract* type: Boolean True if interaction with", "or specification (if it is an object). *item.name* type: String", "key of the stream. *stream.settings.use_auth* type: boolean (optional) Indicates whether", "= 'ListProfiles' self.datain['profiles'] = None def getProfiles(self): return self.datain['profiles'] class", "= sourceName self.dataout['monitorType'] = monitorType class TakeSourceScreenshot(Baserequests): \"\"\" At least", "None def getName(self): return self.datain['name'] def getSources(self): return self.datain['sources'] class", "self.datain['sc-name'] class ListSceneCollections(Baserequests): \"\"\"List available scene collections :Returns: *scene_collections* type:", "a scene. :Arguments: *sceneName* type: String Name of the scene", "type ID *types.*.displayName* type: String Display name of the source", "Name of the currently active scene. *sources* type: Array<SceneItem> Ordered", "be shutdown when not visible. \"\"\" def __init__(self, source): Baserequests.__init__(self)", "= 'SetTransitionDuration' self.dataout['duration'] = duration class GetTransitionDuration(Baserequests): \"\"\"Get the duration", "the projector on. If -1 or omitted, opens a window.", "Non-unique internal source type ID *types.*.displayName* type: String Display name", "sourceName def getMediaDuration(self): return self.datain['mediaDuration'] class GetMediaTime(Baserequests): \"\"\"Get the current", "use. Options: `none`, `monitorOnly`, `monitorAndOutput`. \"\"\" def __init__(self, sourceName): Baserequests.__init__(self)", "scaling. *visible* type: bool (optional) The new visibility of the", "identified by bound combination of keys. A single key combination", "properties of a source. Unspecified properties will remain unchanged. Coordinates", "= scene_name class SetSceneItemCrop(Baserequests): \"\"\"Sets the crop coordinates of the", "types along with their settings properties are available from `GetSourceTypesList`.", "mute): Baserequests.__init__(self) self.name = 'SetMute' self.dataout['source'] = source self.dataout['mute'] =", "return self.datain['height'] def getParentGroupName(self): return self.datain['parentGroupName'] def getGroupChildren(self): return self.datain['groupChildren']", "Replay Buffer. Will return an `error` if the Replay Buffer", "is playing, the total duration can be off by upwards", "return self.datain['color'] def getExtents(self): return self.datain['extents'] def getExtents_cx(self): return self.datain['extents_cx']", "self.datain['transitionName'] def getTransitionDuration(self): return self.datain['transitionDuration'] class GetStreamingStatus(Baserequests): \"\"\"Get current streaming", "offset of a specified source. :Arguments: *source* type: String Source", "the transition. \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'GetTransitionList' self.datain['current-transition']", "Main key identifier (e.g. `OBS_KEY_A` for key \"A\"). Available identifiers", "int Outline color. *outline_size* type: int Outline size. *outline_opacity* type:", "\"\"\" def __init__(self, item, scene_name=None): Baserequests.__init__(self) self.name = 'ResetSceneItem' self.dataout['item']", "def __init__(self): Baserequests.__init__(self) self.name = 'ListProfiles' self.datain['profiles'] = None def", "'StartReplayBuffer' class StopReplayBuffer(Baserequests): \"\"\"Stop recording into the Replay Buffer. Will", "from_file=None, log_mode=None, outline=None, text=None, text_file=None, word_wrap=None): Baserequests.__init__(self) self.name = 'SetTextFreetype2Properties'", "= 'GetPreviewScene' self.datain['name'] = None self.datain['sources'] = None def getName(self):", "= None self.datain['colorRange'] = None def getBaseWidth(self): return self.datain['baseWidth'] def", "= 'GetVideoInfo' self.datain['baseWidth'] = None self.datain['baseHeight'] = None self.datain['outputWidth'] =", "*filename_formatting* type: String Filename formatting string to set. \"\"\" def", "*desktop_1* type: String (optional) Name of the first Desktop Audio", "def getProfileName(self): return self.datain['profile-name'] class ListProfiles(Baserequests): \"\"\"Get a list of", "__init__(self, source): Baserequests.__init__(self) self.name = 'GetTextGDIPlusProperties' self.datain['source'] = None self.datain['align']", "None self.datain['recording'] = None self.datain['stream-timecode'] = None self.datain['rec-timecode'] = None", "(optional) Gradient top color. *color2* type: int (optional) Gradient bottom", "replay buffer). \"\"\" def __init__(self): Baserequests.__init__(self) self.name = 'StartStopReplayBuffer' class", "Gradient bottom color. *custom_width* type: int (optional) Custom width (0", "specified source. :Arguments: *source* type: String Source name. :Returns: *name*", "*chatlog_lines* type: int (optional) Chat log lines. *color* type: int", "return self.datain['outputs'] class GetOutputInfo(Baserequests): \"\"\"Get information about a single output", "service configuration. Possible values: 'rtmp_custom' or 'rtmp_common'. *settings* type: Object", "the length of media in milliseconds. Supports ffmpeg and vlc", "currently active scene. *sources* type: Array<SceneItem> Ordered list of the", "status. :Returns: *isRecording* type: boolean Current recording status. *isRecordingPaused* type:", "index positioning) :Arguments: *sourceName* type: String Name of the source", "state of all media sources (vlc and media source) :Returns:", "Current filename formatting string. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "DisableStudioMode(Baserequests): \"\"\"Disables Studio Mode. \"\"\" def __init__(self): Baserequests.__init__(self) self.name =", "class GetCurrentSceneCollection(Baserequests): \"\"\"Get the name of the current scene collection.", "SetCurrentScene(Baserequests): \"\"\"Switch to the specified scene. :Arguments: *scene_name* type: String", "other projector types). \"\"\" def __init__(self, type, monitor, geometry, name):", "client to the server. :Arguments: *auth* type: String Response to", "text from the specified file. *font* type: Object (optional) Holds", "self.datain['recordTimecode'] def getRecordingFilename(self): return self.datain['recordingFilename'] class StartStopRecording(Baserequests): \"\"\"Toggle recording on", "type: String Name of the scene to switch to. \"\"\"", "self.datain['sc-name'] = None def getScName(self): return self.datain['sc-name'] class ListSceneCollections(Baserequests): \"\"\"List", "def __init__(self): Baserequests.__init__(self) self.name = 'ReleaseTBar' class SetTBarPosition(Baserequests): \"\"\" If", "chatlog_lines self.dataout['color'] = color self.dataout['extents'] = extents self.dataout['extents_cx'] = extents_cx", "return self.datain['outline_color'] def getOutline_size(self): return self.datain['outline_size'] def getOutline_opacity(self): return self.datain['outline_opacity']", "def getSourceSettings(self): return self.datain['sourceSettings'] class GetTextGDIPlusProperties(Baserequests): \"\"\"Get the current properties" ]
[ "django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import", "from django.contrib.auth.admin import UserAdmin from .models import CustomUser admin.site.register(CustomUser, UserAdmin)", "admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser admin.site.register(CustomUser,", "import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser", "from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models" ]
[ "elif data.shape[0] <= i: box_outs[layer_name] = data else: box_outs[layer_name] =", "Corporation Licensed under the Apache License, Version 2.0 (the \"License\");", "- 1 tmp = np.where(ey > h)[0] if tmp.shape[0] !=", "+ 1) - dy tmp_xs_len = (edx + 1) -", "np.logical_and(mask, np.logical_and(img_xs_len > 0, img_ys_len > 0)) mask = np.logical_and(mask,", "img_ys_len > 0)) mask = np.logical_and(mask, np.logical_and(tmp_xs_len == img_xs_len, tmp_ys_len", "region_out not in out[0]: region_out = ( region_out + '/sink_port_0'", "previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] mv = mv[np.sort(peek).astype(int)] x_mins, y_mins,", "* 0.5 bboxA[:, 1] = bboxA[:, 1] + h *", "int(tmpw[k]) + int(include_bound) tmp = np.zeros((tmp_k_h, tmp_k_w, 3)) tmp_ys, tmp_xs", "= boxes[:, 2] - boxes[:, 0] + 1 numbox =", "0)) mask = np.logical_and(mask, np.logical_and(tmp_xs_len == img_xs_len, tmp_ys_len == img_ys_len))", "y = boxes[:, 1:2][:, 0] ex = boxes[:, 2:3][:, 0]", "threshold, iou_type) prediction.remove([i for i in range(prediction.size) if i not", "- 1 tmp = np.where(x < 1)[0] if tmp.shape[0] !=", "return boundingbox def filter_valid(dy, edy, dx, edx, y, ey, x,", "return image def transform_for_callback(batch_size, raw_outputs): output_per_box = [] fq_weights =", "edx = np.maximum(0, edx - 1) ey = np.maximum(0, ey", "bb3]).T return boundingbox def filter_valid(dy, edy, dx, edx, y, ey,", "0:4] = np.array([bb0, bb1, bb2, bb3]).T return boundingbox def filter_valid(dy,", "0] + 1 h = boundingbox[:, 3] - boundingbox[:, 1]", "i in range(batch_size): box_outs = OrderedDict() for layer_name, data in", "OrderedDict import cv2 import numpy as np from ...adapters import", "0] h = bboxA[:, 3] - bboxA[:, 1] max_side =", "np.repeat([max_side], 2, axis=0).T return bboxA def cut_roi(image, prediction, dst_size, include_bound=True):", "under the License. \"\"\" from collections import OrderedDict import cv2", "if i not in peek]) return prediction, peek def bbreg(boundingbox,", "+ w * 0.5 - max_side * 0.5 bboxA[:, 1]", "0, img_ys_len > 0)) mask = np.logical_and(mask, np.logical_and(tmp_xs_len == img_xs_len,", "Apache License, Version 2.0 (the \"License\"); you may not use", "* w bb1 = boundingbox[:, 1] + reg[:, 1] *", "tmpw edy = tmph x = boxes[:, 0:1][:, 0] y", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "dy = np.ones(numbox) edx = tmpw edy = tmph x", "'') score = out[0][prob_out][:, 1] pass_t = np.where(score > 0.7)[0]", "of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law", "bbreg(bboxes, mv.T).T previous_stage_predictions[0].x_mins = x_mins previous_stage_predictions[0].y_mins = y_mins previous_stage_predictions[0].x_maxs =", "dx img_ys_len = (ey + 1) - y img_xs_len =", "h, w): boxes = boxesA.copy() tmph = boxes[:, 3] -", "bboxes.shape[0] tempimg = np.zeros((numbox, dst_size, dst_size, 3)) for k in", "pass_t = np.where(score > 0.7)[0] removed_boxes = [i for i", "def cut_roi(image, prediction, dst_size, include_bound=True): bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs,", "the License. \"\"\" from collections import OrderedDict import cv2 import", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "removed_boxes = [i for i in range(previous_stage_predictions[0].size) if i not", "= np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] region_out =", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "dy tmp_xs_len = (edx + 1) - dx img_ys_len =", "< 1)[0] if tmp.shape[0] != 0: dy[tmp] = 2 -", "w)[0] if tmp.shape[0] != 0: edx[tmp] = -ex[tmp] + w", "img = image.data bboxes = rerec(bboxes) bboxes[:, 0:4] = np.fix(bboxes[:,", "reg): reg = reg.T # calibrate bounding boxes w =", "the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or", "ANY KIND, either express or implied. See the License for", "prob_out = outputs_mapping['probability_out'] if prob_out not in out[0]: prob_out =", "] region_out = outputs_mapping['region_out'] if region_out not in out[0]: region_out", "ey[mask], x[mask], ex[mask], tmpw[mask], tmph[mask], mask def pad(boxesA, h, w):", "= boxes[:, 0:1][:, 0] y = boxes[:, 1:2][:, 0] ex", "tmpw, tmph) def rerec(bboxA): w = bboxA[:, 2] - bboxA[:,", "img[img_ys, img_xs] tempimg[k, :, :, :] = cv2.resize(tmp, (dst_size, dst_size))", "http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in", "may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless", "+ 1) - dx img_ys_len = (ey + 1) -", "boundingbox[:, 2] - boundingbox[:, 0] + 1 h = boundingbox[:,", "np.maximum(0, edx - 1) ey = np.maximum(0, ey - 1)", "(edy + 1) - dy tmp_xs_len = (edx + 1)", "= bboxA[:, 0] + w * 0.5 - max_side *", "y - 1) x = np.maximum(0, x - 1) edy", "= np.maximum(0, ex - 1) return filter_valid(dy, edy, dx, edx,", "tempimg[k, :, :, :] = cv2.resize(tmp, (dst_size, dst_size)) image.data =", "mv = mv[np.sort(peek).astype(int)] x_mins, y_mins, x_maxs, y_maxs, _ = bbreg(bboxes,", "* h bb2 = boundingbox[:, 2] + reg[:, 2] *", "tmpw[tmp] ex[tmp] = w - 1 tmp = np.where(ey >", "under the License is distributed on an \"AS IS\" BASIS,", "= boundingbox[:, 0] + reg[:, 0] * w bb1 =", "np.where(ex > w)[0] if tmp.shape[0] != 0: edx[tmp] = -ex[tmp]", "2, axis=0).T return bboxA def cut_roi(image, prediction, dst_size, include_bound=True): bboxes", "MTCNNPAdapter def calibrate_predictions(previous_stage_predictions, out, threshold, outputs_mapping, iou_type=None): prob_out = outputs_mapping['probability_out']", "return dy[mask], edy[mask], dx[mask], edx[mask], y[mask], ey[mask], x[mask], ex[mask], tmpw[mask],", "previous_stage_predictions[0].remove(removed_boxes) previous_stage_predictions[0].scores = score[pass_t] bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs,", "= pad(bboxes, *img.shape[:2]) bboxes = bboxes[mask] numbox = bboxes.shape[0] tempimg", "data.shape[0] <= i: box_outs[layer_name] = data else: box_outs[layer_name] = np.expand_dims(data[i],", "boxes w = boundingbox[:, 2] - boundingbox[:, 0] + 1", "boxes[:, 0] + 1 numbox = boxes.shape[0] dx = np.ones(numbox)", "tmp_xs = slice(int(dy[k]), int(edy[k]) + 1), slice(int(dx[k]), int(edx[k]) + 1)", "prediction, peek def bbreg(boundingbox, reg): reg = reg.T # calibrate", "0.7)[0] removed_boxes = [i for i in range(previous_stage_predictions[0].size) if i", "np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] mv = mv[np.sort(peek).astype(int)]", "= boxes[:, 3] - boxes[:, 1] + 1 tmpw =", "in prob_out else prob_out.replace('/sink_port_0', '') score = out[0][prob_out][:, 1] pass_t", "reg[:, 1] * h bb2 = boundingbox[:, 2] + reg[:,", "dy[mask], edy[mask], dx[mask], edx[mask], y[mask], ey[mask], x[mask], ex[mask], tmpw[mask], tmph[mask],", "1) - dx img_ys_len = (ey + 1) - y", "= score[pass_t] bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores", "import numpy as np from ...adapters import MTCNNPAdapter def calibrate_predictions(previous_stage_predictions,", "= boxes[:, 1:2][:, 0] ex = boxes[:, 2:3][:, 0] ey", "this file except in compliance with the License. You may", "boxes[:, 1] + 1 tmpw = boxes[:, 2] - boxes[:,", "!= 0: dx[tmp] = 2 - x[tmp] x[tmp] = np.ones_like(x[tmp])", "while matlab from 1 dy, dx = np.maximum(0, dy -", "= 2 - x[tmp] x[tmp] = np.ones_like(x[tmp]) tmp = np.where(y", "np.maximum(0, y - 1) x = np.maximum(0, x - 1)", "- 1) ey = np.maximum(0, ey - 1) ex =", "- 1 + tmph[tmp] ey[tmp] = h - 1 tmp", "ey, x, ex, tmpw, tmph) def rerec(bboxA): w = bboxA[:,", "- x mask = np.logical_and(mask, np.logical_and(tmph > 0, tmpw >", "not in region_out else region_out.replace('/sink_port_0', '') ) mv = out[0][region_out][pass_t]", "collections import OrderedDict import cv2 import numpy as np from", "np.logical_and(img_xs_len > 0, img_ys_len > 0)) mask = np.logical_and(mask, np.logical_and(tmp_xs_len", "numpy as np from ...adapters import MTCNNPAdapter def calibrate_predictions(previous_stage_predictions, out,", "in pass_t] previous_stage_predictions[0].remove(removed_boxes) previous_stage_predictions[0].scores = score[pass_t] bboxes = np.c_[ previous_stage_predictions[0].x_mins,", "= np.fix(bboxes[:, 0:4]) dy, edy, dx, edx, y, ey, x,", "ey = np.maximum(0, ey - 1) ex = np.maximum(0, ex", "language governing permissions and limitations under the License. \"\"\" from", "reg[:, 0] * w bb1 = boundingbox[:, 1] + reg[:,", "np from ...adapters import MTCNNPAdapter def calibrate_predictions(previous_stage_predictions, out, threshold, outputs_mapping,", "tmph): mask = np.ones(len(tmph)) tmp_ys_len = (edy + 1) -", "region_out + '/sink_port_0' if '/sink_port_0' not in region_out else region_out.replace('/sink_port_0',", "tmpw = boxes[:, 2] - boxes[:, 0] + 1 numbox", "- boxes[:, 1] + 1 tmpw = boxes[:, 2] -", "bb3 = boundingbox[:, 3] + reg[:, 3] * h boundingbox[:,", "dx, edx, y, ey, x, ex, tmpw, tmph): mask =", "+ h - 1 + tmph[tmp] ey[tmp] = h -", "not in out[0]: prob_out = prob_out + '/sink_port_0' if '/sink_port_0'", "h - 1 + tmph[tmp] ey[tmp] = h - 1", "ey[tmp] = h - 1 tmp = np.where(x < 1)[0]", "reg.T # calibrate bounding boxes w = boundingbox[:, 2] -", "+ int(include_bound) tmp = np.zeros((tmp_k_h, tmp_k_w, 3)) tmp_ys, tmp_xs =", "tmp = np.where(ey > h)[0] if tmp.shape[0] != 0: edy[tmp]", "iou_type) prediction.remove([i for i in range(prediction.size) if i not in", "file except in compliance with the License. You may obtain", "ey, x, ex, tmpw, tmph): mask = np.ones(len(tmph)) tmp_ys_len =", "img_xs_len, tmp_ys_len == img_ys_len)) return dy[mask], edy[mask], dx[mask], edx[mask], y[mask],", "ex - 1) return filter_valid(dy, edy, dx, edx, y, ey,", "= np.maximum(w, h).T bboxA[:, 0] = bboxA[:, 0] + w", "1), slice(int(x[k]), int(ex[k]) + 1) tmp[tmp_ys, tmp_xs] = img[img_ys, img_xs]", "> 0)) mask = np.logical_and(mask, np.logical_and(tmp_ys_len > 0, tmp_xs_len >", "y[mask], ey[mask], x[mask], ex[mask], tmpw[mask], tmph[mask], mask def pad(boxesA, h,", "- boundingbox[:, 1] + 1 bb0 = boundingbox[:, 0] +", "x, ex, tmpw, tmph, mask = pad(bboxes, *img.shape[:2]) bboxes =", "filter_valid(dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph):", "previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] mv = mv[np.sort(peek).astype(int)] x_mins, y_mins, x_maxs,", "OR CONDITIONS OF ANY KIND, either express or implied. See", "(c) 2018-2022 Intel Corporation Licensed under the Apache License, Version", "ex = boxes[:, 2:3][:, 0] ey = boxes[:, 3:4][:, 0]", "tmp.shape[0] != 0: dx[tmp] = 2 - x[tmp] x[tmp] =", "= np.logical_and(mask, np.logical_and(tmph > 0, tmpw > 0)) mask =", "= prob_out + '/sink_port_0' if '/sink_port_0' not in prob_out else", "0.5 bboxA[:, 2:4] = bboxA[:, 0:2] + np.repeat([max_side], 2, axis=0).T", "= nms(previous_stage_predictions[0], threshold, iou_type) bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs,", "edy = np.maximum(0, edy - 1) edx = np.maximum(0, edx", "0:4] = np.fix(bboxes[:, 0:4]) dy, edy, dx, edx, y, ey,", "under the Apache License, Version 2.0 (the \"License\"); you may", "( region_out + '/sink_port_0' if '/sink_port_0' not in region_out else", "in fq_weights: continue if layer_name.endswith('fq_weights_1'): fq_weights.append(layer_name) box_outs[layer_name] = data elif", "region_out = outputs_mapping['region_out'] if region_out not in out[0]: region_out =", "= boundingbox[:, 3] + reg[:, 3] * h boundingbox[:, 0:4]", "= MTCNNPAdapter.nms(bboxes, threshold, iou_type) prediction.remove([i for i in range(prediction.size) if", "img_ys, img_xs = slice(int(y[k]), int(ey[k]) + 1), slice(int(x[k]), int(ex[k]) +", "data elif data.shape[0] <= i: box_outs[layer_name] = data else: box_outs[layer_name]", "previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] mv = mv[np.sort(peek).astype(int)] x_mins,", "_ = bbreg(bboxes, mv.T).T previous_stage_predictions[0].x_mins = x_mins previous_stage_predictions[0].y_mins = y_mins", "tmp_k_w, 3)) tmp_ys, tmp_xs = slice(int(dy[k]), int(edy[k]) + 1), slice(int(dx[k]),", "- bboxA[:, 1] max_side = np.maximum(w, h).T bboxA[:, 0] =", "= np.where(x < 1)[0] if tmp.shape[0] != 0: dx[tmp] =", "1] + 1 bb0 = boundingbox[:, 0] + reg[:, 0]", "h - 1 tmp = np.where(x < 1)[0] if tmp.shape[0]", "x_mins, y_mins, x_maxs, y_maxs, _ = bbreg(bboxes, mv.T).T previous_stage_predictions[0].x_mins =", "2] - boundingbox[:, 0] + 1 h = boundingbox[:, 3]", "!= 0: edx[tmp] = -ex[tmp] + w - 1 +", "boxesA.copy() tmph = boxes[:, 3] - boxes[:, 1] + 1", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "See the License for the specific language governing permissions and", "previous_stage_predictions[0].scores ] mv = mv[np.sort(peek).astype(int)] x_mins, y_mins, x_maxs, y_maxs, _", "(ex + 1) - x mask = np.logical_and(mask, np.logical_and(tmph >", "0: edx[tmp] = -ex[tmp] + w - 1 + tmpw[tmp]", "edy[mask], dx[mask], edx[mask], y[mask], ey[mask], x[mask], ex[mask], tmpw[mask], tmph[mask], mask", "+ 1 numbox = boxes.shape[0] dx = np.ones(numbox) dy =", "bboxA[:, 0] = bboxA[:, 0] + w * 0.5 -", "- dx img_ys_len = (ey + 1) - y img_xs_len", "= slice(int(y[k]), int(ey[k]) + 1), slice(int(x[k]), int(ex[k]) + 1) tmp[tmp_ys,", "prediction.x_maxs, prediction.y_maxs, prediction.scores] img = image.data bboxes = rerec(bboxes) bboxes[:,", "w * 0.5 - max_side * 0.5 bboxA[:, 1] =", "0:2] + np.repeat([max_side], 2, axis=0).T return bboxA def cut_roi(image, prediction,", "tmpw, tmph, mask = pad(bboxes, *img.shape[:2]) bboxes = bboxes[mask] numbox", "> 0.7)[0] removed_boxes = [i for i in range(previous_stage_predictions[0].size) if", "mv.T).T previous_stage_predictions[0].x_mins = x_mins previous_stage_predictions[0].y_mins = y_mins previous_stage_predictions[0].x_maxs = x_maxs", "0.5 - max_side * 0.5 bboxA[:, 1] = bboxA[:, 1]", "dst_size, include_bound=True): bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] img", "= np.maximum(0, dy - 1), np.maximum(0, dx - 1) y", "in writing, software distributed under the License is distributed on", "- bboxA[:, 0] h = bboxA[:, 3] - bboxA[:, 1]", "edx, y, ey, x, ex, tmpw, tmph, mask = pad(bboxes,", "required by applicable law or agreed to in writing, software", "if layer_name.endswith('fq_weights_1'): fq_weights.append(layer_name) box_outs[layer_name] = data elif data.shape[0] <= i:", "1)[0] if tmp.shape[0] != 0: dx[tmp] = 2 - x[tmp]", "2] + reg[:, 2] * w bb3 = boundingbox[:, 3]", "x[tmp] = np.ones_like(x[tmp]) tmp = np.where(y < 1)[0] if tmp.shape[0]", "= bboxA[:, 3] - bboxA[:, 1] max_side = np.maximum(w, h).T", "= OrderedDict() for layer_name, data in raw_outputs[0].items(): if layer_name in", "pad(boxesA, h, w): boxes = boxesA.copy() tmph = boxes[:, 3]", "- 1 + tmpw[tmp] ex[tmp] = w - 1 tmp", "x_mins previous_stage_predictions[0].y_mins = y_mins previous_stage_predictions[0].x_maxs = x_maxs previous_stage_predictions[0].y_maxs = y_maxs", "tempimg = np.zeros((numbox, dst_size, dst_size, 3)) for k in range(numbox):", "tmp = np.zeros((tmp_k_h, tmp_k_w, 3)) tmp_ys, tmp_xs = slice(int(dy[k]), int(edy[k])", "for i in range(batch_size): box_outs = OrderedDict() for layer_name, data", "calibrate_predictions(previous_stage_predictions, out, threshold, outputs_mapping, iou_type=None): prob_out = outputs_mapping['probability_out'] if prob_out", "0, tmpw > 0)) mask = np.logical_and(mask, np.logical_and(tmp_ys_len > 0,", "= np.ones(numbox) dy = np.ones(numbox) edx = tmpw edy =", "ex, tmpw, tmph) def rerec(bboxA): w = bboxA[:, 2] -", "bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] region_out", "'/sink_port_0' not in region_out else region_out.replace('/sink_port_0', '') ) mv =", "not in out[0]: region_out = ( region_out + '/sink_port_0' if", "bounding boxes w = boundingbox[:, 2] - boundingbox[:, 0] +", "include_bound=True): bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] img =", "np.logical_and(tmp_ys_len > 0, tmp_xs_len > 0)) mask = np.logical_and(mask, np.logical_and(img_xs_len", "ex = np.maximum(0, ex - 1) return filter_valid(dy, edy, dx,", "- dy tmp_xs_len = (edx + 1) - dx img_ys_len", "max_side * 0.5 bboxA[:, 2:4] = bboxA[:, 0:2] + np.repeat([max_side],", "previous_stage_predictions[0], peek = nms(previous_stage_predictions[0], threshold, iou_type) bboxes = np.c_[ previous_stage_predictions[0].x_mins,", "prediction.y_maxs, prediction.scores] img = image.data bboxes = rerec(bboxes) bboxes[:, 0:4]", "= np.ones_like(x[tmp]) tmp = np.where(y < 1)[0] if tmp.shape[0] !=", "= bboxes.shape[0] tempimg = np.zeros((numbox, dst_size, dst_size, 3)) for k", "= boundingbox[:, 2] - boundingbox[:, 0] + 1 h =", "previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] region_out = outputs_mapping['region_out'] if", "= y_maxs return previous_stage_predictions def nms(prediction, threshold, iou_type): bboxes =", "software distributed under the License is distributed on an \"AS", "distributed under the License is distributed on an \"AS IS\"", "- 1), np.maximum(0, dx - 1) y = np.maximum(0, y", "fq_weights = [] for i in range(batch_size): box_outs = OrderedDict()", "np.maximum(0, dx - 1) y = np.maximum(0, y - 1)", "0.5 bboxA[:, 1] = bboxA[:, 1] + h * 0.5", "CONDITIONS OF ANY KIND, either express or implied. See the", "= int(tmph[k]) + int(include_bound), int(tmpw[k]) + int(include_bound) tmp = np.zeros((tmp_k_h,", "Version 2.0 (the \"License\"); you may not use this file", "'/sink_port_0' not in prob_out else prob_out.replace('/sink_port_0', '') score = out[0][prob_out][:,", "mask = np.logical_and(mask, np.logical_and(tmph > 0, tmpw > 0)) mask", "y, ey, x, ex, tmpw, tmph, mask = pad(bboxes, *img.shape[:2])", "peek]) return prediction, peek def bbreg(boundingbox, reg): reg = reg.T", "y, ey, x, ex, tmpw, tmph): mask = np.ones(len(tmph)) tmp_ys_len", "range(prediction.size) if i not in peek]) return prediction, peek def", "bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] mv", "x[mask], ex[mask], tmpw[mask], tmph[mask], mask def pad(boxesA, h, w): boxes", "np.zeros((numbox, dst_size, dst_size, 3)) for k in range(numbox): tmp_k_h, tmp_k_w", "tmp_ys, tmp_xs = slice(int(dy[k]), int(edy[k]) + 1), slice(int(dx[k]), int(edx[k]) +", "prob_out = prob_out + '/sink_port_0' if '/sink_port_0' not in prob_out", ") mv = out[0][region_out][pass_t] if iou_type: previous_stage_predictions[0], peek = nms(previous_stage_predictions[0],", "import MTCNNPAdapter def calibrate_predictions(previous_stage_predictions, out, threshold, outputs_mapping, iou_type=None): prob_out =", "prediction.y_maxs, prediction.scores] peek = MTCNNPAdapter.nms(bboxes, threshold, iou_type) prediction.remove([i for i", "1) img_ys, img_xs = slice(int(y[k]), int(ey[k]) + 1), slice(int(x[k]), int(ex[k])", "not use this file except in compliance with the License.", "2.0 (the \"License\"); you may not use this file except", "copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable", "x = np.maximum(0, x - 1) edy = np.maximum(0, edy", "for k in range(numbox): tmp_k_h, tmp_k_w = int(tmph[k]) + int(include_bound),", "numbox = boxes.shape[0] dx = np.ones(numbox) dy = np.ones(numbox) edx", "if region_out not in out[0]: region_out = ( region_out +", "bb2, bb3]).T return boundingbox def filter_valid(dy, edy, dx, edx, y,", "tmp.shape[0] != 0: dy[tmp] = 2 - y[tmp] y[tmp] =", "edy, dx, edx, y, ey, x, ex, tmpw, tmph): mask", "you may not use this file except in compliance with", "np.zeros((tmp_k_h, tmp_k_w, 3)) tmp_ys, tmp_xs = slice(int(dy[k]), int(edy[k]) + 1),", "1 numbox = boxes.shape[0] dx = np.ones(numbox) dy = np.ones(numbox)", "= boundingbox[:, 2] + reg[:, 2] * w bb3 =", "is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "boxes[:, 2:3][:, 0] ey = boxes[:, 3:4][:, 0] tmp =", "the License. You may obtain a copy of the License", "previous_stage_predictions[0].y_mins = y_mins previous_stage_predictions[0].x_maxs = x_maxs previous_stage_predictions[0].y_maxs = y_maxs return", "edy, dx, edx, y, ey, x, ex, tmpw, tmph, mask", "= 2 - y[tmp] y[tmp] = np.ones_like(y[tmp]) # for python", "image.data = tempimg return image def transform_for_callback(batch_size, raw_outputs): output_per_box =", "0] ex = boxes[:, 2:3][:, 0] ey = boxes[:, 3:4][:,", "not in peek]) return prediction, peek def bbreg(boundingbox, reg): reg", "np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] region_out = outputs_mapping['region_out']", "use this file except in compliance with the License. You", "mask def pad(boxesA, h, w): boxes = boxesA.copy() tmph =", "np.ones(numbox) edx = tmpw edy = tmph x = boxes[:,", "0] = bboxA[:, 0] + w * 0.5 - max_side", "+ w - 1 + tmpw[tmp] ex[tmp] = w -", "* 0.5 - max_side * 0.5 bboxA[:, 1] = bboxA[:,", "if '/sink_port_0' not in prob_out else prob_out.replace('/sink_port_0', '') score =", "dx = np.maximum(0, dy - 1), np.maximum(0, dx - 1)", "= np.maximum(0, ey - 1) ex = np.maximum(0, ex -", "cut_roi(image, prediction, dst_size, include_bound=True): bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs,", "cv2 import numpy as np from ...adapters import MTCNNPAdapter def", "== img_ys_len)) return dy[mask], edy[mask], dx[mask], edx[mask], y[mask], ey[mask], x[mask],", "tmp = np.where(ex > w)[0] if tmp.shape[0] != 0: edx[tmp]", "!= 0: edy[tmp] = -ey[tmp] + h - 1 +", "tmp_k_h, tmp_k_w = int(tmph[k]) + int(include_bound), int(tmpw[k]) + int(include_bound) tmp", "mask = np.logical_and(mask, np.logical_and(tmp_xs_len == img_xs_len, tmp_ys_len == img_ys_len)) return", "(dst_size, dst_size)) image.data = tempimg return image def transform_for_callback(batch_size, raw_outputs):", "2 - x[tmp] x[tmp] = np.ones_like(x[tmp]) tmp = np.where(y <", "= bboxA[:, 1] + h * 0.5 - max_side *", "def bbreg(boundingbox, reg): reg = reg.T # calibrate bounding boxes", "- 1) y = np.maximum(0, y - 1) x =", "+ 1) - x mask = np.logical_and(mask, np.logical_and(tmph > 0,", "if layer_name in fq_weights: continue if layer_name.endswith('fq_weights_1'): fq_weights.append(layer_name) box_outs[layer_name] =", "w = bboxA[:, 2] - bboxA[:, 0] h = bboxA[:,", "+ int(include_bound), int(tmpw[k]) + int(include_bound) tmp = np.zeros((tmp_k_h, tmp_k_w, 3))", "1] + reg[:, 1] * h bb2 = boundingbox[:, 2]", "out[0]: region_out = ( region_out + '/sink_port_0' if '/sink_port_0' not", "np.maximum(0, x - 1) edy = np.maximum(0, edy - 1)", "* 0.5 bboxA[:, 2:4] = bboxA[:, 0:2] + np.repeat([max_side], 2,", "def filter_valid(dy, edy, dx, edx, y, ey, x, ex, tmpw,", "bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] peek = MTCNNPAdapter.nms(bboxes,", "image.data bboxes = rerec(bboxes) bboxes[:, 0:4] = np.fix(bboxes[:, 0:4]) dy,", "in range(previous_stage_predictions[0].size) if i not in pass_t] previous_stage_predictions[0].remove(removed_boxes) previous_stage_predictions[0].scores =", "boundingbox[:, 3] - boundingbox[:, 1] + 1 bb0 = boundingbox[:,", "mask = np.logical_and(mask, np.logical_and(tmp_ys_len > 0, tmp_xs_len > 0)) mask", "3] - boundingbox[:, 1] + 1 bb0 = boundingbox[:, 0]", "dst_size, 3)) for k in range(numbox): tmp_k_h, tmp_k_w = int(tmph[k])", "int(include_bound), int(tmpw[k]) + int(include_bound) tmp = np.zeros((tmp_k_h, tmp_k_w, 3)) tmp_ys,", "prob_out not in out[0]: prob_out = prob_out + '/sink_port_0' if", "0.5 - max_side * 0.5 bboxA[:, 2:4] = bboxA[:, 0:2]", "> 0)) mask = np.logical_and(mask, np.logical_and(tmp_xs_len == img_xs_len, tmp_ys_len ==", "tmp[tmp_ys, tmp_xs] = img[img_ys, img_xs] tempimg[k, :, :, :] =", "= outputs_mapping['probability_out'] if prob_out not in out[0]: prob_out = prob_out", "(the \"License\"); you may not use this file except in", "iou_type) bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ]", "edy = tmph x = boxes[:, 0:1][:, 0] y =", "- 1) edy = np.maximum(0, edy - 1) edx =", "fq_weights: continue if layer_name.endswith('fq_weights_1'): fq_weights.append(layer_name) box_outs[layer_name] = data elif data.shape[0]", "boundingbox def filter_valid(dy, edy, dx, edx, y, ey, x, ex,", "= x_maxs previous_stage_predictions[0].y_maxs = y_maxs return previous_stage_predictions def nms(prediction, threshold,", "1 tmp = np.where(x < 1)[0] if tmp.shape[0] != 0:", "reg[:, 3] * h boundingbox[:, 0:4] = np.array([bb0, bb1, bb2,", "\"\"\" Copyright (c) 2018-2022 Intel Corporation Licensed under the Apache", "- max_side * 0.5 bboxA[:, 2:4] = bboxA[:, 0:2] +", ":, :] = cv2.resize(tmp, (dst_size, dst_size)) image.data = tempimg return", "0, tmp_xs_len > 0)) mask = np.logical_and(mask, np.logical_and(img_xs_len > 0,", "else region_out.replace('/sink_port_0', '') ) mv = out[0][region_out][pass_t] if iou_type: previous_stage_predictions[0],", "bboxA[:, 0] + w * 0.5 - max_side * 0.5", "= boxesA.copy() tmph = boxes[:, 3] - boxes[:, 1] +", "1), np.maximum(0, dx - 1) y = np.maximum(0, y -", "You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0", "1) return filter_valid(dy, edy, dx, edx, y, ey, x, ex,", "prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] peek = MTCNNPAdapter.nms(bboxes, threshold, iou_type) prediction.remove([i", "1) edy = np.maximum(0, edy - 1) edx = np.maximum(0,", "1 + tmpw[tmp] ex[tmp] = w - 1 tmp =", "filter_valid(dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph)", "mv = out[0][region_out][pass_t] if iou_type: previous_stage_predictions[0], peek = nms(previous_stage_predictions[0], threshold,", "1 tmp = np.where(ey > h)[0] if tmp.shape[0] != 0:", "edy - 1) edx = np.maximum(0, edx - 1) ey", "ex, tmpw, tmph, mask = pad(bboxes, *img.shape[:2]) bboxes = bboxes[mask]", "limitations under the License. \"\"\" from collections import OrderedDict import", "tmp.shape[0] != 0: edy[tmp] = -ey[tmp] + h - 1", "matlab from 1 dy, dx = np.maximum(0, dy - 1),", "'/sink_port_0' if '/sink_port_0' not in region_out else region_out.replace('/sink_port_0', '') )", "outputs_mapping, iou_type=None): prob_out = outputs_mapping['probability_out'] if prob_out not in out[0]:", "the Apache License, Version 2.0 (the \"License\"); you may not", "or implied. See the License for the specific language governing", "tmp_k_w = int(tmph[k]) + int(include_bound), int(tmpw[k]) + int(include_bound) tmp =", "KIND, either express or implied. See the License for the", "+ '/sink_port_0' if '/sink_port_0' not in prob_out else prob_out.replace('/sink_port_0', '')", "tmpw, tmph): mask = np.ones(len(tmph)) tmp_ys_len = (edy + 1)", "img_ys_len)) return dy[mask], edy[mask], dx[mask], edx[mask], y[mask], ey[mask], x[mask], ex[mask],", "to in writing, software distributed under the License is distributed", "for i in range(prediction.size) if i not in peek]) return", "transform_for_callback(batch_size, raw_outputs): output_per_box = [] fq_weights = [] for i", "slice(int(dx[k]), int(edx[k]) + 1) img_ys, img_xs = slice(int(y[k]), int(ey[k]) +", "0)) mask = np.logical_and(mask, np.logical_and(tmp_ys_len > 0, tmp_xs_len > 0))", "dx[mask], edx[mask], y[mask], ey[mask], x[mask], ex[mask], tmpw[mask], tmph[mask], mask def", "1] + h * 0.5 - max_side * 0.5 bboxA[:,", "law or agreed to in writing, software distributed under the", "ex, tmpw, tmph): mask = np.ones(len(tmph)) tmp_ys_len = (edy +", "= tmph x = boxes[:, 0:1][:, 0] y = boxes[:,", "iou_type): bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] peek =", "np.array([bb0, bb1, bb2, bb3]).T return boundingbox def filter_valid(dy, edy, dx,", "+ tmpw[tmp] ex[tmp] = w - 1 tmp = np.where(ey", "i in range(prediction.size) if i not in peek]) return prediction,", "= mv[np.sort(peek).astype(int)] x_mins, y_mins, x_maxs, y_maxs, _ = bbreg(bboxes, mv.T).T", "not in prob_out else prob_out.replace('/sink_port_0', '') score = out[0][prob_out][:, 1]", "< 1)[0] if tmp.shape[0] != 0: dx[tmp] = 2 -", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "- x[tmp] x[tmp] = np.ones_like(x[tmp]) tmp = np.where(y < 1)[0]", "iou_type=None): prob_out = outputs_mapping['probability_out'] if prob_out not in out[0]: prob_out", "1) edx = np.maximum(0, edx - 1) ey = np.maximum(0,", "1) - dy tmp_xs_len = (edx + 1) - dx", "prediction.x_maxs, prediction.y_maxs, prediction.scores] peek = MTCNNPAdapter.nms(bboxes, threshold, iou_type) prediction.remove([i for", "= np.array([bb0, bb1, bb2, bb3]).T return boundingbox def filter_valid(dy, edy,", "edx[mask], y[mask], ey[mask], x[mask], ex[mask], tmpw[mask], tmph[mask], mask def pad(boxesA,", "<= i: box_outs[layer_name] = data else: box_outs[layer_name] = np.expand_dims(data[i], axis=0)", "tmp_ys_len == img_ys_len)) return dy[mask], edy[mask], dx[mask], edx[mask], y[mask], ey[mask],", "threshold, iou_type) bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores", "dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph,", "permissions and limitations under the License. \"\"\" from collections import", "cv2.resize(tmp, (dst_size, dst_size)) image.data = tempimg return image def transform_for_callback(batch_size,", "bb2 = boundingbox[:, 2] + reg[:, 2] * w bb3", "for the specific language governing permissions and limitations under the", "+ tmph[tmp] ey[tmp] = h - 1 tmp = np.where(x", "x, ex, tmpw, tmph) def rerec(bboxA): w = bboxA[:, 2]", "layer_name, data in raw_outputs[0].items(): if layer_name in fq_weights: continue if", "1 h = boundingbox[:, 3] - boundingbox[:, 1] + 1", "0] + reg[:, 0] * w bb1 = boundingbox[:, 1]", "bboxes = rerec(bboxes) bboxes[:, 0:4] = np.fix(bboxes[:, 0:4]) dy, edy,", "reg = reg.T # calibrate bounding boxes w = boundingbox[:,", "bboxA[:, 3] - bboxA[:, 1] max_side = np.maximum(w, h).T bboxA[:,", "edx, y, ey, x, ex, tmpw, tmph) def rerec(bboxA): w", "bboxA[:, 2] - bboxA[:, 0] h = bboxA[:, 3] -", "prediction.remove([i for i in range(prediction.size) if i not in peek])", "i not in peek]) return prediction, peek def bbreg(boundingbox, reg):", "mask = np.logical_and(mask, np.logical_and(img_xs_len > 0, img_ys_len > 0)) mask", "def nms(prediction, threshold, iou_type): bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs,", "= [] fq_weights = [] for i in range(batch_size): box_outs", "w - 1 tmp = np.where(ey > h)[0] if tmp.shape[0]", "ey = boxes[:, 3:4][:, 0] tmp = np.where(ex > w)[0]", "layer_name.endswith('fq_weights_1'): fq_weights.append(layer_name) box_outs[layer_name] = data elif data.shape[0] <= i: box_outs[layer_name]", "- 1) edx = np.maximum(0, edx - 1) ey =", "- y[tmp] y[tmp] = np.ones_like(y[tmp]) # for python index from", "= data elif data.shape[0] <= i: box_outs[layer_name] = data else:", "1) ex = np.maximum(0, ex - 1) return filter_valid(dy, edy,", "0] ey = boxes[:, 3:4][:, 0] tmp = np.where(ex >", "the License for the specific language governing permissions and limitations", "previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] region_out = outputs_mapping['region_out'] if region_out", "may not use this file except in compliance with the", "if iou_type: previous_stage_predictions[0], peek = nms(previous_stage_predictions[0], threshold, iou_type) bboxes =", "nms(previous_stage_predictions[0], threshold, iou_type) bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs,", "np.ones(len(tmph)) tmp_ys_len = (edy + 1) - dy tmp_xs_len =", "= -ex[tmp] + w - 1 + tmpw[tmp] ex[tmp] =", "1] max_side = np.maximum(w, h).T bboxA[:, 0] = bboxA[:, 0]", "y_mins previous_stage_predictions[0].x_maxs = x_maxs previous_stage_predictions[0].y_maxs = y_maxs return previous_stage_predictions def", "implied. See the License for the specific language governing permissions", "= np.maximum(0, y - 1) x = np.maximum(0, x -", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "from 0, while matlab from 1 dy, dx = np.maximum(0,", "= bboxA[:, 2] - bboxA[:, 0] h = bboxA[:, 3]", "= [] for i in range(batch_size): box_outs = OrderedDict() for", "if '/sink_port_0' not in region_out else region_out.replace('/sink_port_0', '') ) mv", "= np.where(ex > w)[0] if tmp.shape[0] != 0: edx[tmp] =", "0:1][:, 0] y = boxes[:, 1:2][:, 0] ex = boxes[:,", "tmp_xs_len > 0)) mask = np.logical_and(mask, np.logical_and(img_xs_len > 0, img_ys_len", "= np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] peek = MTCNNPAdapter.nms(bboxes, threshold,", "output_per_box = [] fq_weights = [] for i in range(batch_size):", "= bbreg(bboxes, mv.T).T previous_stage_predictions[0].x_mins = x_mins previous_stage_predictions[0].y_mins = y_mins previous_stage_predictions[0].x_maxs", "= np.ones_like(y[tmp]) # for python index from 0, while matlab", "in peek]) return prediction, peek def bbreg(boundingbox, reg): reg =", "*img.shape[:2]) bboxes = bboxes[mask] numbox = bboxes.shape[0] tempimg = np.zeros((numbox,", "int(ex[k]) + 1) tmp[tmp_ys, tmp_xs] = img[img_ys, img_xs] tempimg[k, :,", "boxes.shape[0] dx = np.ones(numbox) dy = np.ones(numbox) edx = tmpw", "previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] region_out = outputs_mapping['region_out'] if region_out not", "boundingbox[:, 0:4] = np.array([bb0, bb1, bb2, bb3]).T return boundingbox def", "3:4][:, 0] tmp = np.where(ex > w)[0] if tmp.shape[0] !=", "range(previous_stage_predictions[0].size) if i not in pass_t] previous_stage_predictions[0].remove(removed_boxes) previous_stage_predictions[0].scores = score[pass_t]", "> 0, img_ys_len > 0)) mask = np.logical_and(mask, np.logical_and(tmp_xs_len ==", "prob_out.replace('/sink_port_0', '') score = out[0][prob_out][:, 1] pass_t = np.where(score >", "x = boxes[:, 0:1][:, 0] y = boxes[:, 1:2][:, 0]", "int(edy[k]) + 1), slice(int(dx[k]), int(edx[k]) + 1) img_ys, img_xs =", "for python index from 0, while matlab from 1 dy,", "(ey + 1) - y img_xs_len = (ex + 1)", "= bboxes[mask] numbox = bboxes.shape[0] tempimg = np.zeros((numbox, dst_size, dst_size,", "boundingbox[:, 2] + reg[:, 2] * w bb3 = boundingbox[:,", "prediction, dst_size, include_bound=True): bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores]", "previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] region_out = outputs_mapping['region_out'] if region_out not in", "w bb1 = boundingbox[:, 1] + reg[:, 1] * h", "+ 1) - y img_xs_len = (ex + 1) -", "dx[tmp] = 2 - x[tmp] x[tmp] = np.ones_like(x[tmp]) tmp =", "= np.maximum(0, edx - 1) ey = np.maximum(0, ey -", "'/sink_port_0' if '/sink_port_0' not in prob_out else prob_out.replace('/sink_port_0', '') score", "License. \"\"\" from collections import OrderedDict import cv2 import numpy", "= np.maximum(0, x - 1) edy = np.maximum(0, edy -", "from 1 dy, dx = np.maximum(0, dy - 1), np.maximum(0,", "= np.logical_and(mask, np.logical_and(img_xs_len > 0, img_ys_len > 0)) mask =", "previous_stage_predictions[0].y_maxs = y_maxs return previous_stage_predictions def nms(prediction, threshold, iou_type): bboxes", "= y_mins previous_stage_predictions[0].x_maxs = x_maxs previous_stage_predictions[0].y_maxs = y_maxs return previous_stage_predictions", "= w - 1 tmp = np.where(ey > h)[0] if", "== img_xs_len, tmp_ys_len == img_ys_len)) return dy[mask], edy[mask], dx[mask], edx[mask],", "3] - bboxA[:, 1] max_side = np.maximum(w, h).T bboxA[:, 0]", "= np.logical_and(mask, np.logical_and(tmp_ys_len > 0, tmp_xs_len > 0)) mask =", "np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] img = image.data bboxes =", "writing, software distributed under the License is distributed on an", "bboxes[mask] numbox = bboxes.shape[0] tempimg = np.zeros((numbox, dst_size, dst_size, 3))", "threshold, outputs_mapping, iou_type=None): prob_out = outputs_mapping['probability_out'] if prob_out not in", "# for python index from 0, while matlab from 1", "tmph) def rerec(bboxA): w = bboxA[:, 2] - bboxA[:, 0]", "ex[mask], tmpw[mask], tmph[mask], mask def pad(boxesA, h, w): boxes =", "int(tmph[k]) + int(include_bound), int(tmpw[k]) + int(include_bound) tmp = np.zeros((tmp_k_h, tmp_k_w,", "np.logical_and(mask, np.logical_and(tmph > 0, tmpw > 0)) mask = np.logical_and(mask,", "def transform_for_callback(batch_size, raw_outputs): output_per_box = [] fq_weights = [] for", "in compliance with the License. You may obtain a copy", "in range(prediction.size) if i not in peek]) return prediction, peek", "fq_weights.append(layer_name) box_outs[layer_name] = data elif data.shape[0] <= i: box_outs[layer_name] =", "dx = np.ones(numbox) dy = np.ones(numbox) edx = tmpw edy", "boundingbox[:, 0] + reg[:, 0] * w bb1 = boundingbox[:,", "pad(bboxes, *img.shape[:2]) bboxes = bboxes[mask] numbox = bboxes.shape[0] tempimg =", "int(ey[k]) + 1), slice(int(x[k]), int(ex[k]) + 1) tmp[tmp_ys, tmp_xs] =", "= out[0][prob_out][:, 1] pass_t = np.where(score > 0.7)[0] removed_boxes =", "calibrate bounding boxes w = boundingbox[:, 2] - boundingbox[:, 0]", "agreed to in writing, software distributed under the License is", "i: box_outs[layer_name] = data else: box_outs[layer_name] = np.expand_dims(data[i], axis=0) output_per_box.append(box_outs)", "* w bb3 = boundingbox[:, 3] + reg[:, 3] *", "at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to", "if prob_out not in out[0]: prob_out = prob_out + '/sink_port_0'", "img_xs_len = (ex + 1) - x mask = np.logical_and(mask,", "data in raw_outputs[0].items(): if layer_name in fq_weights: continue if layer_name.endswith('fq_weights_1'):", "= cv2.resize(tmp, (dst_size, dst_size)) image.data = tempimg return image def", "boundingbox[:, 1] + 1 bb0 = boundingbox[:, 0] + reg[:,", "0)) mask = np.logical_and(mask, np.logical_and(img_xs_len > 0, img_ys_len > 0))", "> w)[0] if tmp.shape[0] != 0: edx[tmp] = -ex[tmp] +", "edx[tmp] = -ex[tmp] + w - 1 + tmpw[tmp] ex[tmp]", "= h - 1 tmp = np.where(x < 1)[0] if", "dx, edx, y, ey, x, ex, tmpw, tmph, mask =", "h)[0] if tmp.shape[0] != 0: edy[tmp] = -ey[tmp] + h", "tempimg return image def transform_for_callback(batch_size, raw_outputs): output_per_box = [] fq_weights", "'') ) mv = out[0][region_out][pass_t] if iou_type: previous_stage_predictions[0], peek =", "= np.ones(numbox) edx = tmpw edy = tmph x =", "- 1) x = np.maximum(0, x - 1) edy =", "tmph[mask], mask def pad(boxesA, h, w): boxes = boxesA.copy() tmph", "h bb2 = boundingbox[:, 2] + reg[:, 2] * w", "return filter_valid(dy, edy, dx, edx, y, ey, x, ex, tmpw,", "* h boundingbox[:, 0:4] = np.array([bb0, bb1, bb2, bb3]).T return", "= tmpw edy = tmph x = boxes[:, 0:1][:, 0]", "axis=0).T return bboxA def cut_roi(image, prediction, dst_size, include_bound=True): bboxes =", "either express or implied. See the License for the specific", "pass_t] previous_stage_predictions[0].remove(removed_boxes) previous_stage_predictions[0].scores = score[pass_t] bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins,", "bb1 = boundingbox[:, 1] + reg[:, 1] * h bb2", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "y[tmp] = np.ones_like(y[tmp]) # for python index from 0, while", "0] y = boxes[:, 1:2][:, 0] ex = boxes[:, 2:3][:,", "\"License\"); you may not use this file except in compliance", "= np.logical_and(mask, np.logical_and(tmp_xs_len == img_xs_len, tmp_ys_len == img_ys_len)) return dy[mask],", "License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "\"\"\" from collections import OrderedDict import cv2 import numpy as", "outputs_mapping['probability_out'] if prob_out not in out[0]: prob_out = prob_out +", "+ reg[:, 1] * h bb2 = boundingbox[:, 2] +", "= np.where(y < 1)[0] if tmp.shape[0] != 0: dy[tmp] =", "License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed", "boxes[:, 1:2][:, 0] ex = boxes[:, 2:3][:, 0] ey =", "prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] img = image.data bboxes = rerec(bboxes)", "= -ey[tmp] + h - 1 + tmph[tmp] ey[tmp] =", "License for the specific language governing permissions and limitations under", "bboxA[:, 1] = bboxA[:, 1] + h * 0.5 -", "ey - 1) ex = np.maximum(0, ex - 1) return", "2 - y[tmp] y[tmp] = np.ones_like(y[tmp]) # for python index", "1] * h bb2 = boundingbox[:, 2] + reg[:, 2]", "+ 1 tmpw = boxes[:, 2] - boxes[:, 0] +", "img_ys_len = (ey + 1) - y img_xs_len = (ex", "nms(prediction, threshold, iou_type): bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores]", "previous_stage_predictions[0].scores ] region_out = outputs_mapping['region_out'] if region_out not in out[0]:", "h * 0.5 - max_side * 0.5 bboxA[:, 2:4] =", "continue if layer_name.endswith('fq_weights_1'): fq_weights.append(layer_name) box_outs[layer_name] = data elif data.shape[0] <=", "np.maximum(0, ex - 1) return filter_valid(dy, edy, dx, edx, y,", "x_maxs, y_maxs, _ = bbreg(bboxes, mv.T).T previous_stage_predictions[0].x_mins = x_mins previous_stage_predictions[0].y_mins", "x_maxs previous_stage_predictions[0].y_maxs = y_maxs return previous_stage_predictions def nms(prediction, threshold, iou_type):", "peek = MTCNNPAdapter.nms(bboxes, threshold, iou_type) prediction.remove([i for i in range(prediction.size)", "in range(batch_size): box_outs = OrderedDict() for layer_name, data in raw_outputs[0].items():", "w = boundingbox[:, 2] - boundingbox[:, 0] + 1 h", "= [i for i in range(previous_stage_predictions[0].size) if i not in", "index from 0, while matlab from 1 dy, dx =", "= data else: box_outs[layer_name] = np.expand_dims(data[i], axis=0) output_per_box.append(box_outs) return output_per_box", "0] + w * 0.5 - max_side * 0.5 bboxA[:,", "3] - boxes[:, 1] + 1 tmpw = boxes[:, 2]", "out, threshold, outputs_mapping, iou_type=None): prob_out = outputs_mapping['probability_out'] if prob_out not", "np.maximum(w, h).T bboxA[:, 0] = bboxA[:, 0] + w *", "= ( region_out + '/sink_port_0' if '/sink_port_0' not in region_out", "tmp_xs_len = (edx + 1) - dx img_ys_len = (ey", "image def transform_for_callback(batch_size, raw_outputs): output_per_box = [] fq_weights = []", "boxes[:, 3] - boxes[:, 1] + 1 tmpw = boxes[:,", "y_maxs return previous_stage_predictions def nms(prediction, threshold, iou_type): bboxes = np.c_[prediction.x_mins,", "2018-2022 Intel Corporation Licensed under the Apache License, Version 2.0", "i in range(previous_stage_predictions[0].size) if i not in pass_t] previous_stage_predictions[0].remove(removed_boxes) previous_stage_predictions[0].scores", "0] * w bb1 = boundingbox[:, 1] + reg[:, 1]", "= boundingbox[:, 1] + reg[:, 1] * h bb2 =", "np.maximum(0, dy - 1), np.maximum(0, dx - 1) y =", "tmp.shape[0] != 0: edx[tmp] = -ex[tmp] + w - 1", "tmpw[mask], tmph[mask], mask def pad(boxesA, h, w): boxes = boxesA.copy()", "except in compliance with the License. You may obtain a", "0: dy[tmp] = 2 - y[tmp] y[tmp] = np.ones_like(y[tmp]) #", "bboxA[:, 0] h = bboxA[:, 3] - bboxA[:, 1] max_side", ":] = cv2.resize(tmp, (dst_size, dst_size)) image.data = tempimg return image", "x, ex, tmpw, tmph): mask = np.ones(len(tmph)) tmp_ys_len = (edy", "region_out.replace('/sink_port_0', '') ) mv = out[0][region_out][pass_t] if iou_type: previous_stage_predictions[0], peek", "def pad(boxesA, h, w): boxes = boxesA.copy() tmph = boxes[:,", "+ reg[:, 3] * h boundingbox[:, 0:4] = np.array([bb0, bb1,", "np.ones_like(y[tmp]) # for python index from 0, while matlab from", "2:4] = bboxA[:, 0:2] + np.repeat([max_side], 2, axis=0).T return bboxA", "= x_mins previous_stage_predictions[0].y_mins = y_mins previous_stage_predictions[0].x_maxs = x_maxs previous_stage_predictions[0].y_maxs =", "= np.where(ey > h)[0] if tmp.shape[0] != 0: edy[tmp] =", "compliance with the License. You may obtain a copy of", "return previous_stage_predictions def nms(prediction, threshold, iou_type): bboxes = np.c_[prediction.x_mins, prediction.y_mins,", "prediction.scores] img = image.data bboxes = rerec(bboxes) bboxes[:, 0:4] =", "if tmp.shape[0] != 0: dy[tmp] = 2 - y[tmp] y[tmp]", "in raw_outputs[0].items(): if layer_name in fq_weights: continue if layer_name.endswith('fq_weights_1'): fq_weights.append(layer_name)", "x[tmp] x[tmp] = np.ones_like(x[tmp]) tmp = np.where(y < 1)[0] if", "np.maximum(0, ey - 1) ex = np.maximum(0, ex - 1)", "= np.where(score > 0.7)[0] removed_boxes = [i for i in", "0] + 1 numbox = boxes.shape[0] dx = np.ones(numbox) dy", "-ex[tmp] + w - 1 + tmpw[tmp] ex[tmp] = w", "as np from ...adapters import MTCNNPAdapter def calibrate_predictions(previous_stage_predictions, out, threshold,", "w - 1 + tmpw[tmp] ex[tmp] = w - 1", "= outputs_mapping['region_out'] if region_out not in out[0]: region_out = (", "1] pass_t = np.where(score > 0.7)[0] removed_boxes = [i for", "OrderedDict() for layer_name, data in raw_outputs[0].items(): if layer_name in fq_weights:", "0] tmp = np.where(ex > w)[0] if tmp.shape[0] != 0:", "+ '/sink_port_0' if '/sink_port_0' not in region_out else region_out.replace('/sink_port_0', '')", "np.where(x < 1)[0] if tmp.shape[0] != 0: dx[tmp] = 2", "y, ey, x, ex, tmpw, tmph) def rerec(bboxA): w =", "boundingbox[:, 0] + 1 h = boundingbox[:, 3] - boundingbox[:,", "score = out[0][prob_out][:, 1] pass_t = np.where(score > 0.7)[0] removed_boxes", "- max_side * 0.5 bboxA[:, 1] = bboxA[:, 1] +", "else prob_out.replace('/sink_port_0', '') score = out[0][prob_out][:, 1] pass_t = np.where(score", "boxes[:, 3:4][:, 0] tmp = np.where(ex > w)[0] if tmp.shape[0]", "edx, y, ey, x, ex, tmpw, tmph): mask = np.ones(len(tmph))", "x - 1) edy = np.maximum(0, edy - 1) edx", "w bb3 = boundingbox[:, 3] + reg[:, 3] * h", "= np.maximum(0, edy - 1) edx = np.maximum(0, edx -", "...adapters import MTCNNPAdapter def calibrate_predictions(previous_stage_predictions, out, threshold, outputs_mapping, iou_type=None): prob_out", "iou_type: previous_stage_predictions[0], peek = nms(previous_stage_predictions[0], threshold, iou_type) bboxes = np.c_[", "= out[0][region_out][pass_t] if iou_type: previous_stage_predictions[0], peek = nms(previous_stage_predictions[0], threshold, iou_type)", "raw_outputs[0].items(): if layer_name in fq_weights: continue if layer_name.endswith('fq_weights_1'): fq_weights.append(layer_name) box_outs[layer_name]", "- 1) return filter_valid(dy, edy, dx, edx, y, ey, x,", "ey, x, ex, tmpw, tmph, mask = pad(bboxes, *img.shape[:2]) bboxes", "in out[0]: prob_out = prob_out + '/sink_port_0' if '/sink_port_0' not", "= tempimg return image def transform_for_callback(batch_size, raw_outputs): output_per_box = []", "> 0, tmpw > 0)) mask = np.logical_and(mask, np.logical_and(tmp_ys_len >", "region_out = ( region_out + '/sink_port_0' if '/sink_port_0' not in", "previous_stage_predictions def nms(prediction, threshold, iou_type): bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs,", "* 0.5 - max_side * 0.5 bboxA[:, 2:4] = bboxA[:,", "and limitations under the License. \"\"\" from collections import OrderedDict", "boxes = boxesA.copy() tmph = boxes[:, 3] - boxes[:, 1]", "= rerec(bboxes) bboxes[:, 0:4] = np.fix(bboxes[:, 0:4]) dy, edy, dx,", "max_side = np.maximum(w, h).T bboxA[:, 0] = bboxA[:, 0] +", "np.maximum(0, edy - 1) edx = np.maximum(0, edx - 1)", "1)[0] if tmp.shape[0] != 0: dy[tmp] = 2 - y[tmp]", "[i for i in range(previous_stage_predictions[0].size) if i not in pass_t]", "previous_stage_predictions[0].x_mins = x_mins previous_stage_predictions[0].y_mins = y_mins previous_stage_predictions[0].x_maxs = x_maxs previous_stage_predictions[0].y_maxs", "edy, dx, edx, y, ey, x, ex, tmpw, tmph) def", "= (edx + 1) - dx img_ys_len = (ey +", "1), slice(int(dx[k]), int(edx[k]) + 1) img_ys, img_xs = slice(int(y[k]), int(ey[k])", "1 + tmph[tmp] ey[tmp] = h - 1 tmp =", "+ reg[:, 0] * w bb1 = boundingbox[:, 1] +", "prediction.scores] peek = MTCNNPAdapter.nms(bboxes, threshold, iou_type) prediction.remove([i for i in", "[] for i in range(batch_size): box_outs = OrderedDict() for layer_name,", "edx = tmpw edy = tmph x = boxes[:, 0:1][:,", "prob_out + '/sink_port_0' if '/sink_port_0' not in prob_out else prob_out.replace('/sink_port_0',", "- boxes[:, 0] + 1 numbox = boxes.shape[0] dx =", "-ey[tmp] + h - 1 + tmph[tmp] ey[tmp] = h", "MTCNNPAdapter.nms(bboxes, threshold, iou_type) prediction.remove([i for i in range(prediction.size) if i", "in region_out else region_out.replace('/sink_port_0', '') ) mv = out[0][region_out][pass_t] if", "= boundingbox[:, 3] - boundingbox[:, 1] + 1 bb0 =", "!= 0: dy[tmp] = 2 - y[tmp] y[tmp] = np.ones_like(y[tmp])", "Unless required by applicable law or agreed to in writing,", "by applicable law or agreed to in writing, software distributed", "= np.ones(len(tmph)) tmp_ys_len = (edy + 1) - dy tmp_xs_len", "return bboxA def cut_roi(image, prediction, dst_size, include_bound=True): bboxes = np.c_[prediction.x_mins,", "dx, edx, y, ey, x, ex, tmpw, tmph) def rerec(bboxA):", "slice(int(y[k]), int(ey[k]) + 1), slice(int(x[k]), int(ex[k]) + 1) tmp[tmp_ys, tmp_xs]", "+ 1 bb0 = boundingbox[:, 0] + reg[:, 0] *", "range(batch_size): box_outs = OrderedDict() for layer_name, data in raw_outputs[0].items(): if", "max_side * 0.5 bboxA[:, 1] = bboxA[:, 1] + h", "= reg.T # calibrate bounding boxes w = boundingbox[:, 2]", "1] = bboxA[:, 1] + h * 0.5 - max_side", "bboxA[:, 2:4] = bboxA[:, 0:2] + np.repeat([max_side], 2, axis=0).T return", "outputs_mapping['region_out'] if region_out not in out[0]: region_out = ( region_out", "for layer_name, data in raw_outputs[0].items(): if layer_name in fq_weights: continue", "1 dy, dx = np.maximum(0, dy - 1), np.maximum(0, dx", "np.logical_and(mask, np.logical_and(tmp_xs_len == img_xs_len, tmp_ys_len == img_ys_len)) return dy[mask], edy[mask],", "h).T bboxA[:, 0] = bboxA[:, 0] + w * 0.5", "= np.zeros((tmp_k_h, tmp_k_w, 3)) tmp_ys, tmp_xs = slice(int(dy[k]), int(edy[k]) +", "y img_xs_len = (ex + 1) - x mask =", "= boxes.shape[0] dx = np.ones(numbox) dy = np.ones(numbox) edx =", "1) ey = np.maximum(0, ey - 1) ex = np.maximum(0,", "mask = pad(bboxes, *img.shape[:2]) bboxes = bboxes[mask] numbox = bboxes.shape[0]", "bb1, bb2, bb3]).T return boundingbox def filter_valid(dy, edy, dx, edx,", "for i in range(previous_stage_predictions[0].size) if i not in pass_t] previous_stage_predictions[0].remove(removed_boxes)", "if tmp.shape[0] != 0: edx[tmp] = -ex[tmp] + w -", "out[0][region_out][pass_t] if iou_type: previous_stage_predictions[0], peek = nms(previous_stage_predictions[0], threshold, iou_type) bboxes", "express or implied. See the License for the specific language", "i not in pass_t] previous_stage_predictions[0].remove(removed_boxes) previous_stage_predictions[0].scores = score[pass_t] bboxes =", "from ...adapters import MTCNNPAdapter def calibrate_predictions(previous_stage_predictions, out, threshold, outputs_mapping, iou_type=None):", "np.logical_and(tmph > 0, tmpw > 0)) mask = np.logical_and(mask, np.logical_and(tmp_ys_len", "tmp_xs] = img[img_ys, img_xs] tempimg[k, :, :, :] = cv2.resize(tmp,", "ex[tmp] = w - 1 tmp = np.where(ey > h)[0]", "3] * h boundingbox[:, 0:4] = np.array([bb0, bb1, bb2, bb3]).T", "= (ex + 1) - x mask = np.logical_and(mask, np.logical_and(tmph", "w): boxes = boxesA.copy() tmph = boxes[:, 3] - boxes[:,", "+ np.repeat([max_side], 2, axis=0).T return bboxA def cut_roi(image, prediction, dst_size,", "+ 1) tmp[tmp_ys, tmp_xs] = img[img_ys, img_xs] tempimg[k, :, :,", "previous_stage_predictions[0].scores = score[pass_t] bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs,", "bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] img = image.data", "+ 1) img_ys, img_xs = slice(int(y[k]), int(ey[k]) + 1), slice(int(x[k]),", "dx - 1) y = np.maximum(0, y - 1) x", "] mv = mv[np.sort(peek).astype(int)] x_mins, y_mins, x_maxs, y_maxs, _ =", "Copyright (c) 2018-2022 Intel Corporation Licensed under the Apache License,", "if tmp.shape[0] != 0: dx[tmp] = 2 - x[tmp] x[tmp]", "obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required", "2] - bboxA[:, 0] h = bboxA[:, 3] - bboxA[:,", "k in range(numbox): tmp_k_h, tmp_k_w = int(tmph[k]) + int(include_bound), int(tmpw[k])", "0, while matlab from 1 dy, dx = np.maximum(0, dy", "= np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] mv =", "1) y = np.maximum(0, y - 1) x = np.maximum(0,", "= image.data bboxes = rerec(bboxes) bboxes[:, 0:4] = np.fix(bboxes[:, 0:4])", "- y img_xs_len = (ex + 1) - x mask", "boxes[:, 2] - boxes[:, 0] + 1 numbox = boxes.shape[0]", "import OrderedDict import cv2 import numpy as np from ...adapters", "1] + 1 tmpw = boxes[:, 2] - boxes[:, 0]", "bboxA def cut_roi(image, prediction, dst_size, include_bound=True): bboxes = np.c_[prediction.x_mins, prediction.y_mins,", "with the License. You may obtain a copy of the", "= slice(int(dy[k]), int(edy[k]) + 1), slice(int(dx[k]), int(edx[k]) + 1) img_ys,", "slice(int(x[k]), int(ex[k]) + 1) tmp[tmp_ys, tmp_xs] = img[img_ys, img_xs] tempimg[k,", "1) - y img_xs_len = (ex + 1) - x", "np.logical_and(mask, np.logical_and(tmp_ys_len > 0, tmp_xs_len > 0)) mask = np.logical_and(mask,", "= bboxA[:, 0:2] + np.repeat([max_side], 2, axis=0).T return bboxA def", "region_out else region_out.replace('/sink_port_0', '') ) mv = out[0][region_out][pass_t] if iou_type:", "peek = nms(previous_stage_predictions[0], threshold, iou_type) bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins,", "previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ] mv = mv[np.sort(peek).astype(int)] x_mins, y_mins, x_maxs, y_maxs,", "tmp_ys_len = (edy + 1) - dy tmp_xs_len = (edx", "box_outs[layer_name] = data else: box_outs[layer_name] = np.expand_dims(data[i], axis=0) output_per_box.append(box_outs) return", "1:2][:, 0] ex = boxes[:, 2:3][:, 0] ey = boxes[:,", "layer_name in fq_weights: continue if layer_name.endswith('fq_weights_1'): fq_weights.append(layer_name) box_outs[layer_name] = data", "y[tmp] y[tmp] = np.ones_like(y[tmp]) # for python index from 0,", "if tmp.shape[0] != 0: edy[tmp] = -ey[tmp] + h -", ":, :, :] = cv2.resize(tmp, (dst_size, dst_size)) image.data = tempimg", "specific language governing permissions and limitations under the License. \"\"\"", "edx - 1) ey = np.maximum(0, ey - 1) ex", "mv[np.sort(peek).astype(int)] x_mins, y_mins, x_maxs, y_maxs, _ = bbreg(bboxes, mv.T).T previous_stage_predictions[0].x_mins", "out[0]: prob_out = prob_out + '/sink_port_0' if '/sink_port_0' not in", "dst_size, dst_size, 3)) for k in range(numbox): tmp_k_h, tmp_k_w =", "np.where(y < 1)[0] if tmp.shape[0] != 0: dy[tmp] = 2", "applicable law or agreed to in writing, software distributed under", "range(numbox): tmp_k_h, tmp_k_w = int(tmph[k]) + int(include_bound), int(tmpw[k]) + int(include_bound)", "boundingbox[:, 1] + reg[:, 1] * h bb2 = boundingbox[:,", "# calibrate bounding boxes w = boundingbox[:, 2] - boundingbox[:,", "> 0)) mask = np.logical_and(mask, np.logical_and(img_xs_len > 0, img_ys_len >", "bboxes[:, 0:4] = np.fix(bboxes[:, 0:4]) dy, edy, dx, edx, y,", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "3] + reg[:, 3] * h boundingbox[:, 0:4] = np.array([bb0,", "= boxes[:, 3:4][:, 0] tmp = np.where(ex > w)[0] if", "tmph = boxes[:, 3] - boxes[:, 1] + 1 tmpw", "the specific language governing permissions and limitations under the License.", "np.where(ey > h)[0] if tmp.shape[0] != 0: edy[tmp] = -ey[tmp]", "1 bb0 = boundingbox[:, 0] + reg[:, 0] * w", "tmph x = boxes[:, 0:1][:, 0] y = boxes[:, 1:2][:,", "int(edx[k]) + 1) img_ys, img_xs = slice(int(y[k]), int(ey[k]) + 1),", "not in pass_t] previous_stage_predictions[0].remove(removed_boxes) previous_stage_predictions[0].scores = score[pass_t] bboxes = np.c_[", "> h)[0] if tmp.shape[0] != 0: edy[tmp] = -ey[tmp] +", "1) tmp[tmp_ys, tmp_xs] = img[img_ys, img_xs] tempimg[k, :, :, :]", "bbreg(boundingbox, reg): reg = reg.T # calibrate bounding boxes w", "return prediction, peek def bbreg(boundingbox, reg): reg = reg.T #", "x mask = np.logical_and(mask, np.logical_and(tmph > 0, tmpw > 0))", "boundingbox[:, 3] + reg[:, 3] * h boundingbox[:, 0:4] =", "governing permissions and limitations under the License. \"\"\" from collections", "tmph[tmp] ey[tmp] = h - 1 tmp = np.where(x <", "3)) for k in range(numbox): tmp_k_h, tmp_k_w = int(tmph[k]) +", "raw_outputs): output_per_box = [] fq_weights = [] for i in", "slice(int(dy[k]), int(edy[k]) + 1), slice(int(dx[k]), int(edx[k]) + 1) img_ys, img_xs", "0:4]) dy, edy, dx, edx, y, ey, x, ex, tmpw,", "y_mins, x_maxs, y_maxs, _ = bbreg(bboxes, mv.T).T previous_stage_predictions[0].x_mins = x_mins", "peek def bbreg(boundingbox, reg): reg = reg.T # calibrate bounding", "tmpw > 0)) mask = np.logical_and(mask, np.logical_and(tmp_ys_len > 0, tmp_xs_len", "1) x = np.maximum(0, x - 1) edy = np.maximum(0,", "edy[tmp] = -ey[tmp] + h - 1 + tmph[tmp] ey[tmp]", "dy - 1), np.maximum(0, dx - 1) y = np.maximum(0,", "= np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] img = image.data bboxes", "or agreed to in writing, software distributed under the License", "np.fix(bboxes[:, 0:4]) dy, edy, dx, edx, y, ey, x, ex,", "> 0, tmp_xs_len > 0)) mask = np.logical_and(mask, np.logical_and(img_xs_len >", "= (edy + 1) - dy tmp_xs_len = (edx +", "(edx + 1) - dx img_ys_len = (ey + 1)", "h = bboxA[:, 3] - bboxA[:, 1] max_side = np.maximum(w,", "1) - x mask = np.logical_and(mask, np.logical_and(tmph > 0, tmpw", "h boundingbox[:, 0:4] = np.array([bb0, bb1, bb2, bb3]).T return boundingbox", "y_maxs, _ = bbreg(bboxes, mv.T).T previous_stage_predictions[0].x_mins = x_mins previous_stage_predictions[0].y_mins =", "OF ANY KIND, either express or implied. See the License", "prob_out else prob_out.replace('/sink_port_0', '') score = out[0][prob_out][:, 1] pass_t =", "2] * w bb3 = boundingbox[:, 3] + reg[:, 3]", "2:3][:, 0] ey = boxes[:, 3:4][:, 0] tmp = np.where(ex", "dy[tmp] = 2 - y[tmp] y[tmp] = np.ones_like(y[tmp]) # for", "threshold, iou_type): bboxes = np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] peek", "dy, dx = np.maximum(0, dy - 1), np.maximum(0, dx -", "in out[0]: region_out = ( region_out + '/sink_port_0' if '/sink_port_0'", "bboxA[:, 1] max_side = np.maximum(w, h).T bboxA[:, 0] = bboxA[:,", "img_xs] tempimg[k, :, :, :] = cv2.resize(tmp, (dst_size, dst_size)) image.data", "bboxes = bboxes[mask] numbox = bboxes.shape[0] tempimg = np.zeros((numbox, dst_size,", "y = np.maximum(0, y - 1) x = np.maximum(0, x", "from collections import OrderedDict import cv2 import numpy as np", "+ h * 0.5 - max_side * 0.5 bboxA[:, 2:4]", "rerec(bboxes) bboxes[:, 0:4] = np.fix(bboxes[:, 0:4]) dy, edy, dx, edx,", "box_outs = OrderedDict() for layer_name, data in raw_outputs[0].items(): if layer_name", "2] - boxes[:, 0] + 1 numbox = boxes.shape[0] dx", "= (ey + 1) - y img_xs_len = (ex +", "out[0][prob_out][:, 1] pass_t = np.where(score > 0.7)[0] removed_boxes = [i", "+ 1 h = boundingbox[:, 3] - boundingbox[:, 1] +", "mask = np.ones(len(tmph)) tmp_ys_len = (edy + 1) - dy", "tmp = np.where(x < 1)[0] if tmp.shape[0] != 0: dx[tmp]", "in range(numbox): tmp_k_h, tmp_k_w = int(tmph[k]) + int(include_bound), int(tmpw[k]) +", "License, Version 2.0 (the \"License\"); you may not use this", "int(include_bound) tmp = np.zeros((tmp_k_h, tmp_k_w, 3)) tmp_ys, tmp_xs = slice(int(dy[k]),", "box_outs[layer_name] = data elif data.shape[0] <= i: box_outs[layer_name] = data", "Intel Corporation Licensed under the Apache License, Version 2.0 (the", "np.ones(numbox) dy = np.ones(numbox) edx = tmpw edy = tmph", "= np.zeros((numbox, dst_size, dst_size, 3)) for k in range(numbox): tmp_k_h,", "3)) tmp_ys, tmp_xs = slice(int(dy[k]), int(edy[k]) + 1), slice(int(dx[k]), int(edx[k])", "a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by", "if i not in pass_t] previous_stage_predictions[0].remove(removed_boxes) previous_stage_predictions[0].scores = score[pass_t] bboxes", "np.ones_like(x[tmp]) tmp = np.where(y < 1)[0] if tmp.shape[0] != 0:", "previous_stage_predictions[0].x_maxs = x_maxs previous_stage_predictions[0].y_maxs = y_maxs return previous_stage_predictions def nms(prediction,", "+ reg[:, 2] * w bb3 = boundingbox[:, 3] +", "bboxA[:, 1] + h * 0.5 - max_side * 0.5", "0: dx[tmp] = 2 - x[tmp] x[tmp] = np.ones_like(x[tmp]) tmp", "0: edy[tmp] = -ey[tmp] + h - 1 + tmph[tmp]", "score[pass_t] bboxes = np.c_[ previous_stage_predictions[0].x_mins, previous_stage_predictions[0].y_mins, previous_stage_predictions[0].x_maxs, previous_stage_predictions[0].y_maxs, previous_stage_predictions[0].scores ]", "dst_size)) image.data = tempimg return image def transform_for_callback(batch_size, raw_outputs): output_per_box", "License. You may obtain a copy of the License at", "np.logical_and(tmp_xs_len == img_xs_len, tmp_ys_len == img_ys_len)) return dy[mask], edy[mask], dx[mask],", "h = boundingbox[:, 3] - boundingbox[:, 1] + 1 bb0", "tmp = np.where(y < 1)[0] if tmp.shape[0] != 0: dy[tmp]", "+ 1), slice(int(x[k]), int(ex[k]) + 1) tmp[tmp_ys, tmp_xs] = img[img_ys,", "- boundingbox[:, 0] + 1 h = boundingbox[:, 3] -", "+ 1), slice(int(dx[k]), int(edx[k]) + 1) img_ys, img_xs = slice(int(y[k]),", "boxes[:, 0:1][:, 0] y = boxes[:, 1:2][:, 0] ex =", "numbox = bboxes.shape[0] tempimg = np.zeros((numbox, dst_size, dst_size, 3)) for", "bboxA[:, 0:2] + np.repeat([max_side], 2, axis=0).T return bboxA def cut_roi(image,", "import cv2 import numpy as np from ...adapters import MTCNNPAdapter", "bb0 = boundingbox[:, 0] + reg[:, 0] * w bb1", "def calibrate_predictions(previous_stage_predictions, out, threshold, outputs_mapping, iou_type=None): prob_out = outputs_mapping['probability_out'] if", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "[] fq_weights = [] for i in range(batch_size): box_outs =", "reg[:, 2] * w bb3 = boundingbox[:, 3] + reg[:,", "tmph, mask = pad(bboxes, *img.shape[:2]) bboxes = bboxes[mask] numbox =", "- 1) ex = np.maximum(0, ex - 1) return filter_valid(dy,", "def rerec(bboxA): w = bboxA[:, 2] - bboxA[:, 0] h", "rerec(bboxA): w = bboxA[:, 2] - bboxA[:, 0] h =", "img_xs = slice(int(y[k]), int(ey[k]) + 1), slice(int(x[k]), int(ex[k]) + 1)", "= img[img_ys, img_xs] tempimg[k, :, :, :] = cv2.resize(tmp, (dst_size,", "1 tmpw = boxes[:, 2] - boxes[:, 0] + 1", "np.c_[prediction.x_mins, prediction.y_mins, prediction.x_maxs, prediction.y_maxs, prediction.scores] peek = MTCNNPAdapter.nms(bboxes, threshold, iou_type)", "= boxes[:, 2:3][:, 0] ey = boxes[:, 3:4][:, 0] tmp", "python index from 0, while matlab from 1 dy, dx", "np.where(score > 0.7)[0] removed_boxes = [i for i in range(previous_stage_predictions[0].size)" ]
[ "doc result = client.crud(DocLoading.Bucket.DocOps.DELETE, key) if result[\"status\"] is False: self.log_failure(\"Doc", "scenarios with replica, persist_to and replicate_to settings \"\"\" # Atomicity.basic_ops.basic_ops.test_basic_commit", "= RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(-3600), 'Failed to advance the clock') output, _", "to execute the task\") self.task.jython_task_manager.get_task_result(task) if self.op_type == \"time_out\": self.sleep(90,", "Basic test cases with commit,rollback scenarios \"\"\" class basic_ops(ClusterSetup): def", "= self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, self.op_type, exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to,", "scenarios \"\"\" class basic_ops(ClusterSetup): def setUp(self): super(basic_ops, self).setUp() if self.num_buckets:", "ops\") # Reset active_resident_threshold to avoid further data load as", "INDEX index_1 on %s(name,age) \" \"WHERE mutated=0 USING GSI\" %", "False) gen_create = self.get_doc_generator(0, self.num_items) self.op_type = self.input.param(\"op_type\", 'create') if", "on %s(name,age) \" \"WHERE mutated=0 USING GSI\" % self.bucket_util.buckets[0].name) #", "xattr=True) if fail: self.log_failure(\"Subdoc insert failed: %s\" % fail) else:", "self.input.param(\"num_index\", 1) # Create doc_gen for loading doc_gen = doc_generator(self.key,", "com.couchbase.client.java.json import JsonObject \"\"\" Basic test cases with commit,rollback scenarios", "clock') output, _ = shell.execute_command('date') self.log.info('Date after is set forward", "on %s USING GSI\" % self.bucket_util.buckets[0].name) if num_index == 2:", "\"sysxattr-payload\"], xattr=True) if fail: self.log_failure(\"Subdoc insert failed: %s\" % fail)", "set forward {0}'.format(output)) if self.drift_behind: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(-3600), 'Failed", "process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer)", "to become ready for ops\") # Reset active_resident_threshold to avoid", "for index to become online` for index, _ in enumerate(query):", "= SDKClient([self.cluster.master], self.bucket_util.buckets[0]) query = list() query.append(\"CREATE PRIMARY INDEX index_0", "% index index = 0 state = None while index", "JsonGenerator() return json_generator.generate_docs_bigdata(end=docs_per_day, start=start, value_size=document_size) def test_basic_commit(self): \"\"\" Test transaction", "doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Close SDK Client connection client.close() self.validate_test_failure()", "staged docs to get cleared\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets,", "def get_doc_generator(self, start, end): age = range(5) first = ['james',", "self.input.param(\"drift_behind\", False) gen_create = self.get_doc_generator(0, self.num_items) self.op_type = self.input.param(\"op_type\", 'create')", "== \"time_out\": self.sleep(90, \"Wait for staged docs to get cleared\")", "INDEX index_0 on %s USING GSI\" % self.bucket_util.buckets[0].name) if num_index", "to advance the clock') output, _ = shell.execute_command('date') self.log.info('Date after", "index_0 on %s USING GSI\" % self.bucket_util.buckets[0].name) if num_index ==", "online\" % index) # Start transaction to create the doc", "doc_type=self.doc_type) return generator @staticmethod def generate_docs_bigdata(docs_per_day, start=0, document_size=1024000): json_generator =", "sync=self.sync, defer=self.defer) self.task_manager.get_task_result(task) def test_large_doc_size_commit(self): gen_create = self.generate_docs_bigdata(docs_per_day=self.num_items, document_size=self.doc_size) self.log.info(\"going", "WHERE name='index_%s'\" \\ % index index = 0 state =", "document_size=1024000): json_generator = JsonGenerator() return json_generator.generate_docs_bigdata(end=docs_per_day, start=start, value_size=document_size) def test_basic_commit(self):", "gen_create = self.get_doc_generator(0, self.num_items) self.op_type = self.input.param(\"op_type\", 'create') if self.drift_ahead:", "False) self.drift_behind = self.input.param(\"drift_behind\", False) gen_create = self.get_doc_generator(0, self.num_items) self.op_type", "= self.get_doc_generator(0, self.num_items) self.op_type = self.input.param(\"op_type\", 'create') if self.drift_ahead: shell", "self.assertTrue(shell.change_system_time(3600), 'Failed to advance the clock') output, _ = shell.execute_command('date')", "on same key _, fail = client.crud(DocLoading.Bucket.SubDocOps.INSERT, key=key, value=[\"_sysxattr\", \"sysxattr-payload\"],", "== 2: query.append(\"CREATE INDEX index_1 on %s(name,age) \" \"WHERE mutated=0", "self.cluster.master, self.num_replicas, bucket_count=self.num_buckets, bucket_type=self.bucket_type, ram_quota=self.bucket_size, storage=self.bucket_storage, eviction_policy=self.bucket_eviction_policy) else: self.create_bucket() self.sleep(10,", "transaction_timeout=200, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.task_manager.get_task_result(task) def test_large_doc_size_commit(self): gen_create =", "if fail: self.log_failure(\"Subdoc insert failed: %s\" % fail) else: self.log.info(\"Subdoc", "= JsonObject.create() template.put(\"age\", None) template.put(\"first_name\", None) template.put(\"body\", None) generator =", "replicate_to settings \"\"\" # Atomicity.basic_ops.basic_ops.test_basic_commit self.drift_ahead = self.input.param(\"drift_ahead\", False) self.drift_behind", "SDKClient from com.couchbase.client.java.json import JsonObject \"\"\" Basic test cases with", "persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going to", "\"\"\" class basic_ops(ClusterSetup): def setUp(self): super(basic_ops, self).setUp() if self.num_buckets: self.bucket_util.create_multiple_buckets(", "# Delete the created doc result = client.crud(DocLoading.Bucket.DocOps.DELETE, key) if", "end): age = range(5) first = ['james', 'sharon'] body =", "= self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Close SDK", "= range(5) first = ['james', 'sharon'] body = [''.rjust(self.doc_size -", "operation on same key _, fail = client.crud(DocLoading.Bucket.SubDocOps.INSERT, key=key, value=[\"_sysxattr\",", "for bucket to become ready for ops\") # Reset active_resident_threshold", "couchbase_helper.tuq_generators import JsonGenerator from remote.remote_util import RemoteMachineShellConnection from sdk_client3 import", "a task\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, \"create\", exp=0,", "from com.couchbase.client.java.json import JsonObject \"\"\" Basic test cases with commit,rollback", "_, fail = client.crud(DocLoading.Bucket.SubDocOps.INSERT, key=key, value=[\"_sysxattr\", \"sysxattr-payload\"], xattr=True) if fail:", "commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going to execute the task\") self.task.jython_task_manager.get_task_result(task)", "%s USING GSI\" % self.bucket_util.buckets[0].name) if num_index == 2: query.append(\"CREATE", "%s\" % result[\"error\"]) else: self.log.info(\"Document deleted\") # Re-insert same doc", "from basetestcase import ClusterSetup from couchbase_helper.documentgenerator import DocumentGenerator, doc_generator from", "sync=self.sync, defer=self.defer) self.log.info(\"going to execute the task\") self.task.jython_task_manager.get_task_result(task) if self.op_type", "key) if result[\"status\"] is False: self.log_failure(\"Doc delete failed: %s\" %", "json_generator = JsonGenerator() return json_generator.generate_docs_bigdata(end=docs_per_day, start=start, value_size=document_size) def test_basic_commit(self): \"\"\"", "task\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, \"create\", exp=0, batch_size=10,", "Start transaction to create the doc trans_task = self.task.async_load_gen_docs_atomicity( self.cluster,", "template.put(\"body\", None) generator = DocumentGenerator(self.key, template, randomize=True, age=age, first_name=first, body=body,", "age=age, first_name=first, body=body, start=start, end=end, key_size=self.key_size, doc_size=self.doc_size, doc_type=self.doc_type) return generator", "query = \"SELECT state FROM system:indexes WHERE name='index_%s'\" \\ %", "index to become online` for index, _ in enumerate(query): query", "\"SELECT state FROM system:indexes WHERE name='index_%s'\" \\ % index index", "behind {0}'.format(output)) self.log.info(\"Loading docs using AtomicityTask\") task = self.task.async_load_gen_docs_atomicity( self.cluster,", "10, 'a')] template = JsonObject.create() template.put(\"age\", None) template.put(\"first_name\", None) template.put(\"body\",", "client connection client = SDKClient([self.cluster.master], self.bucket_util.buckets[0]) query = list() query.append(\"CREATE", "shell.execute_command('date') self.log.info('Date after is set behind {0}'.format(output)) self.log.info(\"Loading docs using", "Reset active_resident_threshold to avoid further data load as DGM self.active_resident_threshold", "load as DGM self.active_resident_threshold = 0 self.log.info(\"==========Finished Basic_ops base setup========\")", "primary index on the bucket for q in query: client.cluster.query(q)", "first = ['james', 'sharon'] body = [''.rjust(self.doc_size - 10, 'a')]", "age = range(5) first = ['james', 'sharon'] body = [''.rjust(self.doc_size", "randomize=True, age=age, first_name=first, body=body, start=start, end=end, key_size=self.key_size, doc_size=self.doc_size, doc_type=self.doc_type) return", "\"\"\" Basic test cases with commit,rollback scenarios \"\"\" class basic_ops(ClusterSetup):", "output, _ = shell.execute_command('date') self.log.info('Date after is set behind {0}'.format(output))", "persist_to and replicate_to settings \"\"\" # Atomicity.basic_ops.basic_ops.test_basic_commit self.drift_ahead = self.input.param(\"drift_ahead\",", "end=end, key_size=self.key_size, doc_size=self.doc_size, doc_type=self.doc_type) return generator @staticmethod def generate_docs_bigdata(docs_per_day, start=0,", "if self.drift_behind: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(-3600), 'Failed to advance the", "DocLoading from basetestcase import ClusterSetup from couchbase_helper.documentgenerator import DocumentGenerator, doc_generator", "for staged docs to get cleared\") task = self.task.async_load_gen_docs_atomicity( self.cluster,", "forward {0}'.format(output)) if self.drift_behind: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(-3600), 'Failed to", "self.task_manager.get_task_result(task) def test_large_doc_size_commit(self): gen_create = self.generate_docs_bigdata(docs_per_day=self.num_items, document_size=self.doc_size) self.log.info(\"going to create", "result[\"error\"]) else: self.log.info(\"Document deleted\") # Re-insert same doc through transaction", "self.log.info(\"==========Finished Basic_ops base setup========\") def tearDown(self): super(basic_ops, self).tearDown() def get_doc_generator(self,", "Delete the created doc result = client.crud(DocLoading.Bucket.DocOps.DELETE, key) if result[\"status\"]", "storage=self.bucket_storage, eviction_policy=self.bucket_eviction_policy) else: self.create_bucket() self.sleep(10, \"Wait for bucket to become", "return generator @staticmethod def generate_docs_bigdata(docs_per_day, start=0, document_size=1024000): json_generator = JsonGenerator()", "\"online\": break self.sleep(1) if state != \"online\": self.log_failure(\"Index 'index_%s' not", "create a task\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, \"create\",", "persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=200, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.task_manager.get_task_result(task)", "doc_gen.next() doc_gen.reset() # Open SDK client connection client = SDKClient([self.cluster.master],", "delete failed: %s\" % result[\"error\"]) else: self.log.info(\"Document deleted\") # Re-insert", "self.log.info(\"Subdoc insert success\") # Delete the created doc result =", "import DocumentGenerator, doc_generator from couchbase_helper.tuq_generators import JsonGenerator from remote.remote_util import", "Wait for index to become online` for index, _ in", "self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, self.op_type, exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to,", "doc through transaction trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE)", "super(basic_ops, self).setUp() if self.num_buckets: self.bucket_util.create_multiple_buckets( self.cluster.master, self.num_replicas, bucket_count=self.num_buckets, bucket_type=self.bucket_type, ram_quota=self.bucket_size,", "Atomicity.basic_ops.basic_ops.test_basic_commit self.drift_ahead = self.input.param(\"drift_ahead\", False) self.drift_behind = self.input.param(\"drift_behind\", False) gen_create", "tearDown(self): super(basic_ops, self).tearDown() def get_doc_generator(self, start, end): age = range(5)", "to become online` for index, _ in enumerate(query): query =", "defer=self.defer) self.task_manager.get_task_result(task) def test_large_doc_size_commit(self): gen_create = self.generate_docs_bigdata(docs_per_day=self.num_items, document_size=self.doc_size) self.log.info(\"going to", "update_count=self.update_count, transaction_timeout=200, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.task_manager.get_task_result(task) def test_large_doc_size_commit(self): gen_create", "with commit,rollback scenarios \"\"\" class basic_ops(ClusterSetup): def setUp(self): super(basic_ops, self).setUp()", "on the bucket for q in query: client.cluster.query(q) # Wait", "Open SDK client connection client = SDKClient([self.cluster.master], self.bucket_util.buckets[0]) query =", "RemoteMachineShellConnection from sdk_client3 import SDKClient from com.couchbase.client.java.json import JsonObject \"\"\"", "advance the clock') output, _ = shell.execute_command('date') self.log.info('Date after is", "False: self.log_failure(\"Doc delete failed: %s\" % result[\"error\"]) else: self.log.info(\"Document deleted\")", "replica, persist_to and replicate_to settings \"\"\" # Atomicity.basic_ops.basic_ops.test_basic_commit self.drift_ahead =", "same key _, fail = client.crud(DocLoading.Bucket.SubDocOps.INSERT, key=key, value=[\"_sysxattr\", \"sysxattr-payload\"], xattr=True)", "self.active_resident_threshold = 0 self.log.info(\"==========Finished Basic_ops base setup========\") def tearDown(self): super(basic_ops,", "self.log.info('Date after is set forward {0}'.format(output)) if self.drift_behind: shell =", "doc_generator(self.key, 0, 1) # Get key for delete op and", "durability=self.durability_level, sync=self.sync, defer=self.defer) self.task_manager.get_task_result(task) def test_large_doc_size_commit(self): gen_create = self.generate_docs_bigdata(docs_per_day=self.num_items, document_size=self.doc_size)", "self.log.info(\"going to execute the task\") self.task.jython_task_manager.get_task_result(task) def test_MB_41944(self): num_index =", "index index = 0 state = None while index <", "\" \"WHERE mutated=0 USING GSI\" % self.bucket_util.buckets[0].name) # Create primary", "index, _ in enumerate(query): query = \"SELECT state FROM system:indexes", "= client.crud(DocLoading.Bucket.SubDocOps.INSERT, key=key, value=[\"_sysxattr\", \"sysxattr-payload\"], xattr=True) if fail: self.log_failure(\"Subdoc insert", "= self.input.param(\"drift_behind\", False) gen_create = self.get_doc_generator(0, self.num_items) self.op_type = self.input.param(\"op_type\",", "= 0 state = None while index < 30: state", "base setup========\") def tearDown(self): super(basic_ops, self).tearDown() def get_doc_generator(self, start, end):", "bucket_count=self.num_buckets, bucket_type=self.bucket_type, ram_quota=self.bucket_size, storage=self.bucket_storage, eviction_policy=self.bucket_eviction_policy) else: self.create_bucket() self.sleep(10, \"Wait for", "replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=200, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer)", "persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going", "task\") self.task.jython_task_manager.get_task_result(task) if self.op_type == \"time_out\": self.sleep(90, \"Wait for staged", "RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(-3600), 'Failed to advance the clock') output, _ =", "= 0 self.log.info(\"==========Finished Basic_ops base setup========\") def tearDown(self): super(basic_ops, self).tearDown()", "self.drift_ahead = self.input.param(\"drift_ahead\", False) self.drift_behind = self.input.param(\"drift_behind\", False) gen_create =", "state = None while index < 30: state = client.cluster.query(query)", "deleted\") # Re-insert same doc through transaction trans_task = self.task.async_load_gen_docs_atomicity(", "fail) else: self.log.info(\"Subdoc insert success\") # Delete the created doc", "first_name=first, body=body, start=start, end=end, key_size=self.key_size, doc_size=self.doc_size, doc_type=self.doc_type) return generator @staticmethod", "generator @staticmethod def generate_docs_bigdata(docs_per_day, start=0, document_size=1024000): json_generator = JsonGenerator() return", "Get key for delete op and reset the gen key,", "doc_gen for loading doc_gen = doc_generator(self.key, 0, 1) # Get", "# Create primary index on the bucket for q in", "self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Perform sub_doc operation on same", "# Start transaction to create the doc trans_task = self.task.async_load_gen_docs_atomicity(", "self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Perform sub_doc operation on", "active_resident_threshold to avoid further data load as DGM self.active_resident_threshold =", "fail = client.crud(DocLoading.Bucket.SubDocOps.INSERT, key=key, value=[\"_sysxattr\", \"sysxattr-payload\"], xattr=True) if fail: self.log_failure(\"Subdoc", "self.input.param(\"drift_ahead\", False) self.drift_behind = self.input.param(\"drift_behind\", False) gen_create = self.get_doc_generator(0, self.num_items)", "Cb_constants import DocLoading from basetestcase import ClusterSetup from couchbase_helper.documentgenerator import", "index_1 on %s(name,age) \" \"WHERE mutated=0 USING GSI\" % self.bucket_util.buckets[0].name)", "Basic_ops base setup========\") def tearDown(self): super(basic_ops, self).tearDown() def get_doc_generator(self, start,", "if result[\"status\"] is False: self.log_failure(\"Doc delete failed: %s\" % result[\"error\"])", "data load as DGM self.active_resident_threshold = 0 self.log.info(\"==========Finished Basic_ops base", "batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level,", "defer=self.defer) self.log.info(\"going to execute the task\") self.task.jython_task_manager.get_task_result(task) def test_MB_41944(self): num_index", "for delete op and reset the gen key, v =", "name='index_%s'\" \\ % index index = 0 state = None", "state != \"online\": self.log_failure(\"Index 'index_%s' not yet online\" % index)", "['james', 'sharon'] body = [''.rjust(self.doc_size - 10, 'a')] template =", "doc trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) #", "value_size=document_size) def test_basic_commit(self): \"\"\" Test transaction commit, rollback, time ahead,", "self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Close SDK Client connection client.close()", "to get cleared\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, \"create\",", "= \"SELECT state FROM system:indexes WHERE name='index_%s'\" \\ % index", "2: query.append(\"CREATE INDEX index_1 on %s(name,age) \" \"WHERE mutated=0 USING", "delete op and reset the gen key, v = doc_gen.next()", "doc_generator from couchbase_helper.tuq_generators import JsonGenerator from remote.remote_util import RemoteMachineShellConnection from", "setup========\") def tearDown(self): super(basic_ops, self).tearDown() def get_doc_generator(self, start, end): age", "docs using AtomicityTask\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, self.op_type,", "op and reset the gen key, v = doc_gen.next() doc_gen.reset()", "super(basic_ops, self).tearDown() def get_doc_generator(self, start, end): age = range(5) first", "# Wait for index to become online` for index, _", "create the doc trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE)", "reset the gen key, v = doc_gen.next() doc_gen.reset() # Open", "SDK client connection client = SDKClient([self.cluster.master], self.bucket_util.buckets[0]) query = list()", "gen_create, \"create\", exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, transaction_timeout=self.transaction_timeout,", "GSI\" % self.bucket_util.buckets[0].name) if num_index == 2: query.append(\"CREATE INDEX index_1", "batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync,", "in query: client.cluster.query(q) # Wait for index to become online`", "self.cluster, self.bucket_util.buckets, gen_create, self.op_type, exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout,", "state == \"online\": break self.sleep(1) if state != \"online\": self.log_failure(\"Index", "ram_quota=self.bucket_size, storage=self.bucket_storage, eviction_policy=self.bucket_eviction_policy) else: self.create_bucket() self.sleep(10, \"Wait for bucket to", "doc_size=self.doc_size, doc_type=self.doc_type) return generator @staticmethod def generate_docs_bigdata(docs_per_day, start=0, document_size=1024000): json_generator", "= doc_gen.next() doc_gen.reset() # Open SDK client connection client =", "self.log.info(\"going to execute the task\") self.task.jython_task_manager.get_task_result(task) if self.op_type == \"time_out\":", "start=start, end=end, key_size=self.key_size, doc_size=self.doc_size, doc_type=self.doc_type) return generator @staticmethod def generate_docs_bigdata(docs_per_day,", "\"Wait for staged docs to get cleared\") task = self.task.async_load_gen_docs_atomicity(", "self.log_failure(\"Doc delete failed: %s\" % result[\"error\"]) else: self.log.info(\"Document deleted\") #", "break self.sleep(1) if state != \"online\": self.log_failure(\"Index 'index_%s' not yet", "through transaction trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task)", "\"\"\" # Atomicity.basic_ops.basic_ops.test_basic_commit self.drift_ahead = self.input.param(\"drift_ahead\", False) self.drift_behind = self.input.param(\"drift_behind\",", "ahead, time behind scenarios with replica, persist_to and replicate_to settings", "template.put(\"first_name\", None) template.put(\"body\", None) generator = DocumentGenerator(self.key, template, randomize=True, age=age,", "Re-insert same doc through transaction trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets,", "% result[\"error\"]) else: self.log.info(\"Document deleted\") # Re-insert same doc through", "loading doc_gen = doc_generator(self.key, 0, 1) # Get key for", "execute the task\") self.task.jython_task_manager.get_task_result(task) def test_MB_41944(self): num_index = self.input.param(\"num_index\", 1)", "\"WHERE mutated=0 USING GSI\" % self.bucket_util.buckets[0].name) # Create primary index", "document_size=self.doc_size) self.log.info(\"going to create a task\") task = self.task.async_load_gen_docs_atomicity( self.cluster,", "self.log.info(\"Document deleted\") # Re-insert same doc through transaction trans_task =", "self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Perform sub_doc operation", "self.generate_docs_bigdata(docs_per_day=self.num_items, document_size=self.doc_size) self.log.info(\"going to create a task\") task = self.task.async_load_gen_docs_atomicity(", "get cleared\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, \"create\", exp=0,", "from Cb_constants import DocLoading from basetestcase import ClusterSetup from couchbase_helper.documentgenerator", "state = client.cluster.query(query) \\ .rowsAsObject()[0].get(\"state\") if state == \"online\": break", "- 10, 'a')] template = JsonObject.create() template.put(\"age\", None) template.put(\"first_name\", None)", "durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going to execute the task\") self.task.jython_task_manager.get_task_result(task) def", "self.task.jython_task_manager.get_task_result(task) def test_MB_41944(self): num_index = self.input.param(\"num_index\", 1) # Create doc_gen", "None while index < 30: state = client.cluster.query(query) \\ .rowsAsObject()[0].get(\"state\")", "Create doc_gen for loading doc_gen = doc_generator(self.key, 0, 1) #", "to avoid further data load as DGM self.active_resident_threshold = 0", "using AtomicityTask\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, self.op_type, exp=0,", "query: client.cluster.query(q) # Wait for index to become online` for", "key=key, value=[\"_sysxattr\", \"sysxattr-payload\"], xattr=True) if fail: self.log_failure(\"Subdoc insert failed: %s\"", "DGM self.active_resident_threshold = 0 self.log.info(\"==========Finished Basic_ops base setup========\") def tearDown(self):", "# Create doc_gen for loading doc_gen = doc_generator(self.key, 0, 1)", "trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Perform", "after is set forward {0}'.format(output)) if self.drift_behind: shell = RemoteMachineShellConnection(self.servers[0])", "{0}'.format(output)) if self.drift_behind: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(-3600), 'Failed to advance", "ready for ops\") # Reset active_resident_threshold to avoid further data", "FROM system:indexes WHERE name='index_%s'\" \\ % index index = 0", "generate_docs_bigdata(docs_per_day, start=0, document_size=1024000): json_generator = JsonGenerator() return json_generator.generate_docs_bigdata(end=docs_per_day, start=start, value_size=document_size)", "if self.op_type == \"time_out\": self.sleep(90, \"Wait for staged docs to", "% index) # Start transaction to create the doc trans_task", "self.op_type, exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=self.transaction_timeout,", "list() query.append(\"CREATE PRIMARY INDEX index_0 on %s USING GSI\" %", "transaction trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) #", ".rowsAsObject()[0].get(\"state\") if state == \"online\": break self.sleep(1) if state !=", "self.sleep(90, \"Wait for staged docs to get cleared\") task =", "!= \"online\": self.log_failure(\"Index 'index_%s' not yet online\" % index) #", "is False: self.log_failure(\"Doc delete failed: %s\" % result[\"error\"]) else: self.log.info(\"Document", "# Get key for delete op and reset the gen", "% self.bucket_util.buckets[0].name) if num_index == 2: query.append(\"CREATE INDEX index_1 on", "cleared\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, \"create\", exp=0, batch_size=10,", "self.create_bucket() self.sleep(10, \"Wait for bucket to become ready for ops\")", "commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.task_manager.get_task_result(task) def test_large_doc_size_commit(self): gen_create = self.generate_docs_bigdata(docs_per_day=self.num_items,", "start=0, document_size=1024000): json_generator = JsonGenerator() return json_generator.generate_docs_bigdata(end=docs_per_day, start=start, value_size=document_size) def", "= DocumentGenerator(self.key, template, randomize=True, age=age, first_name=first, body=body, start=start, end=end, key_size=self.key_size,", "doc_gen.reset() # Open SDK client connection client = SDKClient([self.cluster.master], self.bucket_util.buckets[0])", "yet online\" % index) # Start transaction to create the", "import DocLoading from basetestcase import ClusterSetup from couchbase_helper.documentgenerator import DocumentGenerator,", "and reset the gen key, v = doc_gen.next() doc_gen.reset() #", "%s(name,age) \" \"WHERE mutated=0 USING GSI\" % self.bucket_util.buckets[0].name) # Create", "= None while index < 30: state = client.cluster.query(query) \\", "gen_create, \"create\", exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count,", "num_index = self.input.param(\"num_index\", 1) # Create doc_gen for loading doc_gen", "self.log.info(\"going to create a task\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets,", "USING GSI\" % self.bucket_util.buckets[0].name) # Create primary index on the", "= JsonGenerator() return json_generator.generate_docs_bigdata(end=docs_per_day, start=start, value_size=document_size) def test_basic_commit(self): \"\"\" Test", "DocumentGenerator, doc_generator from couchbase_helper.tuq_generators import JsonGenerator from remote.remote_util import RemoteMachineShellConnection", "exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level,", "test_basic_commit(self): \"\"\" Test transaction commit, rollback, time ahead, time behind", "docs to get cleared\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create,", "= [''.rjust(self.doc_size - 10, 'a')] template = JsonObject.create() template.put(\"age\", None)", "Test transaction commit, rollback, time ahead, time behind scenarios with", "cases with commit,rollback scenarios \"\"\" class basic_ops(ClusterSetup): def setUp(self): super(basic_ops,", "timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going to", "JsonObject \"\"\" Basic test cases with commit,rollback scenarios \"\"\" class", "system:indexes WHERE name='index_%s'\" \\ % index index = 0 state", "key, v = doc_gen.next() doc_gen.reset() # Open SDK client connection", "import RemoteMachineShellConnection from sdk_client3 import SDKClient from com.couchbase.client.java.json import JsonObject", "@staticmethod def generate_docs_bigdata(docs_per_day, start=0, document_size=1024000): json_generator = JsonGenerator() return json_generator.generate_docs_bigdata(end=docs_per_day,", "= RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(3600), 'Failed to advance the clock') output, _", "result = client.crud(DocLoading.Bucket.DocOps.DELETE, key) if result[\"status\"] is False: self.log_failure(\"Doc delete", "enumerate(query): query = \"SELECT state FROM system:indexes WHERE name='index_%s'\" \\", "self.bucket_util.buckets, gen_create, self.op_type, exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries,", "update_count=self.update_count, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going to execute the", "shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(3600), 'Failed to advance the clock') output,", "transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going to execute the task\")", "process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=200, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync,", "become online` for index, _ in enumerate(query): query = \"SELECT", "process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync,", "{0}'.format(output)) self.log.info(\"Loading docs using AtomicityTask\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets,", "task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, \"create\", exp=0, batch_size=10, process_concurrency=self.process_concurrency,", "def tearDown(self): super(basic_ops, self).tearDown() def get_doc_generator(self, start, end): age =", "self.drift_behind = self.input.param(\"drift_behind\", False) gen_create = self.get_doc_generator(0, self.num_items) self.op_type =", "to execute the task\") self.task.jython_task_manager.get_task_result(task) def test_MB_41944(self): num_index = self.input.param(\"num_index\",", "def setUp(self): super(basic_ops, self).setUp() if self.num_buckets: self.bucket_util.create_multiple_buckets( self.cluster.master, self.num_replicas, bucket_count=self.num_buckets,", "rollback, time ahead, time behind scenarios with replica, persist_to and", "AtomicityTask\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, self.op_type, exp=0, batch_size=10,", "v = doc_gen.next() doc_gen.reset() # Open SDK client connection client", "SDKClient([self.cluster.master], self.bucket_util.buckets[0]) query = list() query.append(\"CREATE PRIMARY INDEX index_0 on", "gen_create = self.generate_docs_bigdata(docs_per_day=self.num_items, document_size=self.doc_size) self.log.info(\"going to create a task\") task", "doc_gen = doc_generator(self.key, 0, 1) # Get key for delete", "DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Perform sub_doc operation on same key _,", "'a')] template = JsonObject.create() template.put(\"age\", None) template.put(\"first_name\", None) template.put(\"body\", None)", "[''.rjust(self.doc_size - 10, 'a')] template = JsonObject.create() template.put(\"age\", None) template.put(\"first_name\",", "def test_basic_commit(self): \"\"\" Test transaction commit, rollback, time ahead, time", "import ClusterSetup from couchbase_helper.documentgenerator import DocumentGenerator, doc_generator from couchbase_helper.tuq_generators import", "not yet online\" % index) # Start transaction to create", "replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer)", "_ = shell.execute_command('date') self.log.info('Date after is set forward {0}'.format(output)) if", "fail: self.log_failure(\"Subdoc insert failed: %s\" % fail) else: self.log.info(\"Subdoc insert", "client.crud(DocLoading.Bucket.SubDocOps.INSERT, key=key, value=[\"_sysxattr\", \"sysxattr-payload\"], xattr=True) if fail: self.log_failure(\"Subdoc insert failed:", "failed: %s\" % fail) else: self.log.info(\"Subdoc insert success\") # Delete", "class basic_ops(ClusterSetup): def setUp(self): super(basic_ops, self).setUp() if self.num_buckets: self.bucket_util.create_multiple_buckets( self.cluster.master,", "start, end): age = range(5) first = ['james', 'sharon'] body", "for ops\") # Reset active_resident_threshold to avoid further data load", "client.crud(DocLoading.Bucket.DocOps.DELETE, key) if result[\"status\"] is False: self.log_failure(\"Doc delete failed: %s\"", "\"Wait for bucket to become ready for ops\") # Reset", "bucket to become ready for ops\") # Reset active_resident_threshold to", "online` for index, _ in enumerate(query): query = \"SELECT state", "to create a task\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create,", "if state != \"online\": self.log_failure(\"Index 'index_%s' not yet online\" %", "mutated=0 USING GSI\" % self.bucket_util.buckets[0].name) # Create primary index on", "template, randomize=True, age=age, first_name=first, body=body, start=start, end=end, key_size=self.key_size, doc_size=self.doc_size, doc_type=self.doc_type)", "_ in enumerate(query): query = \"SELECT state FROM system:indexes WHERE", "commit, rollback, time ahead, time behind scenarios with replica, persist_to", "commit,rollback scenarios \"\"\" class basic_ops(ClusterSetup): def setUp(self): super(basic_ops, self).setUp() if", "same doc through transaction trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen,", "GSI\" % self.bucket_util.buckets[0].name) # Create primary index on the bucket", "self.op_type == \"time_out\": self.sleep(90, \"Wait for staged docs to get", "template.put(\"age\", None) template.put(\"first_name\", None) template.put(\"body\", None) generator = DocumentGenerator(self.key, template,", "self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Close SDK Client connection", "body=body, start=start, end=end, key_size=self.key_size, doc_size=self.doc_size, doc_type=self.doc_type) return generator @staticmethod def", "settings \"\"\" # Atomicity.basic_ops.basic_ops.test_basic_commit self.drift_ahead = self.input.param(\"drift_ahead\", False) self.drift_behind =", "'index_%s' not yet online\" % index) # Start transaction to", "index = 0 state = None while index < 30:", "self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, \"create\", exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to,", "self.sleep(10, \"Wait for bucket to become ready for ops\") #", "self.log_failure(\"Subdoc insert failed: %s\" % fail) else: self.log.info(\"Subdoc insert success\")", "generator = DocumentGenerator(self.key, template, randomize=True, age=age, first_name=first, body=body, start=start, end=end,", "= shell.execute_command('date') self.log.info('Date after is set behind {0}'.format(output)) self.log.info(\"Loading docs", "import JsonGenerator from remote.remote_util import RemoteMachineShellConnection from sdk_client3 import SDKClient", "JsonObject.create() template.put(\"age\", None) template.put(\"first_name\", None) template.put(\"body\", None) generator = DocumentGenerator(self.key,", "shell.execute_command('date') self.log.info('Date after is set forward {0}'.format(output)) if self.drift_behind: shell", "value=[\"_sysxattr\", \"sysxattr-payload\"], xattr=True) if fail: self.log_failure(\"Subdoc insert failed: %s\" %", "ClusterSetup from couchbase_helper.documentgenerator import DocumentGenerator, doc_generator from couchbase_helper.tuq_generators import JsonGenerator", "self.num_items) self.op_type = self.input.param(\"op_type\", 'create') if self.drift_ahead: shell = RemoteMachineShellConnection(self.servers[0])", "retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=200, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.task_manager.get_task_result(task) def test_large_doc_size_commit(self):", "avoid further data load as DGM self.active_resident_threshold = 0 self.log.info(\"==========Finished", "sub_doc operation on same key _, fail = client.crud(DocLoading.Bucket.SubDocOps.INSERT, key=key,", "= self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, \"create\", exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to,", "doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Perform sub_doc operation on same key", "# Re-insert same doc through transaction trans_task = self.task.async_load_gen_docs_atomicity( self.cluster,", "self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Close SDK Client", "1) # Create doc_gen for loading doc_gen = doc_generator(self.key, 0,", "_ = shell.execute_command('date') self.log.info('Date after is set behind {0}'.format(output)) self.log.info(\"Loading", "the task\") self.task.jython_task_manager.get_task_result(task) def test_MB_41944(self): num_index = self.input.param(\"num_index\", 1) #", "'Failed to advance the clock') output, _ = shell.execute_command('date') self.log.info('Date", "<gh_stars>0 from Cb_constants import DocLoading from basetestcase import ClusterSetup from", "self.log.info('Date after is set behind {0}'.format(output)) self.log.info(\"Loading docs using AtomicityTask\")", "%s\" % fail) else: self.log.info(\"Subdoc insert success\") # Delete the", "def generate_docs_bigdata(docs_per_day, start=0, document_size=1024000): json_generator = JsonGenerator() return json_generator.generate_docs_bigdata(end=docs_per_day, start=start,", "# Atomicity.basic_ops.basic_ops.test_basic_commit self.drift_ahead = self.input.param(\"drift_ahead\", False) self.drift_behind = self.input.param(\"drift_behind\", False)", "< 30: state = client.cluster.query(query) \\ .rowsAsObject()[0].get(\"state\") if state ==", "key _, fail = client.crud(DocLoading.Bucket.SubDocOps.INSERT, key=key, value=[\"_sysxattr\", \"sysxattr-payload\"], xattr=True) if", "num_index == 2: query.append(\"CREATE INDEX index_1 on %s(name,age) \" \"WHERE", "self.log.info(\"Loading docs using AtomicityTask\") task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create,", "replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going", "else: self.log.info(\"Document deleted\") # Re-insert same doc through transaction trans_task", "USING GSI\" % self.bucket_util.buckets[0].name) if num_index == 2: query.append(\"CREATE INDEX", "gen_create, self.op_type, exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count,", "else: self.create_bucket() self.sleep(10, \"Wait for bucket to become ready for", "task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, gen_create, self.op_type, exp=0, batch_size=10, process_concurrency=self.process_concurrency,", "index on the bucket for q in query: client.cluster.query(q) #", "PRIMARY INDEX index_0 on %s USING GSI\" % self.bucket_util.buckets[0].name) if", "= self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Perform sub_doc", "clock') output, _ = shell.execute_command('date') self.log.info('Date after is set behind", "for index, _ in enumerate(query): query = \"SELECT state FROM", "sync=self.sync, defer=self.defer) self.log.info(\"going to execute the task\") self.task.jython_task_manager.get_task_result(task) def test_MB_41944(self):", "from sdk_client3 import SDKClient from com.couchbase.client.java.json import JsonObject \"\"\" Basic", "else: self.log.info(\"Subdoc insert success\") # Delete the created doc result", "self.log_failure(\"Index 'index_%s' not yet online\" % index) # Start transaction", "for loading doc_gen = doc_generator(self.key, 0, 1) # Get key", "exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=200, commit=self.transaction_commit,", "for q in query: client.cluster.query(q) # Wait for index to", "self).setUp() if self.num_buckets: self.bucket_util.create_multiple_buckets( self.cluster.master, self.num_replicas, bucket_count=self.num_buckets, bucket_type=self.bucket_type, ram_quota=self.bucket_size, storage=self.bucket_storage,", "client.cluster.query(q) # Wait for index to become online` for index,", "time behind scenarios with replica, persist_to and replicate_to settings \"\"\"", "self.num_replicas, bucket_count=self.num_buckets, bucket_type=self.bucket_type, ram_quota=self.bucket_size, storage=self.bucket_storage, eviction_policy=self.bucket_eviction_policy) else: self.create_bucket() self.sleep(10, \"Wait", "== \"online\": break self.sleep(1) if state != \"online\": self.log_failure(\"Index 'index_%s'", "as DGM self.active_resident_threshold = 0 self.log.info(\"==========Finished Basic_ops base setup========\") def", "timeout_secs=self.sdk_timeout, retries=self.sdk_retries, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going to execute", "= client.crud(DocLoading.Bucket.DocOps.DELETE, key) if result[\"status\"] is False: self.log_failure(\"Doc delete failed:", "% fail) else: self.log.info(\"Subdoc insert success\") # Delete the created", "key_size=self.key_size, doc_size=self.doc_size, doc_type=self.doc_type) return generator @staticmethod def generate_docs_bigdata(docs_per_day, start=0, document_size=1024000):", "query.append(\"CREATE PRIMARY INDEX index_0 on %s USING GSI\" % self.bucket_util.buckets[0].name)", "if num_index == 2: query.append(\"CREATE INDEX index_1 on %s(name,age) \"", "def test_large_doc_size_commit(self): gen_create = self.generate_docs_bigdata(docs_per_day=self.num_items, document_size=self.doc_size) self.log.info(\"going to create a", "if self.num_buckets: self.bucket_util.create_multiple_buckets( self.cluster.master, self.num_replicas, bucket_count=self.num_buckets, bucket_type=self.bucket_type, ram_quota=self.bucket_size, storage=self.bucket_storage, eviction_policy=self.bucket_eviction_policy)", "the doc trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task)", "JsonGenerator from remote.remote_util import RemoteMachineShellConnection from sdk_client3 import SDKClient from", "test_large_doc_size_commit(self): gen_create = self.generate_docs_bigdata(docs_per_day=self.num_items, document_size=self.doc_size) self.log.info(\"going to create a task\")", "success\") # Delete the created doc result = client.crud(DocLoading.Bucket.DocOps.DELETE, key)", "failed: %s\" % result[\"error\"]) else: self.log.info(\"Document deleted\") # Re-insert same", "query.append(\"CREATE INDEX index_1 on %s(name,age) \" \"WHERE mutated=0 USING GSI\"", "task\") self.task.jython_task_manager.get_task_result(task) def test_MB_41944(self): num_index = self.input.param(\"num_index\", 1) # Create", "= self.input.param(\"num_index\", 1) # Create doc_gen for loading doc_gen =", "is set behind {0}'.format(output)) self.log.info(\"Loading docs using AtomicityTask\") task =", "setUp(self): super(basic_ops, self).setUp() if self.num_buckets: self.bucket_util.create_multiple_buckets( self.cluster.master, self.num_replicas, bucket_count=self.num_buckets, bucket_type=self.bucket_type,", "self.task.jython_task_manager.get_task_result(task) if self.op_type == \"time_out\": self.sleep(90, \"Wait for staged docs", "\"time_out\": self.sleep(90, \"Wait for staged docs to get cleared\") task", "from couchbase_helper.documentgenerator import DocumentGenerator, doc_generator from couchbase_helper.tuq_generators import JsonGenerator from", "template = JsonObject.create() template.put(\"age\", None) template.put(\"first_name\", None) template.put(\"body\", None) generator", "exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit,", "connection client = SDKClient([self.cluster.master], self.bucket_util.buckets[0]) query = list() query.append(\"CREATE PRIMARY", "created doc result = client.crud(DocLoading.Bucket.DocOps.DELETE, key) if result[\"status\"] is False:", "= shell.execute_command('date') self.log.info('Date after is set forward {0}'.format(output)) if self.drift_behind:", "test cases with commit,rollback scenarios \"\"\" class basic_ops(ClusterSetup): def setUp(self):", "the clock') output, _ = shell.execute_command('date') self.log.info('Date after is set", "= self.input.param(\"op_type\", 'create') if self.drift_ahead: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(3600), 'Failed", "transaction commit, rollback, time ahead, time behind scenarios with replica,", "\\ % index index = 0 state = None while", "DocumentGenerator(self.key, template, randomize=True, age=age, first_name=first, body=body, start=start, end=end, key_size=self.key_size, doc_size=self.doc_size,", "None) template.put(\"body\", None) generator = DocumentGenerator(self.key, template, randomize=True, age=age, first_name=first,", "if state == \"online\": break self.sleep(1) if state != \"online\":", "insert failed: %s\" % fail) else: self.log.info(\"Subdoc insert success\") #", "self.bucket_util.buckets[0]) query = list() query.append(\"CREATE PRIMARY INDEX index_0 on %s", "'create') if self.drift_ahead: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(3600), 'Failed to advance", "durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going to execute the task\") self.task.jython_task_manager.get_task_result(task) if", "from remote.remote_util import RemoteMachineShellConnection from sdk_client3 import SDKClient from com.couchbase.client.java.json", "the task\") self.task.jython_task_manager.get_task_result(task) if self.op_type == \"time_out\": self.sleep(90, \"Wait for", "\\ .rowsAsObject()[0].get(\"state\") if state == \"online\": break self.sleep(1) if state", "self.get_doc_generator(0, self.num_items) self.op_type = self.input.param(\"op_type\", 'create') if self.drift_ahead: shell =", "Perform sub_doc operation on same key _, fail = client.crud(DocLoading.Bucket.SubDocOps.INSERT,", "body = [''.rjust(self.doc_size - 10, 'a')] template = JsonObject.create() template.put(\"age\",", "key for delete op and reset the gen key, v", "\"create\", exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=200,", "time ahead, time behind scenarios with replica, persist_to and replicate_to", "# Reset active_resident_threshold to avoid further data load as DGM", "self.task_manager.get_task_result(trans_task) # Perform sub_doc operation on same key _, fail", "return json_generator.generate_docs_bigdata(end=docs_per_day, start=start, value_size=document_size) def test_basic_commit(self): \"\"\" Test transaction commit,", "get_doc_generator(self, start, end): age = range(5) first = ['james', 'sharon']", "behind scenarios with replica, persist_to and replicate_to settings \"\"\" #", "self).tearDown() def get_doc_generator(self, start, end): age = range(5) first =", "= doc_generator(self.key, 0, 1) # Get key for delete op", "query = list() query.append(\"CREATE PRIMARY INDEX index_0 on %s USING", "self.num_buckets: self.bucket_util.create_multiple_buckets( self.cluster.master, self.num_replicas, bucket_count=self.num_buckets, bucket_type=self.bucket_type, ram_quota=self.bucket_size, storage=self.bucket_storage, eviction_policy=self.bucket_eviction_policy) else:", "test_MB_41944(self): num_index = self.input.param(\"num_index\", 1) # Create doc_gen for loading", "state FROM system:indexes WHERE name='index_%s'\" \\ % index index =", "trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen, DocLoading.Bucket.DocOps.CREATE) self.task_manager.get_task_result(trans_task) # Close", "the bucket for q in query: client.cluster.query(q) # Wait for", "is set forward {0}'.format(output)) if self.drift_behind: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(-3600),", "import SDKClient from com.couchbase.client.java.json import JsonObject \"\"\" Basic test cases", "json_generator.generate_docs_bigdata(end=docs_per_day, start=start, value_size=document_size) def test_basic_commit(self): \"\"\" Test transaction commit, rollback,", "30: state = client.cluster.query(query) \\ .rowsAsObject()[0].get(\"state\") if state == \"online\":", "0 state = None while index < 30: state =", "'sharon'] body = [''.rjust(self.doc_size - 10, 'a')] template = JsonObject.create()", "while index < 30: state = client.cluster.query(query) \\ .rowsAsObject()[0].get(\"state\") if", "self.bucket_util.create_multiple_buckets( self.cluster.master, self.num_replicas, bucket_count=self.num_buckets, bucket_type=self.bucket_type, ram_quota=self.bucket_size, storage=self.bucket_storage, eviction_policy=self.bucket_eviction_policy) else: self.create_bucket()", "self.input.param(\"op_type\", 'create') if self.drift_ahead: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(3600), 'Failed to", "\"online\": self.log_failure(\"Index 'index_%s' not yet online\" % index) # Start", "self.drift_ahead: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(3600), 'Failed to advance the clock')", "retries=self.sdk_retries, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going to execute the", "= list() query.append(\"CREATE PRIMARY INDEX index_0 on %s USING GSI\"", "= client.cluster.query(query) \\ .rowsAsObject()[0].get(\"state\") if state == \"online\": break self.sleep(1)", "self.cluster, self.bucket_util.buckets, gen_create, \"create\", exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout,", "self.op_type = self.input.param(\"op_type\", 'create') if self.drift_ahead: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(3600),", "RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(3600), 'Failed to advance the clock') output, _ =", "bucket_type=self.bucket_type, ram_quota=self.bucket_size, storage=self.bucket_storage, eviction_policy=self.bucket_eviction_policy) else: self.create_bucket() self.sleep(10, \"Wait for bucket", "bucket for q in query: client.cluster.query(q) # Wait for index", "0 self.log.info(\"==========Finished Basic_ops base setup========\") def tearDown(self): super(basic_ops, self).tearDown() def", "remote.remote_util import RemoteMachineShellConnection from sdk_client3 import SDKClient from com.couchbase.client.java.json import", "def test_MB_41944(self): num_index = self.input.param(\"num_index\", 1) # Create doc_gen for", "in enumerate(query): query = \"SELECT state FROM system:indexes WHERE name='index_%s'\"", "self.assertTrue(shell.change_system_time(-3600), 'Failed to advance the clock') output, _ = shell.execute_command('date')", "self.drift_behind: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(-3600), 'Failed to advance the clock')", "after is set behind {0}'.format(output)) self.log.info(\"Loading docs using AtomicityTask\") task", "None) generator = DocumentGenerator(self.key, template, randomize=True, age=age, first_name=first, body=body, start=start,", "index < 30: state = client.cluster.query(query) \\ .rowsAsObject()[0].get(\"state\") if state", "\"\"\" Test transaction commit, rollback, time ahead, time behind scenarios", "self.bucket_util.buckets[0].name) # Create primary index on the bucket for q", "= self.input.param(\"drift_ahead\", False) self.drift_behind = self.input.param(\"drift_behind\", False) gen_create = self.get_doc_generator(0,", "transaction to create the doc trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets,", "self.sleep(1) if state != \"online\": self.log_failure(\"Index 'index_%s' not yet online\"", "basetestcase import ClusterSetup from couchbase_helper.documentgenerator import DocumentGenerator, doc_generator from couchbase_helper.tuq_generators", "from couchbase_helper.tuq_generators import JsonGenerator from remote.remote_util import RemoteMachineShellConnection from sdk_client3", "the gen key, v = doc_gen.next() doc_gen.reset() # Open SDK", "batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=200, commit=self.transaction_commit, durability=self.durability_level,", "1) # Get key for delete op and reset the", "and replicate_to settings \"\"\" # Atomicity.basic_ops.basic_ops.test_basic_commit self.drift_ahead = self.input.param(\"drift_ahead\", False)", "self.bucket_util.buckets[0].name) if num_index == 2: query.append(\"CREATE INDEX index_1 on %s(name,age)", "result[\"status\"] is False: self.log_failure(\"Doc delete failed: %s\" % result[\"error\"]) else:", "execute the task\") self.task.jython_task_manager.get_task_result(task) if self.op_type == \"time_out\": self.sleep(90, \"Wait", "if self.drift_ahead: shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(3600), 'Failed to advance the", "with replica, persist_to and replicate_to settings \"\"\" # Atomicity.basic_ops.basic_ops.test_basic_commit self.drift_ahead", "start=start, value_size=document_size) def test_basic_commit(self): \"\"\" Test transaction commit, rollback, time", "\"create\", exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit,", "sdk_client3 import SDKClient from com.couchbase.client.java.json import JsonObject \"\"\" Basic test", "range(5) first = ['james', 'sharon'] body = [''.rjust(self.doc_size - 10,", "retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=self.transaction_timeout, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.log.info(\"going to execute", "defer=self.defer) self.log.info(\"going to execute the task\") self.task.jython_task_manager.get_task_result(task) if self.op_type ==", "eviction_policy=self.bucket_eviction_policy) else: self.create_bucket() self.sleep(10, \"Wait for bucket to become ready", "output, _ = shell.execute_command('date') self.log.info('Date after is set forward {0}'.format(output))", "q in query: client.cluster.query(q) # Wait for index to become", "further data load as DGM self.active_resident_threshold = 0 self.log.info(\"==========Finished Basic_ops", "to create the doc trans_task = self.task.async_load_gen_docs_atomicity( self.cluster, self.bucket_util.buckets, doc_gen,", "client.cluster.query(query) \\ .rowsAsObject()[0].get(\"state\") if state == \"online\": break self.sleep(1) if", "= ['james', 'sharon'] body = [''.rjust(self.doc_size - 10, 'a')] template", "become ready for ops\") # Reset active_resident_threshold to avoid further", "set behind {0}'.format(output)) self.log.info(\"Loading docs using AtomicityTask\") task = self.task.async_load_gen_docs_atomicity(", "0, 1) # Get key for delete op and reset", "# Perform sub_doc operation on same key _, fail =", "import JsonObject \"\"\" Basic test cases with commit,rollback scenarios \"\"\"", "Create primary index on the bucket for q in query:", "insert success\") # Delete the created doc result = client.crud(DocLoading.Bucket.DocOps.DELETE,", "% self.bucket_util.buckets[0].name) # Create primary index on the bucket for", "basic_ops(ClusterSetup): def setUp(self): super(basic_ops, self).setUp() if self.num_buckets: self.bucket_util.create_multiple_buckets( self.cluster.master, self.num_replicas,", "gen key, v = doc_gen.next() doc_gen.reset() # Open SDK client", "# Open SDK client connection client = SDKClient([self.cluster.master], self.bucket_util.buckets[0]) query", "self.bucket_util.buckets, gen_create, \"create\", exp=0, batch_size=10, process_concurrency=self.process_concurrency, replicate_to=self.replicate_to, persist_to=self.persist_to, timeout_secs=self.sdk_timeout, retries=self.sdk_retries,", "timeout_secs=self.sdk_timeout, retries=self.sdk_retries, update_count=self.update_count, transaction_timeout=200, commit=self.transaction_commit, durability=self.durability_level, sync=self.sync, defer=self.defer) self.task_manager.get_task_result(task) def", "client = SDKClient([self.cluster.master], self.bucket_util.buckets[0]) query = list() query.append(\"CREATE PRIMARY INDEX", "shell = RemoteMachineShellConnection(self.servers[0]) self.assertTrue(shell.change_system_time(-3600), 'Failed to advance the clock') output,", "the created doc result = client.crud(DocLoading.Bucket.DocOps.DELETE, key) if result[\"status\"] is", "couchbase_helper.documentgenerator import DocumentGenerator, doc_generator from couchbase_helper.tuq_generators import JsonGenerator from remote.remote_util", "index) # Start transaction to create the doc trans_task =", "None) template.put(\"first_name\", None) template.put(\"body\", None) generator = DocumentGenerator(self.key, template, randomize=True,", "= self.generate_docs_bigdata(docs_per_day=self.num_items, document_size=self.doc_size) self.log.info(\"going to create a task\") task =" ]
[ "range(l): relen = len(sentence.split()[i:][0]) if relen > 5: list1[i]=list1[i][::-1] return", "''' 注意 在2.x版本可以用len()得到list的长度 3.x版本就不行了 优化版本 def spin_words(sentence): # Your code", "# Your code goes here return \" \".join([x[::-1] if len(x)", "#Author:贾江超 def spin_words(sentence): list1=sentence.split() l=len(list1) for i in range(l): relen", "relen > 5: list1[i]=list1[i][::-1] return ' '.join(list1) ''' 注意 在2.x版本可以用len()得到list的长度", "relen = len(sentence.split()[i:][0]) if relen > 5: list1[i]=list1[i][::-1] return '", "5: list1[i]=list1[i][::-1] return ' '.join(list1) ''' 注意 在2.x版本可以用len()得到list的长度 3.x版本就不行了 优化版本", "len(x) >= 5 else x for x in sentence.split(\" \")])", "\".join([x[::-1] if len(x) >= 5 else x for x in", "here return \" \".join([x[::-1] if len(x) >= 5 else x", "if relen > 5: list1[i]=list1[i][::-1] return ' '.join(list1) ''' 注意", "code goes here return \" \".join([x[::-1] if len(x) >= 5", "len(sentence.split()[i:][0]) if relen > 5: list1[i]=list1[i][::-1] return ' '.join(list1) '''", "> 5: list1[i]=list1[i][::-1] return ' '.join(list1) ''' 注意 在2.x版本可以用len()得到list的长度 3.x版本就不行了", "def spin_words(sentence): # Your code goes here return \" \".join([x[::-1]", "5 else x for x in sentence.split(\" \")]) 在这里倒序字符串用切片很方便 str[::-1]", "注意 在2.x版本可以用len()得到list的长度 3.x版本就不行了 优化版本 def spin_words(sentence): # Your code goes", "python3 #-*- coding:utf-8 -*- #Author:贾江超 def spin_words(sentence): list1=sentence.split() l=len(list1) for", "#-*- coding:utf-8 -*- #Author:贾江超 def spin_words(sentence): list1=sentence.split() l=len(list1) for i", "x for x in sentence.split(\" \")]) 在这里倒序字符串用切片很方便 str[::-1] 就ok了 '''", "spin_words(sentence): list1=sentence.split() l=len(list1) for i in range(l): relen = len(sentence.split()[i:][0])", "for i in range(l): relen = len(sentence.split()[i:][0]) if relen >", "-*- #Author:贾江超 def spin_words(sentence): list1=sentence.split() l=len(list1) for i in range(l):", "list1[i]=list1[i][::-1] return ' '.join(list1) ''' 注意 在2.x版本可以用len()得到list的长度 3.x版本就不行了 优化版本 def", "3.x版本就不行了 优化版本 def spin_words(sentence): # Your code goes here return", "优化版本 def spin_words(sentence): # Your code goes here return \"", "#!/usr/bin/env python3 #-*- coding:utf-8 -*- #Author:贾江超 def spin_words(sentence): list1=sentence.split() l=len(list1)", "' '.join(list1) ''' 注意 在2.x版本可以用len()得到list的长度 3.x版本就不行了 优化版本 def spin_words(sentence): #", "coding:utf-8 -*- #Author:贾江超 def spin_words(sentence): list1=sentence.split() l=len(list1) for i in", "= len(sentence.split()[i:][0]) if relen > 5: list1[i]=list1[i][::-1] return ' '.join(list1)", "spin_words(sentence): # Your code goes here return \" \".join([x[::-1] if", "if len(x) >= 5 else x for x in sentence.split(\"", "Your code goes here return \" \".join([x[::-1] if len(x) >=", "in range(l): relen = len(sentence.split()[i:][0]) if relen > 5: list1[i]=list1[i][::-1]", "goes here return \" \".join([x[::-1] if len(x) >= 5 else", "return ' '.join(list1) ''' 注意 在2.x版本可以用len()得到list的长度 3.x版本就不行了 优化版本 def spin_words(sentence):", "l=len(list1) for i in range(l): relen = len(sentence.split()[i:][0]) if relen", "i in range(l): relen = len(sentence.split()[i:][0]) if relen > 5:", ">= 5 else x for x in sentence.split(\" \")]) 在这里倒序字符串用切片很方便", "\" \".join([x[::-1] if len(x) >= 5 else x for x", "else x for x in sentence.split(\" \")]) 在这里倒序字符串用切片很方便 str[::-1] 就ok了", "list1=sentence.split() l=len(list1) for i in range(l): relen = len(sentence.split()[i:][0]) if", "在2.x版本可以用len()得到list的长度 3.x版本就不行了 优化版本 def spin_words(sentence): # Your code goes here", "'.join(list1) ''' 注意 在2.x版本可以用len()得到list的长度 3.x版本就不行了 优化版本 def spin_words(sentence): # Your", "return \" \".join([x[::-1] if len(x) >= 5 else x for", "def spin_words(sentence): list1=sentence.split() l=len(list1) for i in range(l): relen =" ]
[ "socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.__conn = None # ---------------------------------------------------------------------------------------------------------------- def connect(self, wait_for_availability=True):", "wait_for_availability: raise ConnectionRefusedError(ex) time.sleep(0.1) def close(self): try: if self.__conn: self.__conn.close()", "break break except ConnectionError: if not wait_for_availability: raise self.close() time.sleep(0.1)", "socket... self.__socket.bind(self.__address) self.__socket.listen(NetworkSocket.__BACKLOG) self.__conn, _ = self.__socket.accept() # data... while", "2017 @author: <NAME> (<EMAIL>) A network socket abstraction, implementing ProcessComms", "0: break yield message def write(self, message, wait_for_availability=True): while True:", "time.sleep(0.1) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.connect() # ---------------------------------------------------------------------------------------------------------------- def ack(self):", "def __str__(self, *args, **kwargs): return \"NetworkSocket:{address:%s, socket:%s}\" % (self.__address, self.__socket)", "self.__socket.recv(NetworkSocket.__BUFFER_SIZE).decode() != NetworkSocket.__ACK: time.sleep(0.001) if time.time() > timeout: break break", "def write(self, message, wait_for_availability=True): while True: try: # data... self.__socket.send(message.encode())", "# ---------------------------------------------------------------------------------------------------------------- def connect(self, wait_for_availability=True): while True: try: self.__socket.connect(self.__address) break", "_ = self.__socket.accept() # data... while True: message = self.__conn.recv(NetworkSocket.__BUFFER_SIZE).decode().strip()", "---------------------------------------------------------------------------------------------------------------- def ack(self): self.__conn.send(str(NetworkSocket.__ACK).encode()) # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs):", "def ack(self): self.__conn.send(str(NetworkSocket.__ACK).encode()) # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return", "+ NetworkSocket.__TIMEOUT while self.__socket.recv(NetworkSocket.__BUFFER_SIZE).decode() != NetworkSocket.__ACK: time.sleep(0.001) if time.time() >", "# wait for ACK... timeout = time.time() + NetworkSocket.__TIMEOUT while", "\"\"\" __TIMEOUT = 4.0 # seconds __BUFFER_SIZE = 1024 #", "<reponame>south-coast-science/scs_host_cpc<gh_stars>0 \"\"\" Created on 30 May 2017 @author: <NAME> (<EMAIL>)", "self.__socket.bind(self.__address) self.__socket.listen(NetworkSocket.__BACKLOG) self.__conn, _ = self.__socket.accept() # data... while True:", "\"\"\" classdocs \"\"\" __TIMEOUT = 4.0 # seconds __BUFFER_SIZE =", "socket should have host '' \"\"\" Constructor \"\"\" self.__address =", "implementing ProcessComms \"\"\" import socket import time from scs_core.sys.process_comms import", "while True: message = self.__conn.recv(NetworkSocket.__BUFFER_SIZE).decode().strip() if len(message) == 0: break", "break except ConnectionError: if not wait_for_availability: raise self.close() time.sleep(0.1) self.__socket", "a receiving socket should have host '' \"\"\" Constructor \"\"\"", "port) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.__conn = None # ----------------------------------------------------------------------------------------------------------------", "timeout = time.time() + NetworkSocket.__TIMEOUT while self.__socket.recv(NetworkSocket.__BUFFER_SIZE).decode() != NetworkSocket.__ACK: time.sleep(0.001)", "socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.connect() # ---------------------------------------------------------------------------------------------------------------- def ack(self): self.__conn.send(str(NetworkSocket.__ACK).encode()) # ----------------------------------------------------------------------------------------------------------------", "(<EMAIL>) A network socket abstraction, implementing ProcessComms \"\"\" import socket", "port=2000): # a receiving socket should have host '' \"\"\"", "self.__address = (host, port) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.__conn =", "data... while True: message = self.__conn.recv(NetworkSocket.__BUFFER_SIZE).decode().strip() if len(message) == 0:", "__TIMEOUT = 4.0 # seconds __BUFFER_SIZE = 1024 # bytes", "if time.time() > timeout: break break except ConnectionError: if not", "host, port=2000): # a receiving socket should have host ''", "# seconds __BUFFER_SIZE = 1024 # bytes __BACKLOG = 5", "# ---------------------------------------------------------------------------------------------------------------- def read(self): # socket... self.__socket.bind(self.__address) self.__socket.listen(NetworkSocket.__BACKLOG) self.__conn, _", "pass # ---------------------------------------------------------------------------------------------------------------- def read(self): # socket... self.__socket.bind(self.__address) self.__socket.listen(NetworkSocket.__BACKLOG) self.__conn,", "---------------------------------------------------------------------------------------------------------------- def read(self): # socket... self.__socket.bind(self.__address) self.__socket.listen(NetworkSocket.__BACKLOG) self.__conn, _ =", "ConnectionRefusedError as ex: if not wait_for_availability: raise ConnectionRefusedError(ex) time.sleep(0.1) def", "# ---------------------------------------------------------------------------------------------------------------- def __init__(self, host, port=2000): # a receiving socket", "---------------------------------------------------------------------------------------------------------------- def __init__(self, host, port=2000): # a receiving socket should", "(host, port) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.__conn = None #", "message def write(self, message, wait_for_availability=True): while True: try: # data...", "= 4.0 # seconds __BUFFER_SIZE = 1024 # bytes __BACKLOG", "= self.__socket.accept() # data... while True: message = self.__conn.recv(NetworkSocket.__BUFFER_SIZE).decode().strip() if", "True: message = self.__conn.recv(NetworkSocket.__BUFFER_SIZE).decode().strip() if len(message) == 0: break yield", "__ACK = \"ACK\" # ---------------------------------------------------------------------------------------------------------------- def __init__(self, host, port=2000): #", "yield message def write(self, message, wait_for_availability=True): while True: try: #", "except ConnectionError: if not wait_for_availability: raise self.close() time.sleep(0.1) self.__socket =", "# ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"NetworkSocket:{address:%s, socket:%s}\" %", "have host '' \"\"\" Constructor \"\"\" self.__address = (host, port)", "True: try: # data... self.__socket.send(message.encode()) # wait for ACK... timeout", "30 May 2017 @author: <NAME> (<EMAIL>) A network socket abstraction,", "ConnectionError: if not wait_for_availability: raise self.close() time.sleep(0.1) self.__socket = socket.socket(family=socket.AF_INET,", "self.__conn.send(str(NetworkSocket.__ACK).encode()) # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"NetworkSocket:{address:%s, socket:%s}\"", "bytes __BACKLOG = 5 __ACK = \"ACK\" # ---------------------------------------------------------------------------------------------------------------- def", "= 1024 # bytes __BACKLOG = 5 __ACK = \"ACK\"", "# ---------------------------------------------------------------------------------------------------------------- def ack(self): self.__conn.send(str(NetworkSocket.__ACK).encode()) # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args,", "try: self.__socket.close() except RuntimeError: pass # ---------------------------------------------------------------------------------------------------------------- def read(self): #", "read(self): # socket... self.__socket.bind(self.__address) self.__socket.listen(NetworkSocket.__BACKLOG) self.__conn, _ = self.__socket.accept() #", "self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.connect() # ---------------------------------------------------------------------------------------------------------------- def ack(self): self.__conn.send(str(NetworkSocket.__ACK).encode())", "abstraction, implementing ProcessComms \"\"\" import socket import time from scs_core.sys.process_comms", "receiving socket should have host '' \"\"\" Constructor \"\"\" self.__address", "message, wait_for_availability=True): while True: try: # data... self.__socket.send(message.encode()) # wait", "__BUFFER_SIZE = 1024 # bytes __BACKLOG = 5 __ACK =", "-------------------------------------------------------------------------------------------------------------------- class NetworkSocket(ProcessComms): \"\"\" classdocs \"\"\" __TIMEOUT = 4.0 #", "ACK... timeout = time.time() + NetworkSocket.__TIMEOUT while self.__socket.recv(NetworkSocket.__BUFFER_SIZE).decode() != NetworkSocket.__ACK:", "if len(message) == 0: break yield message def write(self, message,", "= socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.connect() # ---------------------------------------------------------------------------------------------------------------- def ack(self): self.__conn.send(str(NetworkSocket.__ACK).encode()) #", "for ACK... timeout = time.time() + NetworkSocket.__TIMEOUT while self.__socket.recv(NetworkSocket.__BUFFER_SIZE).decode() !=", "RuntimeError: pass # ---------------------------------------------------------------------------------------------------------------- def read(self): # socket... self.__socket.bind(self.__address) self.__socket.listen(NetworkSocket.__BACKLOG)", "time from scs_core.sys.process_comms import ProcessComms # -------------------------------------------------------------------------------------------------------------------- class NetworkSocket(ProcessComms): \"\"\"", "wait_for_availability=True): while True: try: self.__socket.connect(self.__address) break except ConnectionRefusedError as ex:", "\"\"\" Constructor \"\"\" self.__address = (host, port) self.__socket = socket.socket(family=socket.AF_INET,", "self.__conn.recv(NetworkSocket.__BUFFER_SIZE).decode().strip() if len(message) == 0: break yield message def write(self,", "host '' \"\"\" Constructor \"\"\" self.__address = (host, port) self.__socket", "socket abstraction, implementing ProcessComms \"\"\" import socket import time from", "while True: try: # data... self.__socket.send(message.encode()) # wait for ACK...", "except RuntimeError: pass # ---------------------------------------------------------------------------------------------------------------- def read(self): # socket... self.__socket.bind(self.__address)", "\"ACK\" # ---------------------------------------------------------------------------------------------------------------- def __init__(self, host, port=2000): # a receiving", "break except ConnectionRefusedError as ex: if not wait_for_availability: raise ConnectionRefusedError(ex)", "try: self.__socket.connect(self.__address) break except ConnectionRefusedError as ex: if not wait_for_availability:", "\"\"\" self.__address = (host, port) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.__conn", "5 __ACK = \"ACK\" # ---------------------------------------------------------------------------------------------------------------- def __init__(self, host, port=2000):", "timeout: break break except ConnectionError: if not wait_for_availability: raise self.close()", "def read(self): # socket... self.__socket.bind(self.__address) self.__socket.listen(NetworkSocket.__BACKLOG) self.__conn, _ = self.__socket.accept()", "as ex: if not wait_for_availability: raise ConnectionRefusedError(ex) time.sleep(0.1) def close(self):", "NetworkSocket.__TIMEOUT while self.__socket.recv(NetworkSocket.__BUFFER_SIZE).decode() != NetworkSocket.__ACK: time.sleep(0.001) if time.time() > timeout:", "self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.__conn = None # ---------------------------------------------------------------------------------------------------------------- def", "> timeout: break break except ConnectionError: if not wait_for_availability: raise", "import ProcessComms # -------------------------------------------------------------------------------------------------------------------- class NetworkSocket(ProcessComms): \"\"\" classdocs \"\"\" __TIMEOUT", "self.__socket.listen(NetworkSocket.__BACKLOG) self.__conn, _ = self.__socket.accept() # data... while True: message", "= self.__conn.recv(NetworkSocket.__BUFFER_SIZE).decode().strip() if len(message) == 0: break yield message def", "time.time() > timeout: break break except ConnectionError: if not wait_for_availability:", "raise self.close() time.sleep(0.1) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.connect() # ----------------------------------------------------------------------------------------------------------------", "except ConnectionRefusedError as ex: if not wait_for_availability: raise ConnectionRefusedError(ex) time.sleep(0.1)", "# -------------------------------------------------------------------------------------------------------------------- class NetworkSocket(ProcessComms): \"\"\" classdocs \"\"\" __TIMEOUT = 4.0", "self.__socket.accept() # data... while True: message = self.__conn.recv(NetworkSocket.__BUFFER_SIZE).decode().strip() if len(message)", "close(self): try: if self.__conn: self.__conn.close() except RuntimeError: pass try: self.__socket.close()", "NetworkSocket(ProcessComms): \"\"\" classdocs \"\"\" __TIMEOUT = 4.0 # seconds __BUFFER_SIZE", "type=socket.SOCK_STREAM) self.__conn = None # ---------------------------------------------------------------------------------------------------------------- def connect(self, wait_for_availability=True): while", "scs_core.sys.process_comms import ProcessComms # -------------------------------------------------------------------------------------------------------------------- class NetworkSocket(ProcessComms): \"\"\" classdocs \"\"\"", "write(self, message, wait_for_availability=True): while True: try: # data... self.__socket.send(message.encode()) #", "ConnectionRefusedError(ex) time.sleep(0.1) def close(self): try: if self.__conn: self.__conn.close() except RuntimeError:", "= socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.__conn = None # ---------------------------------------------------------------------------------------------------------------- def connect(self,", "!= NetworkSocket.__ACK: time.sleep(0.001) if time.time() > timeout: break break except", "4.0 # seconds __BUFFER_SIZE = 1024 # bytes __BACKLOG =", "type=socket.SOCK_STREAM) self.connect() # ---------------------------------------------------------------------------------------------------------------- def ack(self): self.__conn.send(str(NetworkSocket.__ACK).encode()) # ---------------------------------------------------------------------------------------------------------------- def", "socket import time from scs_core.sys.process_comms import ProcessComms # -------------------------------------------------------------------------------------------------------------------- class", "self.__conn = None # ---------------------------------------------------------------------------------------------------------------- def connect(self, wait_for_availability=True): while True:", "wait_for_availability=True): while True: try: # data... self.__socket.send(message.encode()) # wait for", "if not wait_for_availability: raise self.close() time.sleep(0.1) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)", "def close(self): try: if self.__conn: self.__conn.close() except RuntimeError: pass try:", "class NetworkSocket(ProcessComms): \"\"\" classdocs \"\"\" __TIMEOUT = 4.0 # seconds", "self.__socket.close() except RuntimeError: pass # ---------------------------------------------------------------------------------------------------------------- def read(self): # socket...", "if not wait_for_availability: raise ConnectionRefusedError(ex) time.sleep(0.1) def close(self): try: if", "Constructor \"\"\" self.__address = (host, port) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)", "RuntimeError: pass try: self.__socket.close() except RuntimeError: pass # ---------------------------------------------------------------------------------------------------------------- def", "while self.__socket.recv(NetworkSocket.__BUFFER_SIZE).decode() != NetworkSocket.__ACK: time.sleep(0.001) if time.time() > timeout: break", "try: if self.__conn: self.__conn.close() except RuntimeError: pass try: self.__socket.close() except", "message = self.__conn.recv(NetworkSocket.__BUFFER_SIZE).decode().strip() if len(message) == 0: break yield message", "---------------------------------------------------------------------------------------------------------------- def connect(self, wait_for_availability=True): while True: try: self.__socket.connect(self.__address) break except", "on 30 May 2017 @author: <NAME> (<EMAIL>) A network socket", "---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"NetworkSocket:{address:%s, socket:%s}\" % (self.__address,", "self.__conn.close() except RuntimeError: pass try: self.__socket.close() except RuntimeError: pass #", "connect(self, wait_for_availability=True): while True: try: self.__socket.connect(self.__address) break except ConnectionRefusedError as", "None # ---------------------------------------------------------------------------------------------------------------- def connect(self, wait_for_availability=True): while True: try: self.__socket.connect(self.__address)", "wait_for_availability: raise self.close() time.sleep(0.1) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.connect() #", "Created on 30 May 2017 @author: <NAME> (<EMAIL>) A network", "= (host, port) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.__conn = None", "def connect(self, wait_for_availability=True): while True: try: self.__socket.connect(self.__address) break except ConnectionRefusedError", "self.close() time.sleep(0.1) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.connect() # ---------------------------------------------------------------------------------------------------------------- def", "import time from scs_core.sys.process_comms import ProcessComms # -------------------------------------------------------------------------------------------------------------------- class NetworkSocket(ProcessComms):", "__init__(self, host, port=2000): # a receiving socket should have host", "ack(self): self.__conn.send(str(NetworkSocket.__ACK).encode()) # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return \"NetworkSocket:{address:%s,", "True: try: self.__socket.connect(self.__address) break except ConnectionRefusedError as ex: if not", "raise ConnectionRefusedError(ex) time.sleep(0.1) def close(self): try: if self.__conn: self.__conn.close() except", "# socket... self.__socket.bind(self.__address) self.__socket.listen(NetworkSocket.__BACKLOG) self.__conn, _ = self.__socket.accept() # data...", "should have host '' \"\"\" Constructor \"\"\" self.__address = (host,", "# a receiving socket should have host '' \"\"\" Constructor", "ProcessComms # -------------------------------------------------------------------------------------------------------------------- class NetworkSocket(ProcessComms): \"\"\" classdocs \"\"\" __TIMEOUT =", "= time.time() + NetworkSocket.__TIMEOUT while self.__socket.recv(NetworkSocket.__BUFFER_SIZE).decode() != NetworkSocket.__ACK: time.sleep(0.001) if", "# bytes __BACKLOG = 5 __ACK = \"ACK\" # ----------------------------------------------------------------------------------------------------------------", "# data... while True: message = self.__conn.recv(NetworkSocket.__BUFFER_SIZE).decode().strip() if len(message) ==", "ProcessComms \"\"\" import socket import time from scs_core.sys.process_comms import ProcessComms", "__BACKLOG = 5 __ACK = \"ACK\" # ---------------------------------------------------------------------------------------------------------------- def __init__(self,", "pass try: self.__socket.close() except RuntimeError: pass # ---------------------------------------------------------------------------------------------------------------- def read(self):", "except RuntimeError: pass try: self.__socket.close() except RuntimeError: pass # ----------------------------------------------------------------------------------------------------------------", "try: # data... self.__socket.send(message.encode()) # wait for ACK... timeout =", "time.sleep(0.001) if time.time() > timeout: break break except ConnectionError: if", "<NAME> (<EMAIL>) A network socket abstraction, implementing ProcessComms \"\"\" import", "A network socket abstraction, implementing ProcessComms \"\"\" import socket import", "data... self.__socket.send(message.encode()) # wait for ACK... timeout = time.time() +", "May 2017 @author: <NAME> (<EMAIL>) A network socket abstraction, implementing", "time.sleep(0.1) def close(self): try: if self.__conn: self.__conn.close() except RuntimeError: pass", "= \"ACK\" # ---------------------------------------------------------------------------------------------------------------- def __init__(self, host, port=2000): # a", "ex: if not wait_for_availability: raise ConnectionRefusedError(ex) time.sleep(0.1) def close(self): try:", "self.__conn, _ = self.__socket.accept() # data... while True: message =", "len(message) == 0: break yield message def write(self, message, wait_for_availability=True):", "'' \"\"\" Constructor \"\"\" self.__address = (host, port) self.__socket =", "while True: try: self.__socket.connect(self.__address) break except ConnectionRefusedError as ex: if", "seconds __BUFFER_SIZE = 1024 # bytes __BACKLOG = 5 __ACK", "network socket abstraction, implementing ProcessComms \"\"\" import socket import time", "1024 # bytes __BACKLOG = 5 __ACK = \"ACK\" #", "self.__socket.connect(self.__address) break except ConnectionRefusedError as ex: if not wait_for_availability: raise", "= None # ---------------------------------------------------------------------------------------------------------------- def connect(self, wait_for_availability=True): while True: try:", "not wait_for_availability: raise ConnectionRefusedError(ex) time.sleep(0.1) def close(self): try: if self.__conn:", "self.connect() # ---------------------------------------------------------------------------------------------------------------- def ack(self): self.__conn.send(str(NetworkSocket.__ACK).encode()) # ---------------------------------------------------------------------------------------------------------------- def __str__(self,", "@author: <NAME> (<EMAIL>) A network socket abstraction, implementing ProcessComms \"\"\"", "= 5 __ACK = \"ACK\" # ---------------------------------------------------------------------------------------------------------------- def __init__(self, host,", "\"\"\" import socket import time from scs_core.sys.process_comms import ProcessComms #", "from scs_core.sys.process_comms import ProcessComms # -------------------------------------------------------------------------------------------------------------------- class NetworkSocket(ProcessComms): \"\"\" classdocs", "# data... self.__socket.send(message.encode()) # wait for ACK... timeout = time.time()", "classdocs \"\"\" __TIMEOUT = 4.0 # seconds __BUFFER_SIZE = 1024", "break yield message def write(self, message, wait_for_availability=True): while True: try:", "== 0: break yield message def write(self, message, wait_for_availability=True): while", "\"\"\" Created on 30 May 2017 @author: <NAME> (<EMAIL>) A", "self.__socket.send(message.encode()) # wait for ACK... timeout = time.time() + NetworkSocket.__TIMEOUT", "wait for ACK... timeout = time.time() + NetworkSocket.__TIMEOUT while self.__socket.recv(NetworkSocket.__BUFFER_SIZE).decode()", "def __init__(self, host, port=2000): # a receiving socket should have", "not wait_for_availability: raise self.close() time.sleep(0.1) self.__socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) self.connect()", "self.__conn: self.__conn.close() except RuntimeError: pass try: self.__socket.close() except RuntimeError: pass", "if self.__conn: self.__conn.close() except RuntimeError: pass try: self.__socket.close() except RuntimeError:", "import socket import time from scs_core.sys.process_comms import ProcessComms # --------------------------------------------------------------------------------------------------------------------", "time.time() + NetworkSocket.__TIMEOUT while self.__socket.recv(NetworkSocket.__BUFFER_SIZE).decode() != NetworkSocket.__ACK: time.sleep(0.001) if time.time()", "NetworkSocket.__ACK: time.sleep(0.001) if time.time() > timeout: break break except ConnectionError:" ]
[ ":type languages: list :param allow_redetect_language: Enables/disables language re-detection. :type allow_redetect_language:", "days if kwargs.get('months', 0) > 0 and (date.year, date.month) ==", "self.date_string, keep_formatting=False, settings=self._settings) return self._translated_date def _get_translated_date_with_formatting(self): if self._translated_date_with_formatting is", "string representing date and/or time in recognizable localized formats. Supports", "behavior using settings defined in :mod:`dateparser.conf.Settings`. :type settings: dict :return:", "be current day ``16`` from *current date* (which is June", "in :mod:`dateparser.conf.Settings`. :type settings: dict :return: A parser instance :raises:", "def _try_timestamp(self): return { 'date_obj': get_date_from_timestamp(self.date_string, self._settings), 'period': 'day', }", "kwargs.get('months', 0) > 0 and (date.year, date.month) == (end.year, end.month):", "if self._settings.PREFER_LANGUAGE_DATE_ORDER: self._settings.DATE_ORDER = self.language.info.get('dateorder', _order) date_obj, period = date_parser.parse(", "continue else: # If format does not include the day,", "if not date_obj['date_obj']: return False if date_obj['period'] not in ('day',", "LETTER TURNED COMMA}', # u'\\u02bb' u'\\N{ARMENIAN APOSTROPHE}', # u'\\u055a' u'\\N{LATIN", "list(available_language_map.values()), allow_redetection=True) elif languages: self.language_detector = ExactLanguages(languages=languages) else: self.language_detector =", "import regex as re from dateutil.relativedelta import relativedelta from dateparser.date_parser", "== 'month': current_period_start = current_period_start.replace(day=1) elif period == 'year': current_period_start", "in available_language_map for language in languages]): languages = [available_language_map[language] for", "dateparser.conf import apply_settings from dateparser.utils import normalize_unicode, apply_timezone_from_settings APOSTROPHE_LOOK_ALIKE_CHARS =", "if period == 'week': current_period_start \\ = current_period_start - timedelta(days=current_period_start.weekday())", "not ('%y' in date_format or '%Y' in date_format): today =", "codes, e.g. ['en', 'es']. If languages are given, it will", "datetime.datetime(2000, 3, 23, 14, 21), 'period': 'day'} \"\"\" if not(isinstance(date_string,", "date_string def get_date_from_timestamp(date_string, settings): if RE_SEARCH_TIMESTAMP.search(date_string): date_obj = datetime.fromtimestamp(int(date_string[:10])) date_obj", "current_period_start < high: yield current_period_start current_period_start += step def sanitize_date(date_string):", "dict): return False if len(date_obj) != 2: return False if", "_try_given_formats(self): if not self.date_formats: return return parse_with_formats( self._get_translated_date_with_formatting(), self.date_formats, settings=self._settings", "return {'date_obj': None, 'period': period} class _DateLanguageParser(object): DATE_FORMATS_ERROR_MESSAGE = \"Date", "list of two letters language codes, e.g. ['en', 'es']. If", "dictionary with 'period' and 'obj_date'. :returns: :class:`datetime.datetime`, dict or None", "if allow_redetect_language: self.language_detector = AutoDetectLanguage( languages if languages else list(available_language_map.values()),", "date_obj): if not isinstance(date_obj, dict): return False if len(date_obj) !=", "mapping keys to :mod:`datetime.datetime` object and *period*. For example: {'date_obj':", "RE_SANITIZE_RUSSIAN = re.compile(r'([\\W\\d])\\u0433\\.', flags=re.I | re.U) RE_SANITIZE_AMPM = re.compile(r'\\b([ap])(\\.)?m(\\.)?\\b', flags=re.DOTALL", "because the first is usually out of range. if '%d'", "unless specified using `Settings`_. >>> DateDataParser().get_date_data(u'23 March 2000, 1:21 PM", "of writing this). Hence, the level of precision is ``month``:", "at the moment of writing this). Hence, the level of", "assumed to be current day ``16`` from *current date* (which", "= date_string self.date_formats = date_formats self._translated_date = None self._translated_date_with_formatting =", "ExactLanguages from dateparser.conf import apply_settings from dateparser.utils import normalize_unicode, apply_timezone_from_settings", "raise ValueError(\"Invalid period: {}\".format(period)) if high <= low: return step", "self._try_hardcoded_formats, ): date_obj = parser() if self._is_valid_date_obj(date_obj): return date_obj else:", "if self._settings.NORMALIZE: date_string = normalize_unicode(date_string) date_string = sanitize_date(date_string) for language", "3, 23, 14, 21), 'period': 'day'} \"\"\" if not(isinstance(date_string, six.text_type)", "normalize_unicode, apply_timezone_from_settings APOSTROPHE_LOOK_ALIKE_CHARS = [ u'\\N{RIGHT SINGLE QUOTATION MARK}', #", "UTC offsets are returned in UTC time unless specified using", "today = datetime.today() date_obj = date_obj.replace(year=today.year) date_obj = apply_timezone_from_settings(date_obj, settings)", "None: self._translated_date_with_formatting = self.language.translate( self.date_string, keep_formatting=True, settings=self._settings) return self._translated_date_with_formatting def", "for date_format in date_formats: try: date_obj = datetime.strptime(date_string, date_format) except", "raise ValueError(\"Invalid argument: %s\" % arg) step = relativedelta(**kwargs) if", "[ u'\\N{RIGHT SINGLE QUOTATION MARK}', # u'\\u2019' u'\\N{MODIFIER LETTER APOSTROPHE}',", "# u'\\uff07' ] RE_NBSP = re.compile(u'\\xa0', flags=re.UNICODE) RE_SPACES = re.compile(r'\\s+')", "'week', 'day', 'hour', 'minute', 'second'] for arg in dateutil_error_prone_args: if", "not in date_obj: return False if not date_obj['date_obj']: return False", "test_period in ['microsecond', 'second', 'minute', 'hour']: if test_period == period:", "date_formats, settings): \"\"\" Parse with formats and return a dictionary", "relativedelta from dateparser.date_parser import date_parser from dateparser.freshness_date_parser import freshness_date_parser from", "list(available_language_map.values()), allow_redetection=False) def get_date_data(self, date_string, date_formats=None): \"\"\" Parse string representing", "_order) date_obj, period = date_parser.parse( self._get_translated_date(), settings=self._settings) self._settings.DATE_ORDER = _order", "arg) step = relativedelta(**kwargs) if kwargs else relativedelta(days=1) date =", "MARK}', # u'\\u2019' u'\\N{MODIFIER LETTER APOSTROPHE}', # u'\\u02bc' u'\\N{MODIFIER LETTER", "argument: %s\" % arg) step = relativedelta(**kwargs) if kwargs else", "self.language.info.get('dateorder', _order) date_obj, period = date_parser.parse( self._get_translated_date(), settings=self._settings) self._settings.DATE_ORDER =", "parser in ( self._try_timestamp, self._try_freshness_parser, self._try_given_formats, self._try_parser, self._try_hardcoded_formats, ): date_obj", "return date_obj else: return None def _try_timestamp(self): return { 'date_obj':", "else: return {'date_obj': None, 'period': period} class _DateLanguageParser(object): DATE_FORMATS_ERROR_MESSAGE =", "*current date* (which is June 16, 2015, at the moment", "given, it will not attempt to detect the language. :type", "return True class DateDataParser(object): \"\"\" Class which handles language detection,", "apply_timezone_from_settings(date_obj, settings) return date_obj def get_last_day_of_month(year, month): return calendar.monthrange(year, month)[1]", "<https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_. The parser applies formats one by one, taking into", "period = 'day' for date_format in date_formats: try: date_obj =", "into account the detected languages. :type date_formats: list :return: a", "(date.year, date.month) == (end.year, end.month): yield end def get_intersecting_periods(low, high,", "else relativedelta(days=1) date = begin while date < end: yield", "hardcoded_date_formats = [ '%B %d, %Y, %I:%M:%S %p', '%b %d,", "def _try_freshness_parser(self): return freshness_date_parser.get_date_data(self._get_translated_date(), self._settings) def _try_parser(self): _order = self._settings.DATE_ORDER", "!= 2: return False if 'date_obj' not in date_obj or", "u'\\N{MODIFIER LETTER APOSTROPHE}', # u'\\u02bc' u'\\N{MODIFIER LETTER TURNED COMMA}', #", "settings if isinstance(date_formats, six.string_types): warn(self.DATE_FORMATS_ERROR_MESSAGE, FutureWarning) date_formats = [date_formats] elif", "values can be a 'day' (default), 'week', 'month', 'year'. *Period*", "not self.date_formats: return return parse_with_formats( self._get_translated_date_with_formatting(), self.date_formats, settings=self._settings ) def", "should be list, tuple or set of strings\" def __init__(self,", "strings with no day and month information present, level of", "settings=self._settings) return self._translated_date def _get_translated_date_with_formatting(self): if self._translated_date_with_formatting is None: self._translated_date_with_formatting", "_DateLanguageParser.parse( language, date_string, date_formats, settings=self._settings) if parsed_date: parsed_date['language'] = language.shortname", "settings): if RE_SEARCH_TIMESTAMP.search(date_string): date_obj = datetime.fromtimestamp(int(date_string[:10])) date_obj = apply_timezone_from_settings(date_obj, settings)", "date strings with no day and month information present, level", "are given, it will not attempt to detect the language.", "handles edge-case when iterating months and last interval is <", "2015') {'date_obj': datetime.datetime(2015, 3, 16, 0, 0), 'period': u'month'} Similarly,", "allow_redetect_language: bool :param settings: Configure customized behavior using settings defined", "None @classmethod def parse(cls, language, date_string, date_formats=None, settings=None): instance =", "self._settings = settings available_language_map = self._get_language_loader().get_language_map() if isinstance(languages, (list, tuple,", "precision is ``month``: >>> DateDataParser().get_date_data(u'March 2015') {'date_obj': datetime.datetime(2015, 3, 16,", "None} def get_date_tuple(self, *args, **kwargs): date_tuple = collections.namedtuple('DateData', 'date_obj period", "one, taking into account the detected languages. :type date_formats: list", "ValueError: self._settings.DATE_ORDER = _order return None def _try_given_formats(self): if not", "while current_period_start < high: yield current_period_start current_period_start += step def", "None or isinstance(date_formats, (list, tuple, collections.Set))): raise TypeError(self.DATE_FORMATS_ERROR_MESSAGE) self.language =", "date and/or time in a recognizably valid format. :type date_string:", "= RE_SANITIZE_APOSTROPHE.sub(u\"'\", date_string) return date_string def get_date_from_timestamp(date_string, settings): if RE_SEARCH_TIMESTAMP.search(date_string):", "= settings available_language_map = self._get_language_loader().get_language_map() if isinstance(languages, (list, tuple, collections.Set)):", "= self.language.info.get('dateorder', _order) date_obj, period = date_parser.parse( self._get_translated_date(), settings=self._settings) self._settings.DATE_ORDER", "None def _try_given_formats(self): if not self.date_formats: return return parse_with_formats( self._get_translated_date_with_formatting(),", "tuple, collections.Set)): if all([language in available_language_map for language in languages]):", "date_format) except ValueError: continue else: # If format does not", "re.compile(r'^\\s+(\\S.*?)\\s+$') RE_SANITIZE_SKIP = re.compile(r'\\t|\\n|\\r|\\u00bb|,\\s\\u0432|\\u200e|\\xb7|\\u200f|\\u064e|\\u064f', flags=re.M) RE_SANITIZE_RUSSIAN = re.compile(r'([\\W\\d])\\u0433\\.', flags=re.I |", "languages] else: unsupported_languages = set(languages) - set(available_language_map.keys()) raise ValueError( \"Unknown", "@classmethod def parse(cls, language, date_string, date_formats=None, settings=None): instance = cls(language,", "u'day'} :raises: ValueError - Unknown Language .. note:: *Period* values", "end def get_intersecting_periods(low, high, period='day'): if period not in ['year',", "or [], self._settings) if res['date_obj']: return res if self._settings.NORMALIZE: date_string", "def _get_translated_date(self): if self._translated_date is None: self._translated_date = self.language.translate( self.date_string,", "= None self._translated_date_with_formatting = None @classmethod def parse(cls, language, date_string,", "if date_obj['period'] not in ('day', 'week', 'month', 'year'): return False", "= date_obj.replace( day=get_last_day_of_month(date_obj.year, date_obj.month)) if not ('%y' in date_format or", "return step = relativedelta(**{period + 's': 1}) current_period_start = low", "return {'date_obj': None, 'period': 'day', 'language': None} def get_date_tuple(self, *args,", "None: self._translated_date = self.language.translate( self.date_string, keep_formatting=False, settings=self._settings) return self._translated_date def", "A parser instance :raises: ValueError - Unknown Language, TypeError -", "date_string = sanitize_spaces(date_string) date_string = RE_SANITIZE_AMPM.sub(r'\\1m', date_string) date_string = RE_SANITIZE_ON.sub(r'\\1',", "Unknown Language .. note:: *Period* values can be a 'day'", "= date_obj.replace(year=today.year) date_obj = apply_timezone_from_settings(date_obj, settings) return {'date_obj': date_obj, 'period':", "u'\\N{PRIME}', # u'\\u2032' u'\\N{REVERSED PRIME}', # u'\\u2035' u'\\N{MODIFIER LETTER PRIME}',", "- set(available_language_map.keys()) raise ValueError( \"Unknown language(s): %s\" % ', '.join(map(repr,", "= [ '%B %d, %Y, %I:%M:%S %p', '%b %d, %Y", "return None def _get_translated_date(self): if self._translated_date is None: self._translated_date =", "break else: reset_arguments[test_period] = 0 current_period_start = current_period_start.replace(**reset_arguments) if period", "one by one, taking into account the detected languages. :type", "``year`` and day ``16`` and month ``6`` are from *current_date*.", ":param languages: A list of two letters language codes, e.g.", "time in a recognizably valid format. :type date_string: str|unicode :param", "current_period_start \\ = current_period_start - timedelta(days=current_period_start.weekday()) elif period == 'month':", "'day' (default), 'week', 'month', 'year'. *Period* represents the granularity of", "\"\"\" if not(isinstance(date_string, six.text_type) or isinstance(date_string, six.string_types)): raise TypeError('Input type", "'%Y' in date_format): today = datetime.today() date_obj = date_obj.replace(year=today.year) date_obj", "%B %d, %Y', '%Y-%m-%dT%H:%M:%S.%fZ' ] try: return parse_with_formats( self._get_translated_date_with_formatting(), hardcoded_date_formats,", "PRIME}', # u'\\u02b9' u'\\N{FULLWIDTH APOSTROPHE}', # u'\\uff07' ] RE_NBSP =", "date_obj or 'period' not in date_obj: return False if not", "re-detection. :type allow_redetect_language: bool :param settings: Configure customized behavior using", "translation and subsequent generic parsing of string representing date and/or", "# u'\\u2032' u'\\N{REVERSED PRIME}', # u'\\u2035' u'\\N{MODIFIER LETTER PRIME}', #", "settings=self._settings ) def _try_hardcoded_formats(self): hardcoded_date_formats = [ '%B %d, %Y,", "2: return False if 'date_obj' not in date_obj or 'period'", "which handles language detection, translation and subsequent generic parsing of", "'period': period} else: return {'date_obj': None, 'period': period} class _DateLanguageParser(object):", "else: return None def _try_timestamp(self): return { 'date_obj': get_date_from_timestamp(self.date_string, self._settings),", "localized formats. Supports parsing multiple languages and timezones. :param date_string:", "= current_period_start - timedelta(days=current_period_start.weekday()) elif period == 'month': current_period_start =", "high, period='day'): if period not in ['year', 'month', 'week', 'day',", "def _is_valid_date_obj(self, date_obj): if not isinstance(date_obj, dict): return False if", "TypeError - Languages argument must be a list \"\"\" language_loader", "high <= low: return step = relativedelta(**{period + 's': 1})", "datetime import datetime, timedelta from warnings import warn import six", "re.compile(u'|'.join(APOSTROPHE_LOOK_ALIKE_CHARS)) RE_SEARCH_TIMESTAMP = re.compile(r'^\\d{10}(?![^\\d.])') def sanitize_spaces(html_string): html_string = RE_NBSP.sub(' ',", ":raises: ValueError - Unknown Language .. note:: *Period* values can", "step = relativedelta(**{period + 's': 1}) current_period_start = low if", "list of format strings using directives as given `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_.", "no day information is present, the day is assumed to", "customized behavior using settings defined in :mod:`dateparser.conf.Settings`. :type settings: dict", "range. if '%d' not in date_format: period = 'month' date_obj", "and/or time in recognizable localized formats. Supports parsing multiple languages", "< 30 days if kwargs.get('months', 0) > 0 and (date.year,", "date_obj = date_obj.replace(year=today.year) date_obj = apply_timezone_from_settings(date_obj, settings) return {'date_obj': date_obj,", "strings using directives as given `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_. The parser applies", "0 and (date.year, date.month) == (end.year, end.month): yield end def", "parse(cls, language, date_string, date_formats=None, settings=None): instance = cls(language, date_string, date_formats,", "in date_format or '%Y' in date_format): today = datetime.today() date_obj", "recognizable localized formats. Supports parsing multiple languages and timezones. :param", "Language .. note:: *Period* values can be a 'day' (default),", "= RE_SPACES.sub(' ', html_string) html_string = RE_TRIM_SPACES.sub(r'\\1', html_string) return html_string", ":class:`datetime.datetime`, dict or None \"\"\" period = 'day' for date_format", "raise TypeError(self.DATE_FORMATS_ERROR_MESSAGE) self.language = language self.date_string = date_string self.date_formats =", "( self._try_timestamp, self._try_freshness_parser, self._try_given_formats, self._try_parser, self._try_hardcoded_formats, ): date_obj = parser()", "dict mapping keys to :mod:`datetime.datetime` object and *period*. For example:", "be a 'day' (default), 'week', 'month', 'year'. *Period* represents the", "# handles edge-case when iterating months and last interval is", "= RE_SANITIZE_ON.sub(r'\\1', date_string) date_string = RE_SANITIZE_APOSTROPHE.sub(u\"'\", date_string) return date_string def", "'obj_date'. :returns: :class:`datetime.datetime`, dict or None \"\"\" period = 'day'", "two letters language codes, e.g. ['en', 'es']. If languages are", "APOSTROPHE}', # u'\\u02bc' u'\\N{MODIFIER LETTER TURNED COMMA}', # u'\\u02bb' u'\\N{ARMENIAN", "from dateparser.utils import normalize_unicode, apply_timezone_from_settings APOSTROPHE_LOOK_ALIKE_CHARS = [ u'\\N{RIGHT SINGLE", "u'year'} Dates with time zone indications or UTC offsets are", "= re.compile(r'\\t|\\n|\\r|\\u00bb|,\\s\\u0432|\\u200e|\\xb7|\\u200f|\\u064e|\\u064f', flags=re.M) RE_SANITIZE_RUSSIAN = re.compile(r'([\\W\\d])\\u0433\\.', flags=re.I | re.U) RE_SANITIZE_AMPM", "date_string = normalize_unicode(date_string) date_string = sanitize_date(date_string) for language in self.language_detector.iterate_applicable_languages(", "'month', 'week', 'day', 'hour', 'minute', 'second'] for arg in dateutil_error_prone_args:", "_get_translated_date(self): if self._translated_date is None: self._translated_date = self.language.translate( self.date_string, keep_formatting=False,", "def _try_parser(self): _order = self._settings.DATE_ORDER try: if self._settings.PREFER_LANGUAGE_DATE_ORDER: self._settings.DATE_ORDER =", "languages are given, it will not attempt to detect the", "apply_timezone_from_settings(date_obj, settings) return {'date_obj': date_obj, 'period': period} else: return {'date_obj':", "it will not attempt to detect the language. :type languages:", "'period': u'year'} Dates with time zone indications or UTC offsets", "QUOTATION MARK}', # u'\\u2019' u'\\N{MODIFIER LETTER APOSTROPHE}', # u'\\u02bc' u'\\N{MODIFIER", "if all([language in available_language_map for language in languages]): languages =", "[date_formats] elif not (date_formats is None or isinstance(date_formats, (list, tuple,", "== period: break else: reset_arguments[test_period] = 0 current_period_start = current_period_start.replace(**reset_arguments)", "in words date_string = sanitize_spaces(date_string) date_string = RE_SANITIZE_AMPM.sub(r'\\1m', date_string) date_string", "if not ('%y' in date_format or '%Y' in date_format): today", "= RE_NBSP.sub(' ', html_string) html_string = RE_SPACES.sub(' ', html_string) html_string", "self.language.translate( self.date_string, keep_formatting=True, settings=self._settings) return self._translated_date_with_formatting def _is_valid_date_obj(self, date_obj): if", "u'\\u055a' u'\\N{LATIN SMALL LETTER SALTILLO}', # u'\\ua78c' u'\\N{PRIME}', # u'\\u2032'", "is present, the day is assumed to be current day", "(date_formats is None or isinstance(date_formats, (list, tuple, collections.Set))): raise TypeError(self.DATE_FORMATS_ERROR_MESSAGE)", "*Period* values can be a 'day' (default), 'week', 'month', 'year'.", "test_period == period: break else: reset_arguments[test_period] = 0 current_period_start =", "of strings\" def __init__(self, language, date_string, date_formats, settings=None): self._settings =", "if isinstance(current_period_start, datetime): reset_arguments = {} for test_period in ['microsecond',", "RE_NBSP = re.compile(u'\\xa0', flags=re.UNICODE) RE_SPACES = re.compile(r'\\s+') RE_TRIM_SPACES = re.compile(r'^\\s+(\\S.*?)\\s+$')", "= self.language.translate( self.date_string, keep_formatting=True, settings=self._settings) return self._translated_date_with_formatting def _is_valid_date_obj(self, date_obj):", "self.date_string = date_string self.date_formats = date_formats self._translated_date = None self._translated_date_with_formatting", "date_obj def get_last_day_of_month(year, month): return calendar.monthrange(year, month)[1] def parse_with_formats(date_string, date_formats,", "date_obj = datetime.fromtimestamp(int(date_string[:10])) date_obj = apply_timezone_from_settings(date_obj, settings) return date_obj def", "return calendar.monthrange(year, month)[1] def parse_with_formats(date_string, date_formats, settings): \"\"\" Parse with", "is ``year`` and day ``16`` and month ``6`` are from", "TypeError(\"languages argument must be a list (%r given)\" % type(languages))", "normalize_unicode(date_string) date_string = sanitize_date(date_string) for language in self.language_detector.iterate_applicable_languages( date_string, modify=True,", "and 'obj_date'. :returns: :class:`datetime.datetime`, dict or None \"\"\" period =", "in ['microsecond', 'second', 'minute', 'hour']: if test_period == period: break", "valid format. :type date_string: str|unicode :param date_formats: A list of", "date += step # handles edge-case when iterating months and", "languages = [available_language_map[language] for language in languages] else: unsupported_languages =", "in UTC time unless specified using `Settings`_. >>> DateDataParser().get_date_data(u'23 March", "and/or time. :param languages: A list of two letters language", "``month``: >>> DateDataParser().get_date_data(u'March 2015') {'date_obj': datetime.datetime(2015, 3, 16, 0, 0),", "{'date_obj': datetime.datetime(2015, 3, 16, 0, 0), 'period': u'month'} Similarly, for", "with formats and return a dictionary with 'period' and 'obj_date'.", "at %I:%M %p', '%d %B %Y %H:%M:%S', '%A, %B %d,", "parse_with_formats( self._get_translated_date_with_formatting(), hardcoded_date_formats, settings=self._settings ) except TypeError: return None def", "representing date and/or time. :param languages: A list of two", "RE_SANITIZE_SKIP = re.compile(r'\\t|\\n|\\r|\\u00bb|,\\s\\u0432|\\u200e|\\xb7|\\u200f|\\u064e|\\u064f', flags=re.M) RE_SANITIZE_RUSSIAN = re.compile(r'([\\W\\d])\\u0433\\.', flags=re.I | re.U)", "parser applies formats one by one, taking into account the", "sanitize_spaces(html_string): html_string = RE_NBSP.sub(' ', html_string) html_string = RE_SPACES.sub(' ',", "%d, %Y', '%Y-%m-%dT%H:%M:%S.%fZ' ] try: return parse_with_formats( self._get_translated_date_with_formatting(), hardcoded_date_formats, settings=self._settings", "set(available_language_map.keys()) raise ValueError( \"Unknown language(s): %s\" % ', '.join(map(repr, unsupported_languages)))", "the example below, since no day information is present, the", "the detected languages. :type date_formats: list :return: a dict mapping", "begin while date < end: yield date date += step", "language, date_string, date_formats, settings=self._settings) if parsed_date: parsed_date['language'] = language.shortname return", "and (date.year, date.month) == (end.year, end.month): yield end def get_intersecting_periods(low,", "date_string, date_formats=None): \"\"\" Parse string representing date and/or time in", "self._get_translated_date_with_formatting(), hardcoded_date_formats, settings=self._settings ) except TypeError: return None def _get_translated_date(self):", "< high: yield current_period_start current_period_start += step def sanitize_date(date_string): date_string", "to :mod:`datetime.datetime` object and *period*. For example: {'date_obj': datetime.datetime(2015, 6,", "datetime.fromtimestamp(int(date_string[:10])) date_obj = apply_timezone_from_settings(date_obj, settings) return date_obj def get_last_day_of_month(year, month):", "dateutil_error_prone_args = ['year', 'month', 'week', 'day', 'hour', 'minute', 'second'] for", "available_language_map = self._get_language_loader().get_language_map() if isinstance(languages, (list, tuple, collections.Set)): if all([language", "LETTER APOSTROPHE}', # u'\\u02bc' u'\\N{MODIFIER LETTER TURNED COMMA}', # u'\\u02bb'", "period == 'week': current_period_start \\ = current_period_start - timedelta(days=current_period_start.weekday()) elif", "raise TypeError('Input type must be str or unicode') res =", "end, **kwargs): dateutil_error_prone_args = ['year', 'month', 'week', 'day', 'hour', 'minute',", "datetime): reset_arguments = {} for test_period in ['microsecond', 'second', 'minute',", "represents the granularity of date parsed from the given string.", "if self._translated_date is None: self._translated_date = self.language.translate( self.date_string, keep_formatting=False, settings=self._settings)", "date_string self.date_formats = date_formats self._translated_date = None self._translated_date_with_formatting = None", "the language. :type languages: list :param allow_redetect_language: Enables/disables language re-detection.", "'s': 1}) current_period_start = low if isinstance(current_period_start, datetime): reset_arguments =", "date_formats self._translated_date = None self._translated_date_with_formatting = None @classmethod def parse(cls,", "parsed_date else: return {'date_obj': None, 'period': 'day', 'language': None} def", "@apply_settings def __init__(self, languages=None, allow_redetect_language=False, settings=None): self._settings = settings available_language_map", "*Period* represents the granularity of date parsed from the given", "self._settings.DATE_ORDER = _order return { 'date_obj': date_obj, 'period': period, }", "must be a list \"\"\" language_loader = None @apply_settings def", "language self.date_string = date_string self.date_formats = date_formats self._translated_date = None", ":type date_string: str|unicode :param date_formats: A list of format strings", "= collections.namedtuple('DateData', 'date_obj period language') date_data = self.get_date_data(*args, **kwargs) return", "returned in UTC time unless specified using `Settings`_. >>> DateDataParser().get_date_data(u'23", "apply_timezone_from_settings APOSTROPHE_LOOK_ALIKE_CHARS = [ u'\\N{RIGHT SINGLE QUOTATION MARK}', # u'\\u2019'", "% ', '.join(map(repr, unsupported_languages))) elif languages is not None: raise", "self._translated_date = self.language.translate( self.date_string, keep_formatting=False, settings=self._settings) return self._translated_date def _get_translated_date_with_formatting(self):", "e.g. ['en', 'es']. If languages are given, it will not", "', date_string) # remove u'г.' (Russian for year) but not", "of format strings using directives as given `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_. The", "', html_string) html_string = RE_SPACES.sub(' ', html_string) html_string = RE_TRIM_SPACES.sub(r'\\1',", "and return a dictionary with 'period' and 'obj_date'. :returns: :class:`datetime.datetime`,", "isinstance(date_obj, dict): return False if len(date_obj) != 2: return False", "date_obj = datetime.strptime(date_string, date_format) except ValueError: continue else: # If", "format. :type date_string: str|unicode :param date_formats: A list of format", "for arg in dateutil_error_prone_args: if arg in kwargs: raise ValueError(\"Invalid", "= current_period_start.replace(month=1, day=1) while current_period_start < high: yield current_period_start current_period_start", "reset_arguments = {} for test_period in ['microsecond', 'second', 'minute', 'hour']:", "isinstance(date_formats, (list, tuple, collections.Set))): raise TypeError(self.DATE_FORMATS_ERROR_MESSAGE) self.language = language self.date_string", "not date_obj['date_obj']: return False if date_obj['period'] not in ('day', 'week',", "'day' for date_format in date_formats: try: date_obj = datetime.strptime(date_string, date_format)", "'period': 'day'} \"\"\" if not(isinstance(date_string, six.text_type) or isinstance(date_string, six.string_types)): raise", "% type(languages)) if allow_redetect_language: self.language_detector = AutoDetectLanguage( languages if languages", "['en', 'es']. If languages are given, it will not attempt", "LETTER PRIME}', # u'\\u02b9' u'\\N{FULLWIDTH APOSTROPHE}', # u'\\uff07' ] RE_NBSP", "if res['date_obj']: return res if self._settings.NORMALIZE: date_string = normalize_unicode(date_string) date_string", "| re.I) RE_SANITIZE_ON = re.compile(r'^.*?on:\\s+(.*)') RE_SANITIZE_APOSTROPHE = re.compile(u'|'.join(APOSTROPHE_LOOK_ALIKE_CHARS)) RE_SEARCH_TIMESTAMP =", "AutoDetectLanguage( list(available_language_map.values()), allow_redetection=False) def get_date_data(self, date_string, date_formats=None): \"\"\" Parse string", "self._settings) if res['date_obj']: return res if self._settings.NORMALIZE: date_string = normalize_unicode(date_string)", "'%A, %B %d, %Y', '%Y-%m-%dT%H:%M:%S.%fZ' ] try: return parse_with_formats( self._get_translated_date_with_formatting(),", "are returned in UTC time unless specified using `Settings`_. >>>", "*current_date*. >>> DateDataParser().get_date_data(u'2014') {'date_obj': datetime.datetime(2014, 6, 16, 0, 0), 'period':", "For example: {'date_obj': datetime.datetime(2015, 6, 1, 0, 0), 'period': u'day'}", "interval is < 30 days if kwargs.get('months', 0) > 0", "date date += step # handles edge-case when iterating months", "datetime.datetime(2015, 6, 1, 0, 0), 'period': u'day'} :raises: ValueError -", "1:21 PM CET') {'date_obj': datetime.datetime(2000, 3, 23, 14, 21), 'period':", "_order return None def _try_given_formats(self): if not self.date_formats: return return", "'minute', 'second'] for arg in dateutil_error_prone_args: if arg in kwargs:", "list :param allow_redetect_language: Enables/disables language re-detection. :type allow_redetect_language: bool :param", "parsed_date = _DateLanguageParser.parse( language, date_string, date_formats, settings=self._settings) if parsed_date: parsed_date['language']", "parse_with_formats(date_string, date_formats, settings): \"\"\" Parse with formats and return a", "def _parse(self): for parser in ( self._try_timestamp, self._try_freshness_parser, self._try_given_formats, self._try_parser,", "date_formats, settings=self._settings) if parsed_date: parsed_date['language'] = language.shortname return parsed_date else:", "1}) current_period_start = low if isinstance(current_period_start, datetime): reset_arguments = {}", "self._translated_date = None self._translated_date_with_formatting = None @classmethod def parse(cls, language,", "day of the month # instead of first, because the", "string representing date and/or time. :param languages: A list of", "no day and month information present, level of precision is", "six.string_types)): raise TypeError('Input type must be str or unicode') res", "AutoDetectLanguage, ExactLanguages from dateparser.conf import apply_settings from dateparser.utils import normalize_unicode,", "date_parser from dateparser.freshness_date_parser import freshness_date_parser from dateparser.languages.loader import LanguageDataLoader from", "get_date_data(self, date_string, date_formats=None): \"\"\" Parse string representing date and/or time", "self.get_date_data(*args, **kwargs) return date_tuple(**date_data) @classmethod def _get_language_loader(cls): if not cls.language_loader:", "# u'\\ua78c' u'\\N{PRIME}', # u'\\u2032' u'\\N{REVERSED PRIME}', # u'\\u2035' u'\\N{MODIFIER", "for parser in ( self._try_timestamp, self._try_freshness_parser, self._try_given_formats, self._try_parser, self._try_hardcoded_formats, ):", "from dateparser.conf import apply_settings from dateparser.utils import normalize_unicode, apply_timezone_from_settings APOSTROPHE_LOOK_ALIKE_CHARS", "date and/or time in recognizable localized formats. Supports parsing multiple", "specified using `Settings`_. >>> DateDataParser().get_date_data(u'23 March 2000, 1:21 PM CET')", "isinstance(date_string, six.string_types)): raise TypeError('Input type must be str or unicode')", "def _try_hardcoded_formats(self): hardcoded_date_formats = [ '%B %d, %Y, %I:%M:%S %p',", "def parse(cls, language, date_string, date_formats=None, settings=None): instance = cls(language, date_string,", "'%d' not in date_format: period = 'month' date_obj = date_obj.replace(", "elif languages is not None: raise TypeError(\"languages argument must be", "of the month # instead of first, because the first", "and timezones. :param date_string: A string representing date and/or time", "] RE_NBSP = re.compile(u'\\xa0', flags=re.UNICODE) RE_SPACES = re.compile(r'\\s+') RE_TRIM_SPACES =", "six.string_types): warn(self.DATE_FORMATS_ERROR_MESSAGE, FutureWarning) date_formats = [date_formats] elif not (date_formats is", ":mod:`dateparser.conf.Settings`. :type settings: dict :return: A parser instance :raises: ValueError", "example: {'date_obj': datetime.datetime(2015, 6, 1, 0, 0), 'period': u'day'} :raises:", "SMALL LETTER SALTILLO}', # u'\\ua78c' u'\\N{PRIME}', # u'\\u2032' u'\\N{REVERSED PRIME}',", "u'\\N{ARMENIAN APOSTROPHE}', # u'\\u055a' u'\\N{LATIN SMALL LETTER SALTILLO}', # u'\\ua78c'", "'week', 'month', 'year'. *Period* represents the granularity of date parsed", "language_loader = None @apply_settings def __init__(self, languages=None, allow_redetect_language=False, settings=None): self._settings", "return False if not date_obj['date_obj']: return False if date_obj['period'] not", "return parse_with_formats( self._get_translated_date_with_formatting(), self.date_formats, settings=self._settings ) def _try_hardcoded_formats(self): hardcoded_date_formats =", "re.U) RE_SANITIZE_AMPM = re.compile(r'\\b([ap])(\\.)?m(\\.)?\\b', flags=re.DOTALL | re.I) RE_SANITIZE_ON = re.compile(r'^.*?on:\\s+(.*)')", "is < 30 days if kwargs.get('months', 0) > 0 and", "directives as given `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_. The parser applies formats one", "return date_obj def get_last_day_of_month(year, month): return calendar.monthrange(year, month)[1] def parse_with_formats(date_string,", "period='day'): if period not in ['year', 'month', 'week', 'day', 'hour',", "current_period_start current_period_start += step def sanitize_date(date_string): date_string = RE_SANITIZE_SKIP.sub(' ',", "re.compile(r'^\\d{10}(?![^\\d.])') def sanitize_spaces(html_string): html_string = RE_NBSP.sub(' ', html_string) html_string =", "if parsed_date: parsed_date['language'] = language.shortname return parsed_date else: return {'date_obj':", "(%r given)\" % type(languages)) if allow_redetect_language: self.language_detector = AutoDetectLanguage( languages", "date.month) == (end.year, end.month): yield end def get_intersecting_periods(low, high, period='day'):", "Enables/disables language re-detection. :type allow_redetect_language: bool :param settings: Configure customized", "dateparser.freshness_date_parser import freshness_date_parser from dateparser.languages.loader import LanguageDataLoader from dateparser.languages.detection import", "'day'} \"\"\" if not(isinstance(date_string, six.text_type) or isinstance(date_string, six.string_types)): raise TypeError('Input", "'week', 'day', 'hour', 'minute', 'second', 'microsecond']: raise ValueError(\"Invalid period: {}\".format(period))", "unsupported_languages))) elif languages is not None: raise TypeError(\"languages argument must", "a list (%r given)\" % type(languages)) if allow_redetect_language: self.language_detector =", "if kwargs else relativedelta(days=1) date = begin while date <", "_get_translated_date_with_formatting(self): if self._translated_date_with_formatting is None: self._translated_date_with_formatting = self.language.translate( self.date_string, keep_formatting=True,", "| re.U) RE_SANITIZE_AMPM = re.compile(r'\\b([ap])(\\.)?m(\\.)?\\b', flags=re.DOTALL | re.I) RE_SANITIZE_ON =", "date_formats: try: date_obj = datetime.strptime(date_string, date_format) except ValueError: continue else:", "parsing multiple languages and timezones. :param date_string: A string representing", "datetime, timedelta from warnings import warn import six import regex", "'period' not in date_obj: return False if not date_obj['date_obj']: return", "languages]): languages = [available_language_map[language] for language in languages] else: unsupported_languages", "keep_formatting=False, settings=self._settings) return self._translated_date def _get_translated_date_with_formatting(self): if self._translated_date_with_formatting is None:", "RE_SANITIZE_AMPM = re.compile(r'\\b([ap])(\\.)?m(\\.)?\\b', flags=re.DOTALL | re.I) RE_SANITIZE_ON = re.compile(r'^.*?on:\\s+(.*)') RE_SANITIZE_APOSTROPHE", "'es']. If languages are given, it will not attempt to", "for language in self.language_detector.iterate_applicable_languages( date_string, modify=True, settings=self._settings): parsed_date = _DateLanguageParser.parse(", "by one, taking into account the detected languages. :type date_formats:", "defined in :mod:`dateparser.conf.Settings`. :type settings: dict :return: A parser instance", "yield current_period_start current_period_start += step def sanitize_date(date_string): date_string = RE_SANITIZE_SKIP.sub('", "the given string. In the example below, since no day", "date_formats or [], self._settings) if res['date_obj']: return res if self._settings.NORMALIZE:", "self._translated_date is None: self._translated_date = self.language.translate( self.date_string, keep_formatting=False, settings=self._settings) return", "will not attempt to detect the language. :type languages: list", "languages: A list of two letters language codes, e.g. ['en',", "is None or isinstance(date_formats, (list, tuple, collections.Set))): raise TypeError(self.DATE_FORMATS_ERROR_MESSAGE) self.language", "{'date_obj': datetime.datetime(2000, 3, 23, 14, 21), 'period': 'day'} \"\"\" if", "apply_settings from dateparser.utils import normalize_unicode, apply_timezone_from_settings APOSTROPHE_LOOK_ALIKE_CHARS = [ u'\\N{RIGHT", "u'\\u02b9' u'\\N{FULLWIDTH APOSTROPHE}', # u'\\uff07' ] RE_NBSP = re.compile(u'\\xa0', flags=re.UNICODE)", "from dateparser.freshness_date_parser import freshness_date_parser from dateparser.languages.loader import LanguageDataLoader from dateparser.languages.detection", "(default), 'week', 'month', 'year'. *Period* represents the granularity of date", "\"\"\" language_loader = None @apply_settings def __init__(self, languages=None, allow_redetect_language=False, settings=None):", "and *period*. For example: {'date_obj': datetime.datetime(2015, 6, 1, 0, 0),", "present, level of precision is ``year`` and day ``16`` and", "u'\\N{MODIFIER LETTER PRIME}', # u'\\u02b9' u'\\N{FULLWIDTH APOSTROPHE}', # u'\\uff07' ]", "date_obj = apply_timezone_from_settings(date_obj, settings) return date_obj def get_last_day_of_month(year, month): return", "False if date_obj['period'] not in ('day', 'week', 'month', 'year'): return", "def get_date_data(self, date_string, date_formats=None): \"\"\" Parse string representing date and/or", "None \"\"\" period = 'day' for date_format in date_formats: try:", "date_format in date_formats: try: date_obj = datetime.strptime(date_string, date_format) except ValueError:", "except ValueError: self._settings.DATE_ORDER = _order return None def _try_given_formats(self): if", ":param date_formats: A list of format strings using directives as", "u'\\u02bc' u'\\N{MODIFIER LETTER TURNED COMMA}', # u'\\u02bb' u'\\N{ARMENIAN APOSTROPHE}', #", "# u'\\u02b9' u'\\N{FULLWIDTH APOSTROPHE}', # u'\\uff07' ] RE_NBSP = re.compile(u'\\xa0',", "self._is_valid_date_obj(date_obj): return date_obj else: return None def _try_timestamp(self): return {", "from the given string. In the example below, since no", "= low if isinstance(current_period_start, datetime): reset_arguments = {} for test_period", "``6`` are from *current_date*. >>> DateDataParser().get_date_data(u'2014') {'date_obj': datetime.datetime(2014, 6, 16,", "TypeError(self.DATE_FORMATS_ERROR_MESSAGE) self.language = language self.date_string = date_string self.date_formats = date_formats", "html_string = RE_NBSP.sub(' ', html_string) html_string = RE_SPACES.sub(' ', html_string)", "the moment of writing this). Hence, the level of precision", "get_last_day_of_month(year, month): return calendar.monthrange(year, month)[1] def parse_with_formats(date_string, date_formats, settings): \"\"\"", "is not None: raise TypeError(\"languages argument must be a list", "not in words date_string = sanitize_spaces(date_string) date_string = RE_SANITIZE_AMPM.sub(r'\\1m', date_string)", "self._translated_date_with_formatting = None @classmethod def parse(cls, language, date_string, date_formats=None, settings=None):", "date_string = RE_SANITIZE_RUSSIAN.sub(r'\\1 ', date_string) # remove u'г.' (Russian for", "with no day and month information present, level of precision", "formats. Supports parsing multiple languages and timezones. :param date_string: A", "None self._translated_date_with_formatting = None @classmethod def parse(cls, language, date_string, date_formats=None,", "RE_NBSP.sub(' ', html_string) html_string = RE_SPACES.sub(' ', html_string) html_string =", "_try_hardcoded_formats(self): hardcoded_date_formats = [ '%B %d, %Y, %I:%M:%S %p', '%b", "date_string) date_string = RE_SANITIZE_RUSSIAN.sub(r'\\1 ', date_string) # remove u'г.' (Russian", ".. note:: *Period* values can be a 'day' (default), 'week',", "23, 14, 21), 'period': 'day'} \"\"\" if not(isinstance(date_string, six.text_type) or", "{ 'date_obj': date_obj, 'period': period, } except ValueError: self._settings.DATE_ORDER =", "month)[1] def parse_with_formats(date_string, date_formats, settings): \"\"\" Parse with formats and", "import collections from datetime import datetime, timedelta from warnings import", "'date_obj' not in date_obj or 'period' not in date_obj: return", "a recognizably valid format. :type date_string: str|unicode :param date_formats: A", "from warnings import warn import six import regex as re", "in ('day', 'week', 'month', 'year'): return False return True class", "- timedelta(days=current_period_start.weekday()) elif period == 'month': current_period_start = current_period_start.replace(day=1) elif", "multiple languages and timezones. :param date_string: A string representing date", "utf-8 -*- import calendar import collections from datetime import datetime,", "parsed_date['language'] = language.shortname return parsed_date else: return {'date_obj': None, 'period':", "or UTC offsets are returned in UTC time unless specified", "date_string, date_formats, settings=self._settings) if parsed_date: parsed_date['language'] = language.shortname return parsed_date", "u'\\u2032' u'\\N{REVERSED PRIME}', # u'\\u2035' u'\\N{MODIFIER LETTER PRIME}', # u'\\u02b9'", "= re.compile(r'([\\W\\d])\\u0433\\.', flags=re.I | re.U) RE_SANITIZE_AMPM = re.compile(r'\\b([ap])(\\.)?m(\\.)?\\b', flags=re.DOTALL |", "def _get_language_loader(cls): if not cls.language_loader: cls.language_loader = LanguageDataLoader() return cls.language_loader", "'period': u'day'} :raises: ValueError - Unknown Language .. note:: *Period*", ":mod:`datetime.datetime` object and *period*. For example: {'date_obj': datetime.datetime(2015, 6, 1,", "if period not in ['year', 'month', 'week', 'day', 'hour', 'minute',", "_parse(self): for parser in ( self._try_timestamp, self._try_freshness_parser, self._try_given_formats, self._try_parser, self._try_hardcoded_formats,", "is assumed to be current day ``16`` from *current date*", "else list(available_language_map.values()), allow_redetection=True) elif languages: self.language_detector = ExactLanguages(languages=languages) else: self.language_detector", "current_period_start = current_period_start.replace(**reset_arguments) if period == 'week': current_period_start \\ =", "from dateparser.languages.detection import AutoDetectLanguage, ExactLanguages from dateparser.conf import apply_settings from", "`here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_. The parser applies formats one by one, taking", "step def sanitize_date(date_string): date_string = RE_SANITIZE_SKIP.sub(' ', date_string) date_string =", "current_period_start.replace(month=1, day=1) while current_period_start < high: yield current_period_start current_period_start +=", "%Y %H:%M:%S', '%A, %B %d, %Y', '%Y-%m-%dT%H:%M:%S.%fZ' ] try: return", "except ValueError: continue else: # If format does not include", "timedelta from warnings import warn import six import regex as", "def _try_given_formats(self): if not self.date_formats: return return parse_with_formats( self._get_translated_date_with_formatting(), self.date_formats,", "_DateLanguageParser(object): DATE_FORMATS_ERROR_MESSAGE = \"Date formats should be list, tuple or", "settings) return instance._parse() def _parse(self): for parser in ( self._try_timestamp,", "settings=self._settings) self._settings.DATE_ORDER = _order return { 'date_obj': date_obj, 'period': period,", "APOSTROPHE_LOOK_ALIKE_CHARS = [ u'\\N{RIGHT SINGLE QUOTATION MARK}', # u'\\u2019' u'\\N{MODIFIER", "self._settings.NORMALIZE: date_string = normalize_unicode(date_string) date_string = sanitize_date(date_string) for language in", "'month', 'year'. *Period* represents the granularity of date parsed from", "last day of the month # instead of first, because", "'hour', 'minute', 'second'] for arg in dateutil_error_prone_args: if arg in", "if not isinstance(date_obj, dict): return False if len(date_obj) != 2:", "if not self.date_formats: return return parse_with_formats( self._get_translated_date_with_formatting(), self.date_formats, settings=self._settings )", "``16`` from *current date* (which is June 16, 2015, at", "+ 's': 1}) current_period_start = low if isinstance(current_period_start, datetime): reset_arguments", "if isinstance(date_formats, six.string_types): warn(self.DATE_FORMATS_ERROR_MESSAGE, FutureWarning) date_formats = [date_formats] elif not", "_is_valid_date_obj(self, date_obj): if not isinstance(date_obj, dict): return False if len(date_obj)", "yield end def get_intersecting_periods(low, high, period='day'): if period not in", "flags=re.I | re.U) RE_SANITIZE_AMPM = re.compile(r'\\b([ap])(\\.)?m(\\.)?\\b', flags=re.DOTALL | re.I) RE_SANITIZE_ON", "dateparser.utils import normalize_unicode, apply_timezone_from_settings APOSTROPHE_LOOK_ALIKE_CHARS = [ u'\\N{RIGHT SINGLE QUOTATION", "CET') {'date_obj': datetime.datetime(2000, 3, 23, 14, 21), 'period': 'day'} \"\"\"", "class DateDataParser(object): \"\"\" Class which handles language detection, translation and", "with 'period' and 'obj_date'. :returns: :class:`datetime.datetime`, dict or None \"\"\"", "PRIME}', # u'\\u2035' u'\\N{MODIFIER LETTER PRIME}', # u'\\u02b9' u'\\N{FULLWIDTH APOSTROPHE}',", "formats and return a dictionary with 'period' and 'obj_date'. :returns:", "format strings using directives as given `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_. The parser", "'period': u'month'} Similarly, for date strings with no day and", "= begin while date < end: yield date date +=", "date_obj, 'period': period, } except ValueError: self._settings.DATE_ORDER = _order return", "html_string = RE_TRIM_SPACES.sub(r'\\1', html_string) return html_string def date_range(begin, end, **kwargs):", "== 'week': current_period_start \\ = current_period_start - timedelta(days=current_period_start.weekday()) elif period", "= language self.date_string = date_string self.date_formats = date_formats self._translated_date =", "def sanitize_spaces(html_string): html_string = RE_NBSP.sub(' ', html_string) html_string = RE_SPACES.sub('", "relativedelta(**{period + 's': 1}) current_period_start = low if isinstance(current_period_start, datetime):", "] try: return parse_with_formats( self._get_translated_date_with_formatting(), hardcoded_date_formats, settings=self._settings ) except TypeError:", "= AutoDetectLanguage( languages if languages else list(available_language_map.values()), allow_redetection=True) elif languages:", "date_string, date_formats, settings=None): self._settings = settings if isinstance(date_formats, six.string_types): warn(self.DATE_FORMATS_ERROR_MESSAGE,", "keys to :mod:`datetime.datetime` object and *period*. For example: {'date_obj': datetime.datetime(2015,", "from dateparser.date_parser import date_parser from dateparser.freshness_date_parser import freshness_date_parser from dateparser.languages.loader", "= relativedelta(**{period + 's': 1}) current_period_start = low if isinstance(current_period_start,", "'year': current_period_start = current_period_start.replace(month=1, day=1) while current_period_start < high: yield", "def sanitize_date(date_string): date_string = RE_SANITIZE_SKIP.sub(' ', date_string) date_string = RE_SANITIZE_RUSSIAN.sub(r'\\1", "('day', 'week', 'month', 'year'): return False return True class DateDataParser(object):", "False if 'date_obj' not in date_obj or 'period' not in", "Dates with time zone indications or UTC offsets are returned", "try: if self._settings.PREFER_LANGUAGE_DATE_ORDER: self._settings.DATE_ORDER = self.language.info.get('dateorder', _order) date_obj, period =", "ValueError( \"Unknown language(s): %s\" % ', '.join(map(repr, unsupported_languages))) elif languages", "RE_SPACES.sub(' ', html_string) html_string = RE_TRIM_SPACES.sub(r'\\1', html_string) return html_string def", "16, 0, 0), 'period': u'month'} Similarly, for date strings with", "get_date_from_timestamp(self.date_string, self._settings), 'period': 'day', } def _try_freshness_parser(self): return freshness_date_parser.get_date_data(self._get_translated_date(), self._settings)", "language detection, translation and subsequent generic parsing of string representing", "settings) return date_obj def get_last_day_of_month(year, month): return calendar.monthrange(year, month)[1] def", "list, tuple or set of strings\" def __init__(self, language, date_string,", "<= low: return step = relativedelta(**{period + 's': 1}) current_period_start", "date_formats, settings=None): self._settings = settings if isinstance(date_formats, six.string_types): warn(self.DATE_FORMATS_ERROR_MESSAGE, FutureWarning)", "(end.year, end.month): yield end def get_intersecting_periods(low, high, period='day'): if period", "{'date_obj': None, 'period': 'day', 'language': None} def get_date_tuple(self, *args, **kwargs):", "= [date_formats] elif not (date_formats is None or isinstance(date_formats, (list,", "< end: yield date date += step # handles edge-case", "warnings import warn import six import regex as re from", "date_string: str|unicode :param date_formats: A list of format strings using", "taking into account the detected languages. :type date_formats: list :return:", "languages if languages else list(available_language_map.values()), allow_redetection=True) elif languages: self.language_detector =", "freshness_date_parser from dateparser.languages.loader import LanguageDataLoader from dateparser.languages.detection import AutoDetectLanguage, ExactLanguages", "month # instead of first, because the first is usually", "3, 16, 0, 0), 'period': u'month'} Similarly, for date strings", "(list, tuple, collections.Set)): if all([language in available_language_map for language in", "RE_SEARCH_TIMESTAMP.search(date_string): date_obj = datetime.fromtimestamp(int(date_string[:10])) date_obj = apply_timezone_from_settings(date_obj, settings) return date_obj", "period = 'month' date_obj = date_obj.replace( day=get_last_day_of_month(date_obj.year, date_obj.month)) if not", "date_string, date_formats, settings) return instance._parse() def _parse(self): for parser in", ") except TypeError: return None def _get_translated_date(self): if self._translated_date is", "', date_string) date_string = RE_SANITIZE_RUSSIAN.sub(r'\\1 ', date_string) # remove u'г.'", "= datetime.fromtimestamp(int(date_string[:10])) date_obj = apply_timezone_from_settings(date_obj, settings) return date_obj def get_last_day_of_month(year,", "'month', 'year'): return False return True class DateDataParser(object): \"\"\" Class", "to be current day ``16`` from *current date* (which is", "return False if len(date_obj) != 2: return False if 'date_obj'", "RE_SANITIZE_ON.sub(r'\\1', date_string) date_string = RE_SANITIZE_APOSTROPHE.sub(u\"'\", date_string) return date_string def get_date_from_timestamp(date_string,", "subsequent generic parsing of string representing date and/or time. :param", "**kwargs): date_tuple = collections.namedtuple('DateData', 'date_obj period language') date_data = self.get_date_data(*args,", "allow_redetect_language=False, settings=None): self._settings = settings available_language_map = self._get_language_loader().get_language_map() if isinstance(languages,", "sanitize_date(date_string) for language in self.language_detector.iterate_applicable_languages( date_string, modify=True, settings=self._settings): parsed_date =", "date_string = RE_SANITIZE_APOSTROPHE.sub(u\"'\", date_string) return date_string def get_date_from_timestamp(date_string, settings): if", "date_obj, 'period': period} else: return {'date_obj': None, 'period': period} class", "RE_SANITIZE_SKIP.sub(' ', date_string) date_string = RE_SANITIZE_RUSSIAN.sub(r'\\1 ', date_string) # remove", "def date_range(begin, end, **kwargs): dateutil_error_prone_args = ['year', 'month', 'week', 'day',", "list (%r given)\" % type(languages)) if allow_redetect_language: self.language_detector = AutoDetectLanguage(", "None, 'period': period} class _DateLanguageParser(object): DATE_FORMATS_ERROR_MESSAGE = \"Date formats should", "def __init__(self, languages=None, allow_redetect_language=False, settings=None): self._settings = settings available_language_map =", "given string. In the example below, since no day information", "date < end: yield date date += step # handles", "settings defined in :mod:`dateparser.conf.Settings`. :type settings: dict :return: A parser", "granularity of date parsed from the given string. In the", ":type date_formats: list :return: a dict mapping keys to :mod:`datetime.datetime`", "# u'\\u2019' u'\\N{MODIFIER LETTER APOSTROPHE}', # u'\\u02bc' u'\\N{MODIFIER LETTER TURNED", "Language, TypeError - Languages argument must be a list \"\"\"", "and month ``6`` are from *current_date*. >>> DateDataParser().get_date_data(u'2014') {'date_obj': datetime.datetime(2014,", "high: yield current_period_start current_period_start += step def sanitize_date(date_string): date_string =", "DateDataParser().get_date_data(u'March 2015') {'date_obj': datetime.datetime(2015, 3, 16, 0, 0), 'period': u'month'}", "**kwargs) return date_tuple(**date_data) @classmethod def _get_language_loader(cls): if not cls.language_loader: cls.language_loader", "+= step def sanitize_date(date_string): date_string = RE_SANITIZE_SKIP.sub(' ', date_string) date_string", "kwargs: raise ValueError(\"Invalid argument: %s\" % arg) step = relativedelta(**kwargs)", "languages. :type date_formats: list :return: a dict mapping keys to", "return {'date_obj': date_obj, 'period': period} else: return {'date_obj': None, 'period':", "as re from dateutil.relativedelta import relativedelta from dateparser.date_parser import date_parser", "u'\\N{REVERSED PRIME}', # u'\\u2035' u'\\N{MODIFIER LETTER PRIME}', # u'\\u02b9' u'\\N{FULLWIDTH", "%Y at %I:%M %p', '%d %B %Y %H:%M:%S', '%A, %B", "else: self.language_detector = AutoDetectLanguage( list(available_language_map.values()), allow_redetection=False) def get_date_data(self, date_string, date_formats=None):", "'day', 'hour', 'minute', 'second', 'microsecond']: raise ValueError(\"Invalid period: {}\".format(period)) if", "None def _try_timestamp(self): return { 'date_obj': get_date_from_timestamp(self.date_string, self._settings), 'period': 'day',", "language, date_string, date_formats=None, settings=None): instance = cls(language, date_string, date_formats, settings)", "with time zone indications or UTC offsets are returned in", "Languages argument must be a list \"\"\" language_loader = None", "time. :param languages: A list of two letters language codes,", "current_period_start = current_period_start.replace(month=1, day=1) while current_period_start < high: yield current_period_start", "self._settings), 'period': 'day', } def _try_freshness_parser(self): return freshness_date_parser.get_date_data(self._get_translated_date(), self._settings) def", "'date_obj': get_date_from_timestamp(self.date_string, self._settings), 'period': 'day', } def _try_freshness_parser(self): return freshness_date_parser.get_date_data(self._get_translated_date(),", "below, since no day information is present, the day is", ") def _try_hardcoded_formats(self): hardcoded_date_formats = [ '%B %d, %Y, %I:%M:%S", "u'\\uff07' ] RE_NBSP = re.compile(u'\\xa0', flags=re.UNICODE) RE_SPACES = re.compile(r'\\s+') RE_TRIM_SPACES", "import LanguageDataLoader from dateparser.languages.detection import AutoDetectLanguage, ExactLanguages from dateparser.conf import", "current_period_start = current_period_start.replace(day=1) elif period == 'year': current_period_start = current_period_start.replace(month=1,", "format does not include the day, use last day of", "current_period_start.replace(day=1) elif period == 'year': current_period_start = current_period_start.replace(month=1, day=1) while", "Similarly, for date strings with no day and month information", "', html_string) html_string = RE_TRIM_SPACES.sub(r'\\1', html_string) return html_string def date_range(begin,", "dateutil_error_prone_args: if arg in kwargs: raise ValueError(\"Invalid argument: %s\" %", ":type allow_redetect_language: bool :param settings: Configure customized behavior using settings", "import date_parser from dateparser.freshness_date_parser import freshness_date_parser from dateparser.languages.loader import LanguageDataLoader", "if '%d' not in date_format: period = 'month' date_obj =", "'day', 'language': None} def get_date_tuple(self, *args, **kwargs): date_tuple = collections.namedtuple('DateData',", "time unless specified using `Settings`_. >>> DateDataParser().get_date_data(u'23 March 2000, 1:21", "= sanitize_spaces(date_string) date_string = RE_SANITIZE_AMPM.sub(r'\\1m', date_string) date_string = RE_SANITIZE_ON.sub(r'\\1', date_string)", "date_string) date_string = RE_SANITIZE_APOSTROPHE.sub(u\"'\", date_string) return date_string def get_date_from_timestamp(date_string, settings):", ":returns: :class:`datetime.datetime`, dict or None \"\"\" period = 'day' for", "import normalize_unicode, apply_timezone_from_settings APOSTROPHE_LOOK_ALIKE_CHARS = [ u'\\N{RIGHT SINGLE QUOTATION MARK}',", "'%d %B %Y %H:%M:%S', '%A, %B %d, %Y', '%Y-%m-%dT%H:%M:%S.%fZ' ]", "of two letters language codes, e.g. ['en', 'es']. If languages", "self._try_given_formats, self._try_parser, self._try_hardcoded_formats, ): date_obj = parser() if self._is_valid_date_obj(date_obj): return", "the granularity of date parsed from the given string. In", "isinstance(current_period_start, datetime): reset_arguments = {} for test_period in ['microsecond', 'second',", "'second'] for arg in dateutil_error_prone_args: if arg in kwargs: raise", "if languages else list(available_language_map.values()), allow_redetection=True) elif languages: self.language_detector = ExactLanguages(languages=languages)", "date_data = self.get_date_data(*args, **kwargs) return date_tuple(**date_data) @classmethod def _get_language_loader(cls): if", "'year'): return False return True class DateDataParser(object): \"\"\" Class which", "first, because the first is usually out of range. if", "datetime.today() date_obj = date_obj.replace(year=today.year) date_obj = apply_timezone_from_settings(date_obj, settings) return {'date_obj':", "0, 0), 'period': u'year'} Dates with time zone indications or", "{'date_obj': datetime.datetime(2015, 6, 1, 0, 0), 'period': u'day'} :raises: ValueError", "a dictionary with 'period' and 'obj_date'. :returns: :class:`datetime.datetime`, dict or", "'hour', 'minute', 'second', 'microsecond']: raise ValueError(\"Invalid period: {}\".format(period)) if high", "def get_last_day_of_month(year, month): return calendar.monthrange(year, month)[1] def parse_with_formats(date_string, date_formats, settings):", "day=1) while current_period_start < high: yield current_period_start current_period_start += step", "= re.compile(u'|'.join(APOSTROPHE_LOOK_ALIKE_CHARS)) RE_SEARCH_TIMESTAMP = re.compile(r'^\\d{10}(?![^\\d.])') def sanitize_spaces(html_string): html_string = RE_NBSP.sub('", "'week': current_period_start \\ = current_period_start - timedelta(days=current_period_start.weekday()) elif period ==", "If format does not include the day, use last day", "date_tuple(**date_data) @classmethod def _get_language_loader(cls): if not cls.language_loader: cls.language_loader = LanguageDataLoader()", "TypeError('Input type must be str or unicode') res = parse_with_formats(date_string,", "language re-detection. :type allow_redetect_language: bool :param settings: Configure customized behavior", "hardcoded_date_formats, settings=self._settings ) except TypeError: return None def _get_translated_date(self): if", "%d, %Y, %I:%M:%S %p', '%b %d, %Y at %I:%M %p',", "languages is not None: raise TypeError(\"languages argument must be a", "offsets are returned in UTC time unless specified using `Settings`_.", "LETTER SALTILLO}', # u'\\ua78c' u'\\N{PRIME}', # u'\\u2032' u'\\N{REVERSED PRIME}', #", "day ``16`` and month ``6`` are from *current_date*. >>> DateDataParser().get_date_data(u'2014')", "in self.language_detector.iterate_applicable_languages( date_string, modify=True, settings=self._settings): parsed_date = _DateLanguageParser.parse( language, date_string,", "res if self._settings.NORMALIZE: date_string = normalize_unicode(date_string) date_string = sanitize_date(date_string) for", "period} else: return {'date_obj': None, 'period': period} class _DateLanguageParser(object): DATE_FORMATS_ERROR_MESSAGE", "'month' date_obj = date_obj.replace( day=get_last_day_of_month(date_obj.year, date_obj.month)) if not ('%y' in", "if test_period == period: break else: reset_arguments[test_period] = 0 current_period_start", "ValueError - Unknown Language, TypeError - Languages argument must be", "= RE_TRIM_SPACES.sub(r'\\1', html_string) return html_string def date_range(begin, end, **kwargs): dateutil_error_prone_args", "u'\\N{FULLWIDTH APOSTROPHE}', # u'\\uff07' ] RE_NBSP = re.compile(u'\\xa0', flags=re.UNICODE) RE_SPACES", "%B %Y %H:%M:%S', '%A, %B %d, %Y', '%Y-%m-%dT%H:%M:%S.%fZ' ] try:", "must be a list (%r given)\" % type(languages)) if allow_redetect_language:", "re.compile(r'([\\W\\d])\\u0433\\.', flags=re.I | re.U) RE_SANITIZE_AMPM = re.compile(r'\\b([ap])(\\.)?m(\\.)?\\b', flags=re.DOTALL | re.I)", "cls(language, date_string, date_formats, settings) return instance._parse() def _parse(self): for parser", "when iterating months and last interval is < 30 days", "date_format: period = 'month' date_obj = date_obj.replace( day=get_last_day_of_month(date_obj.year, date_obj.month)) if", "ValueError(\"Invalid period: {}\".format(period)) if high <= low: return step =", "get_date_from_timestamp(date_string, settings): if RE_SEARCH_TIMESTAMP.search(date_string): date_obj = datetime.fromtimestamp(int(date_string[:10])) date_obj = apply_timezone_from_settings(date_obj,", "collections.namedtuple('DateData', 'date_obj period language') date_data = self.get_date_data(*args, **kwargs) return date_tuple(**date_data)", "settings=None): instance = cls(language, date_string, date_formats, settings) return instance._parse() def", "and/or time in a recognizably valid format. :type date_string: str|unicode", "return res if self._settings.NORMALIZE: date_string = normalize_unicode(date_string) date_string = sanitize_date(date_string)", "from datetime import datetime, timedelta from warnings import warn import", "u'г.' (Russian for year) but not in words date_string =", "information is present, the day is assumed to be current", "self._translated_date_with_formatting def _is_valid_date_obj(self, date_obj): if not isinstance(date_obj, dict): return False", "can be a 'day' (default), 'week', 'month', 'year'. *Period* represents", "\"Date formats should be list, tuple or set of strings\"", "last interval is < 30 days if kwargs.get('months', 0) >", "in ['year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'microsecond']: raise", "as given `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_. The parser applies formats one by", "def _get_translated_date_with_formatting(self): if self._translated_date_with_formatting is None: self._translated_date_with_formatting = self.language.translate( self.date_string,", "= current_period_start.replace(**reset_arguments) if period == 'week': current_period_start \\ = current_period_start", "date* (which is June 16, 2015, at the moment of", "if RE_SEARCH_TIMESTAMP.search(date_string): date_obj = datetime.fromtimestamp(int(date_string[:10])) date_obj = apply_timezone_from_settings(date_obj, settings) return", "keep_formatting=True, settings=self._settings) return self._translated_date_with_formatting def _is_valid_date_obj(self, date_obj): if not isinstance(date_obj,", "in date_obj: return False if not date_obj['date_obj']: return False if", "in kwargs: raise ValueError(\"Invalid argument: %s\" % arg) step =", "def get_date_from_timestamp(date_string, settings): if RE_SEARCH_TIMESTAMP.search(date_string): date_obj = datetime.fromtimestamp(int(date_string[:10])) date_obj =", "TypeError: return None def _get_translated_date(self): if self._translated_date is None: self._translated_date", "level of precision is ``year`` and day ``16`` and month", "period language') date_data = self.get_date_data(*args, **kwargs) return date_tuple(**date_data) @classmethod def", "writing this). Hence, the level of precision is ``month``: >>>", "= settings if isinstance(date_formats, six.string_types): warn(self.DATE_FORMATS_ERROR_MESSAGE, FutureWarning) date_formats = [date_formats]", "import warn import six import regex as re from dateutil.relativedelta", "datetime.datetime(2015, 3, 16, 0, 0), 'period': u'month'} Similarly, for date", "raise TypeError(\"languages argument must be a list (%r given)\" %", "given)\" % type(languages)) if allow_redetect_language: self.language_detector = AutoDetectLanguage( languages if", "LanguageDataLoader from dateparser.languages.detection import AutoDetectLanguage, ExactLanguages from dateparser.conf import apply_settings", "'period': period, } except ValueError: self._settings.DATE_ORDER = _order return None", "If languages are given, it will not attempt to detect", "FutureWarning) date_formats = [date_formats] elif not (date_formats is None or", "= parse_with_formats(date_string, date_formats or [], self._settings) if res['date_obj']: return res", "strings\" def __init__(self, language, date_string, date_formats, settings=None): self._settings = settings", "date_formats = [date_formats] elif not (date_formats is None or isinstance(date_formats,", "month information present, level of precision is ``year`` and day", "date = begin while date < end: yield date date", "_try_freshness_parser(self): return freshness_date_parser.get_date_data(self._get_translated_date(), self._settings) def _try_parser(self): _order = self._settings.DATE_ORDER try:", "settings available_language_map = self._get_language_loader().get_language_map() if isinstance(languages, (list, tuple, collections.Set)): if", "= _DateLanguageParser.parse( language, date_string, date_formats, settings=self._settings) if parsed_date: parsed_date['language'] =", "return { 'date_obj': date_obj, 'period': period, } except ValueError: self._settings.DATE_ORDER", "'period': 'day', } def _try_freshness_parser(self): return freshness_date_parser.get_date_data(self._get_translated_date(), self._settings) def _try_parser(self):", ":return: A parser instance :raises: ValueError - Unknown Language, TypeError", "self._settings.DATE_ORDER try: if self._settings.PREFER_LANGUAGE_DATE_ORDER: self._settings.DATE_ORDER = self.language.info.get('dateorder', _order) date_obj, period", "date_tuple = collections.namedtuple('DateData', 'date_obj period language') date_data = self.get_date_data(*args, **kwargs)", "\"\"\" Parse string representing date and/or time in recognizable localized", "while date < end: yield date date += step #", "html_string) html_string = RE_TRIM_SPACES.sub(r'\\1', html_string) return html_string def date_range(begin, end,", "u'\\N{LATIN SMALL LETTER SALTILLO}', # u'\\ua78c' u'\\N{PRIME}', # u'\\u2032' u'\\N{REVERSED", "date_obj = parser() if self._is_valid_date_obj(date_obj): return date_obj else: return None", "a dict mapping keys to :mod:`datetime.datetime` object and *period*. For", "a 'day' (default), 'week', 'month', 'year'. *Period* represents the granularity", "is usually out of range. if '%d' not in date_format:", "TURNED COMMA}', # u'\\u02bb' u'\\N{ARMENIAN APOSTROPHE}', # u'\\u055a' u'\\N{LATIN SMALL", "# u'\\u055a' u'\\N{LATIN SMALL LETTER SALTILLO}', # u'\\ua78c' u'\\N{PRIME}', #", "return None def _try_given_formats(self): if not self.date_formats: return return parse_with_formats(", "%Y', '%Y-%m-%dT%H:%M:%S.%fZ' ] try: return parse_with_formats( self._get_translated_date_with_formatting(), hardcoded_date_formats, settings=self._settings )", "applies formats one by one, taking into account the detected", "{ 'date_obj': get_date_from_timestamp(self.date_string, self._settings), 'period': 'day', } def _try_freshness_parser(self): return", "return False return True class DateDataParser(object): \"\"\" Class which handles", "raise ValueError( \"Unknown language(s): %s\" % ', '.join(map(repr, unsupported_languages))) elif", "isinstance(languages, (list, tuple, collections.Set)): if all([language in available_language_map for language", "self._get_language_loader().get_language_map() if isinstance(languages, (list, tuple, collections.Set)): if all([language in available_language_map", "does not include the day, use last day of the", "Class which handles language detection, translation and subsequent generic parsing", "'hour']: if test_period == period: break else: reset_arguments[test_period] = 0", "timezones. :param date_string: A string representing date and/or time in", "In the example below, since no day information is present,", ">>> DateDataParser().get_date_data(u'March 2015') {'date_obj': datetime.datetime(2015, 3, 16, 0, 0), 'period':", "string. In the example below, since no day information is", "modify=True, settings=self._settings): parsed_date = _DateLanguageParser.parse( language, date_string, date_formats, settings=self._settings) if", "u'\\u2035' u'\\N{MODIFIER LETTER PRIME}', # u'\\u02b9' u'\\N{FULLWIDTH APOSTROPHE}', # u'\\uff07'", "if not(isinstance(date_string, six.text_type) or isinstance(date_string, six.string_types)): raise TypeError('Input type must", "{'date_obj': None, 'period': period} class _DateLanguageParser(object): DATE_FORMATS_ERROR_MESSAGE = \"Date formats", "since no day information is present, the day is assumed", "True class DateDataParser(object): \"\"\" Class which handles language detection, translation", "'day', } def _try_freshness_parser(self): return freshness_date_parser.get_date_data(self._get_translated_date(), self._settings) def _try_parser(self): _order", "letters language codes, e.g. ['en', 'es']. If languages are given,", "self._try_freshness_parser, self._try_given_formats, self._try_parser, self._try_hardcoded_formats, ): date_obj = parser() if self._is_valid_date_obj(date_obj):", "COMMA}', # u'\\u02bb' u'\\N{ARMENIAN APOSTROPHE}', # u'\\u055a' u'\\N{LATIN SMALL LETTER", "%p', '%d %B %Y %H:%M:%S', '%A, %B %d, %Y', '%Y-%m-%dT%H:%M:%S.%fZ'", "for date strings with no day and month information present,", ":return: a dict mapping keys to :mod:`datetime.datetime` object and *period*.", "end: yield date date += step # handles edge-case when", "date_parser.parse( self._get_translated_date(), settings=self._settings) self._settings.DATE_ORDER = _order return { 'date_obj': date_obj,", "self._translated_date_with_formatting = self.language.translate( self.date_string, keep_formatting=True, settings=self._settings) return self._translated_date_with_formatting def _is_valid_date_obj(self,", "False return True class DateDataParser(object): \"\"\" Class which handles language", "the first is usually out of range. if '%d' not", "return parsed_date else: return {'date_obj': None, 'period': 'day', 'language': None}", "'language': None} def get_date_tuple(self, *args, **kwargs): date_tuple = collections.namedtuple('DateData', 'date_obj", "__init__(self, language, date_string, date_formats, settings=None): self._settings = settings if isinstance(date_formats,", "the month # instead of first, because the first is", "first is usually out of range. if '%d' not in", "'period' and 'obj_date'. :returns: :class:`datetime.datetime`, dict or None \"\"\" period", "formats should be list, tuple or set of strings\" def", "= re.compile(u'\\xa0', flags=re.UNICODE) RE_SPACES = re.compile(r'\\s+') RE_TRIM_SPACES = re.compile(r'^\\s+(\\S.*?)\\s+$') RE_SANITIZE_SKIP", "DateDataParser().get_date_data(u'23 March 2000, 1:21 PM CET') {'date_obj': datetime.datetime(2000, 3, 23,", "_order return { 'date_obj': date_obj, 'period': period, } except ValueError:", "6, 16, 0, 0), 'period': u'year'} Dates with time zone", "allow_redetect_language: self.language_detector = AutoDetectLanguage( languages if languages else list(available_language_map.values()), allow_redetection=True)", ":type settings: dict :return: A parser instance :raises: ValueError -", "None, 'period': 'day', 'language': None} def get_date_tuple(self, *args, **kwargs): date_tuple", "must be str or unicode') res = parse_with_formats(date_string, date_formats or", "languages: list :param allow_redetect_language: Enables/disables language re-detection. :type allow_redetect_language: bool", "*period*. For example: {'date_obj': datetime.datetime(2015, 6, 1, 0, 0), 'period':", "day is assumed to be current day ``16`` from *current", "return False if 'date_obj' not in date_obj or 'period' not", "'day', 'hour', 'minute', 'second'] for arg in dateutil_error_prone_args: if arg", "'second', 'minute', 'hour']: if test_period == period: break else: reset_arguments[test_period]", "for language in languages]): languages = [available_language_map[language] for language in", "but not in words date_string = sanitize_spaces(date_string) date_string = RE_SANITIZE_AMPM.sub(r'\\1m',", "u'\\u2019' u'\\N{MODIFIER LETTER APOSTROPHE}', # u'\\u02bc' u'\\N{MODIFIER LETTER TURNED COMMA}',", "= normalize_unicode(date_string) date_string = sanitize_date(date_string) for language in self.language_detector.iterate_applicable_languages( date_string,", "0) > 0 and (date.year, date.month) == (end.year, end.month): yield", "RE_TRIM_SPACES.sub(r'\\1', html_string) return html_string def date_range(begin, end, **kwargs): dateutil_error_prone_args =", "import datetime, timedelta from warnings import warn import six import", "self.language = language self.date_string = date_string self.date_formats = date_formats self._translated_date", "} except ValueError: self._settings.DATE_ORDER = _order return None def _try_given_formats(self):", "language, date_string, date_formats, settings=None): self._settings = settings if isinstance(date_formats, six.string_types):", "isinstance(date_formats, six.string_types): warn(self.DATE_FORMATS_ERROR_MESSAGE, FutureWarning) date_formats = [date_formats] elif not (date_formats", "_try_timestamp(self): return { 'date_obj': get_date_from_timestamp(self.date_string, self._settings), 'period': 'day', } def", "not(isinstance(date_string, six.text_type) or isinstance(date_string, six.string_types)): raise TypeError('Input type must be", "instance = cls(language, date_string, date_formats, settings) return instance._parse() def _parse(self):", "%p', '%b %d, %Y at %I:%M %p', '%d %B %Y", "__init__(self, languages=None, allow_redetect_language=False, settings=None): self._settings = settings available_language_map = self._get_language_loader().get_language_map()", "RE_SANITIZE_AMPM.sub(r'\\1m', date_string) date_string = RE_SANITIZE_ON.sub(r'\\1', date_string) date_string = RE_SANITIZE_APOSTROPHE.sub(u\"'\", date_string)", "= self.get_date_data(*args, **kwargs) return date_tuple(**date_data) @classmethod def _get_language_loader(cls): if not", "30 days if kwargs.get('months', 0) > 0 and (date.year, date.month)", "the day is assumed to be current day ``16`` from", "= current_period_start.replace(day=1) elif period == 'year': current_period_start = current_period_start.replace(month=1, day=1)", "if arg in kwargs: raise ValueError(\"Invalid argument: %s\" % arg)", "parser() if self._is_valid_date_obj(date_obj): return date_obj else: return None def _try_timestamp(self):", "warn import six import regex as re from dateutil.relativedelta import", "calendar.monthrange(year, month)[1] def parse_with_formats(date_string, date_formats, settings): \"\"\" Parse with formats", "or set of strings\" def __init__(self, language, date_string, date_formats, settings=None):", "of date parsed from the given string. In the example", "= 'month' date_obj = date_obj.replace( day=get_last_day_of_month(date_obj.year, date_obj.month)) if not ('%y'", "date_obj.month)) if not ('%y' in date_format or '%Y' in date_format):", "html_string = RE_SPACES.sub(' ', html_string) html_string = RE_TRIM_SPACES.sub(r'\\1', html_string) return", "languages=None, allow_redetect_language=False, settings=None): self._settings = settings available_language_map = self._get_language_loader().get_language_map() if", "date_obj: return False if not date_obj['date_obj']: return False if date_obj['period']", "for year) but not in words date_string = sanitize_spaces(date_string) date_string", "period, } except ValueError: self._settings.DATE_ORDER = _order return None def", "'year'. *Period* represents the granularity of date parsed from the", "language.shortname return parsed_date else: return {'date_obj': None, 'period': 'day', 'language':", "'month': current_period_start = current_period_start.replace(day=1) elif period == 'year': current_period_start =", "= self.language.translate( self.date_string, keep_formatting=False, settings=self._settings) return self._translated_date def _get_translated_date_with_formatting(self): if", "= 0 current_period_start = current_period_start.replace(**reset_arguments) if period == 'week': current_period_start", "if high <= low: return step = relativedelta(**{period + 's':", "= set(languages) - set(available_language_map.keys()) raise ValueError( \"Unknown language(s): %s\" %", "June 16, 2015, at the moment of writing this). Hence,", "or 'period' not in date_obj: return False if not date_obj['date_obj']:", "} def _try_freshness_parser(self): return freshness_date_parser.get_date_data(self._get_translated_date(), self._settings) def _try_parser(self): _order =", "%d, %Y at %I:%M %p', '%d %B %Y %H:%M:%S', '%A,", "self.date_formats = date_formats self._translated_date = None self._translated_date_with_formatting = None @classmethod", "day ``16`` from *current date* (which is June 16, 2015,", "be list, tuple or set of strings\" def __init__(self, language,", "in dateutil_error_prone_args: if arg in kwargs: raise ValueError(\"Invalid argument: %s\"", "html_string) html_string = RE_SPACES.sub(' ', html_string) html_string = RE_TRIM_SPACES.sub(r'\\1', html_string)", "current_period_start.replace(**reset_arguments) if period == 'week': current_period_start \\ = current_period_start -", "re.compile(r'\\t|\\n|\\r|\\u00bb|,\\s\\u0432|\\u200e|\\xb7|\\u200f|\\u064e|\\u064f', flags=re.M) RE_SANITIZE_RUSSIAN = re.compile(r'([\\W\\d])\\u0433\\.', flags=re.I | re.U) RE_SANITIZE_AMPM =", "date_obj['period'] not in ('day', 'week', 'month', 'year'): return False return", "relativedelta(days=1) date = begin while date < end: yield date", "re.compile(r'^.*?on:\\s+(.*)') RE_SANITIZE_APOSTROPHE = re.compile(u'|'.join(APOSTROPHE_LOOK_ALIKE_CHARS)) RE_SEARCH_TIMESTAMP = re.compile(r'^\\d{10}(?![^\\d.])') def sanitize_spaces(html_string): html_string", "date_string) # remove u'г.' (Russian for year) but not in", "@classmethod def _get_language_loader(cls): if not cls.language_loader: cls.language_loader = LanguageDataLoader() return", "remove u'г.' (Russian for year) but not in words date_string", "instead of first, because the first is usually out of", "date_obj = date_obj.replace( day=get_last_day_of_month(date_obj.year, date_obj.month)) if not ('%y' in date_format", "%s\" % ', '.join(map(repr, unsupported_languages))) elif languages is not None:", "date_obj, period = date_parser.parse( self._get_translated_date(), settings=self._settings) self._settings.DATE_ORDER = _order return", "flags=re.M) RE_SANITIZE_RUSSIAN = re.compile(r'([\\W\\d])\\u0433\\.', flags=re.I | re.U) RE_SANITIZE_AMPM = re.compile(r'\\b([ap])(\\.)?m(\\.)?\\b',", "= \"Date formats should be list, tuple or set of", "self.date_string, keep_formatting=True, settings=self._settings) return self._translated_date_with_formatting def _is_valid_date_obj(self, date_obj): if not", "'%b %d, %Y at %I:%M %p', '%d %B %Y %H:%M:%S',", "u'\\N{RIGHT SINGLE QUOTATION MARK}', # u'\\u2019' u'\\N{MODIFIER LETTER APOSTROPHE}', #", "be a list (%r given)\" % type(languages)) if allow_redetect_language: self.language_detector", "instance :raises: ValueError - Unknown Language, TypeError - Languages argument", "or isinstance(date_string, six.string_types)): raise TypeError('Input type must be str or", "using `Settings`_. >>> DateDataParser().get_date_data(u'23 March 2000, 1:21 PM CET') {'date_obj':", "'%B %d, %Y, %I:%M:%S %p', '%b %d, %Y at %I:%M", "RE_SANITIZE_APOSTROPHE = re.compile(u'|'.join(APOSTROPHE_LOOK_ALIKE_CHARS)) RE_SEARCH_TIMESTAMP = re.compile(r'^\\d{10}(?![^\\d.])') def sanitize_spaces(html_string): html_string =", "0), 'period': u'year'} Dates with time zone indications or UTC", "not in date_format: period = 'month' date_obj = date_obj.replace( day=get_last_day_of_month(date_obj.year,", "yield date date += step # handles edge-case when iterating", "language') date_data = self.get_date_data(*args, **kwargs) return date_tuple(**date_data) @classmethod def _get_language_loader(cls):", "coding: utf-8 -*- import calendar import collections from datetime import", "_try_parser(self): _order = self._settings.DATE_ORDER try: if self._settings.PREFER_LANGUAGE_DATE_ORDER: self._settings.DATE_ORDER = self.language.info.get('dateorder',", "): date_obj = parser() if self._is_valid_date_obj(date_obj): return date_obj else: return", "from dateutil.relativedelta import relativedelta from dateparser.date_parser import date_parser from dateparser.freshness_date_parser", "be a list \"\"\" language_loader = None @apply_settings def __init__(self,", "6, 1, 0, 0), 'period': u'day'} :raises: ValueError - Unknown", "date_string = RE_SANITIZE_AMPM.sub(r'\\1m', date_string) date_string = RE_SANITIZE_ON.sub(r'\\1', date_string) date_string =", "dateutil.relativedelta import relativedelta from dateparser.date_parser import date_parser from dateparser.freshness_date_parser import", "settings=self._settings) if parsed_date: parsed_date['language'] = language.shortname return parsed_date else: return", "sanitize_spaces(date_string) date_string = RE_SANITIZE_AMPM.sub(r'\\1m', date_string) date_string = RE_SANITIZE_ON.sub(r'\\1', date_string) date_string", "u'month'} Similarly, for date strings with no day and month", "day, use last day of the month # instead of", "= cls(language, date_string, date_formats, settings) return instance._parse() def _parse(self): for", "The parser applies formats one by one, taking into account", "flags=re.DOTALL | re.I) RE_SANITIZE_ON = re.compile(r'^.*?on:\\s+(.*)') RE_SANITIZE_APOSTROPHE = re.compile(u'|'.join(APOSTROPHE_LOOK_ALIKE_CHARS)) RE_SEARCH_TIMESTAMP", "import relativedelta from dateparser.date_parser import date_parser from dateparser.freshness_date_parser import freshness_date_parser", "precision is ``year`` and day ``16`` and month ``6`` are", "= self._settings.DATE_ORDER try: if self._settings.PREFER_LANGUAGE_DATE_ORDER: self._settings.DATE_ORDER = self.language.info.get('dateorder', _order) date_obj,", "and month information present, level of precision is ``year`` and", "try: return parse_with_formats( self._get_translated_date_with_formatting(), hardcoded_date_formats, settings=self._settings ) except TypeError: return", "16, 2015, at the moment of writing this). Hence, the", "allow_redetect_language: Enables/disables language re-detection. :type allow_redetect_language: bool :param settings: Configure", "settings: Configure customized behavior using settings defined in :mod:`dateparser.conf.Settings`. :type", "a list \"\"\" language_loader = None @apply_settings def __init__(self, languages=None,", "-*- import calendar import collections from datetime import datetime, timedelta", "ValueError: continue else: # If format does not include the", "return False if date_obj['period'] not in ('day', 'week', 'month', 'year'):", "(list, tuple, collections.Set))): raise TypeError(self.DATE_FORMATS_ERROR_MESSAGE) self.language = language self.date_string =", "month ``6`` are from *current_date*. >>> DateDataParser().get_date_data(u'2014') {'date_obj': datetime.datetime(2014, 6,", "representing date and/or time in a recognizably valid format. :type", "RE_TRIM_SPACES = re.compile(r'^\\s+(\\S.*?)\\s+$') RE_SANITIZE_SKIP = re.compile(r'\\t|\\n|\\r|\\u00bb|,\\s\\u0432|\\u200e|\\xb7|\\u200f|\\u064e|\\u064f', flags=re.M) RE_SANITIZE_RUSSIAN = re.compile(r'([\\W\\d])\\u0433\\.',", "# u'\\u02bc' u'\\N{MODIFIER LETTER TURNED COMMA}', # u'\\u02bb' u'\\N{ARMENIAN APOSTROPHE}',", "= apply_timezone_from_settings(date_obj, settings) return {'date_obj': date_obj, 'period': period} else: return", "list :return: a dict mapping keys to :mod:`datetime.datetime` object and", "else: unsupported_languages = set(languages) - set(available_language_map.keys()) raise ValueError( \"Unknown language(s):", "date_range(begin, end, **kwargs): dateutil_error_prone_args = ['year', 'month', 'week', 'day', 'hour',", "time in recognizable localized formats. Supports parsing multiple languages and", ":param date_string: A string representing date and/or time in a", "ValueError(\"Invalid argument: %s\" % arg) step = relativedelta(**kwargs) if kwargs", "set(languages) - set(available_language_map.keys()) raise ValueError( \"Unknown language(s): %s\" % ',", "date_format or '%Y' in date_format): today = datetime.today() date_obj =", "for language in languages] else: unsupported_languages = set(languages) - set(available_language_map.keys())", "is None: self._translated_date = self.language.translate( self.date_string, keep_formatting=False, settings=self._settings) return self._translated_date", "parsing of string representing date and/or time. :param languages: A", "= AutoDetectLanguage( list(available_language_map.values()), allow_redetection=False) def get_date_data(self, date_string, date_formats=None): \"\"\" Parse", "re.compile(r'\\s+') RE_TRIM_SPACES = re.compile(r'^\\s+(\\S.*?)\\s+$') RE_SANITIZE_SKIP = re.compile(r'\\t|\\n|\\r|\\u00bb|,\\s\\u0432|\\u200e|\\xb7|\\u200f|\\u064e|\\u064f', flags=re.M) RE_SANITIZE_RUSSIAN =", "# u'\\u2035' u'\\N{MODIFIER LETTER PRIME}', # u'\\u02b9' u'\\N{FULLWIDTH APOSTROPHE}', #", "not include the day, use last day of the month", "\"\"\" Parse with formats and return a dictionary with 'period'", "= apply_timezone_from_settings(date_obj, settings) return date_obj def get_last_day_of_month(year, month): return calendar.monthrange(year,", "= sanitize_date(date_string) for language in self.language_detector.iterate_applicable_languages( date_string, modify=True, settings=self._settings): parsed_date", "return instance._parse() def _parse(self): for parser in ( self._try_timestamp, self._try_freshness_parser,", "0), 'period': u'day'} :raises: ValueError - Unknown Language .. note::", "A list of two letters language codes, e.g. ['en', 'es'].", "= RE_SANITIZE_RUSSIAN.sub(r'\\1 ', date_string) # remove u'г.' (Russian for year)", "def __init__(self, language, date_string, date_formats, settings=None): self._settings = settings if", "level of precision is ``month``: >>> DateDataParser().get_date_data(u'March 2015') {'date_obj': datetime.datetime(2015,", "date_obj = apply_timezone_from_settings(date_obj, settings) return {'date_obj': date_obj, 'period': period} else:", "= self._get_language_loader().get_language_map() if isinstance(languages, (list, tuple, collections.Set)): if all([language in", "current_period_start - timedelta(days=current_period_start.weekday()) elif period == 'month': current_period_start = current_period_start.replace(day=1)", "import apply_settings from dateparser.utils import normalize_unicode, apply_timezone_from_settings APOSTROPHE_LOOK_ALIKE_CHARS = [", "= re.compile(r'\\b([ap])(\\.)?m(\\.)?\\b', flags=re.DOTALL | re.I) RE_SANITIZE_ON = re.compile(r'^.*?on:\\s+(.*)') RE_SANITIZE_APOSTROPHE =", "> 0 and (date.year, date.month) == (end.year, end.month): yield end", "*args, **kwargs): date_tuple = collections.namedtuple('DateData', 'date_obj period language') date_data =", "elif not (date_formats is None or isinstance(date_formats, (list, tuple, collections.Set))):", "return self._translated_date def _get_translated_date_with_formatting(self): if self._translated_date_with_formatting is None: self._translated_date_with_formatting =", "parse_with_formats( self._get_translated_date_with_formatting(), self.date_formats, settings=self._settings ) def _try_hardcoded_formats(self): hardcoded_date_formats = [", "False if len(date_obj) != 2: return False if 'date_obj' not", "day and month information present, level of precision is ``year``", "parsed from the given string. In the example below, since", "RE_SANITIZE_ON = re.compile(r'^.*?on:\\s+(.*)') RE_SANITIZE_APOSTROPHE = re.compile(u'|'.join(APOSTROPHE_LOOK_ALIKE_CHARS)) RE_SEARCH_TIMESTAMP = re.compile(r'^\\d{10}(?![^\\d.])') def", "self.date_formats: return return parse_with_formats( self._get_translated_date_with_formatting(), self.date_formats, settings=self._settings ) def _try_hardcoded_formats(self):", "False if not date_obj['date_obj']: return False if date_obj['period'] not in", "in languages]): languages = [available_language_map[language] for language in languages] else:", "in date_formats: try: date_obj = datetime.strptime(date_string, date_format) except ValueError: continue", "to detect the language. :type languages: list :param allow_redetect_language: Enables/disables", "('%y' in date_format or '%Y' in date_format): today = datetime.today()", "['microsecond', 'second', 'minute', 'hour']: if test_period == period: break else:", "DATE_FORMATS_ERROR_MESSAGE = \"Date formats should be list, tuple or set", "self.language.translate( self.date_string, keep_formatting=False, settings=self._settings) return self._translated_date def _get_translated_date_with_formatting(self): if self._translated_date_with_formatting", "SALTILLO}', # u'\\ua78c' u'\\N{PRIME}', # u'\\u2032' u'\\N{REVERSED PRIME}', # u'\\u2035'", "UTC time unless specified using `Settings`_. >>> DateDataParser().get_date_data(u'23 March 2000,", "self._settings.PREFER_LANGUAGE_DATE_ORDER: self._settings.DATE_ORDER = self.language.info.get('dateorder', _order) date_obj, period = date_parser.parse( self._get_translated_date(),", "end.month): yield end def get_intersecting_periods(low, high, period='day'): if period not", "A list of format strings using directives as given `here", "collections.Set)): if all([language in available_language_map for language in languages]): languages", "bool :param settings: Configure customized behavior using settings defined in", "date_obj['date_obj']: return False if date_obj['period'] not in ('day', 'week', 'month',", "not (date_formats is None or isinstance(date_formats, (list, tuple, collections.Set))): raise", "['year', 'month', 'week', 'day', 'hour', 'minute', 'second'] for arg in", "{'date_obj': datetime.datetime(2014, 6, 16, 0, 0), 'period': u'year'} Dates with", "self._settings.DATE_ORDER = self.language.info.get('dateorder', _order) date_obj, period = date_parser.parse( self._get_translated_date(), settings=self._settings)", "type must be str or unicode') res = parse_with_formats(date_string, date_formats", "RE_SANITIZE_RUSSIAN.sub(r'\\1 ', date_string) # remove u'г.' (Russian for year) but", "collections.Set))): raise TypeError(self.DATE_FORMATS_ERROR_MESSAGE) self.language = language self.date_string = date_string self.date_formats", "date parsed from the given string. In the example below,", "import freshness_date_parser from dateparser.languages.loader import LanguageDataLoader from dateparser.languages.detection import AutoDetectLanguage,", "freshness_date_parser.get_date_data(self._get_translated_date(), self._settings) def _try_parser(self): _order = self._settings.DATE_ORDER try: if self._settings.PREFER_LANGUAGE_DATE_ORDER:", "**kwargs): dateutil_error_prone_args = ['year', 'month', 'week', 'day', 'hour', 'minute', 'second']", "% arg) step = relativedelta(**kwargs) if kwargs else relativedelta(days=1) date", "available_language_map for language in languages]): languages = [available_language_map[language] for language", "current_period_start = low if isinstance(current_period_start, datetime): reset_arguments = {} for", "- Languages argument must be a list \"\"\" language_loader =", "settings: dict :return: A parser instance :raises: ValueError - Unknown", "= None @classmethod def parse(cls, language, date_string, date_formats=None, settings=None): instance", "in date_format: period = 'month' date_obj = date_obj.replace( day=get_last_day_of_month(date_obj.year, date_obj.month))", ">>> DateDataParser().get_date_data(u'23 March 2000, 1:21 PM CET') {'date_obj': datetime.datetime(2000, 3,", "str or unicode') res = parse_with_formats(date_string, date_formats or [], self._settings)", "u'\\ua78c' u'\\N{PRIME}', # u'\\u2032' u'\\N{REVERSED PRIME}', # u'\\u2035' u'\\N{MODIFIER LETTER", "= date_formats self._translated_date = None self._translated_date_with_formatting = None @classmethod def", "detected languages. :type date_formats: list :return: a dict mapping keys", "'date_obj': date_obj, 'period': period, } except ValueError: self._settings.DATE_ORDER = _order", "and subsequent generic parsing of string representing date and/or time.", "'.join(map(repr, unsupported_languages))) elif languages is not None: raise TypeError(\"languages argument", "[ '%B %d, %Y, %I:%M:%S %p', '%b %d, %Y at", "return return parse_with_formats( self._get_translated_date_with_formatting(), self.date_formats, settings=self._settings ) def _try_hardcoded_formats(self): hardcoded_date_formats", "instance._parse() def _parse(self): for parser in ( self._try_timestamp, self._try_freshness_parser, self._try_given_formats,", "the level of precision is ``month``: >>> DateDataParser().get_date_data(u'March 2015') {'date_obj':", "RE_SANITIZE_APOSTROPHE.sub(u\"'\", date_string) return date_string def get_date_from_timestamp(date_string, settings): if RE_SEARCH_TIMESTAMP.search(date_string): date_obj", "{}\".format(period)) if high <= low: return step = relativedelta(**{period +", "example below, since no day information is present, the day", "is June 16, 2015, at the moment of writing this).", "{} for test_period in ['microsecond', 'second', 'minute', 'hour']: if test_period", "present, the day is assumed to be current day ``16``", "and day ``16`` and month ``6`` are from *current_date*. >>>", "elif languages: self.language_detector = ExactLanguages(languages=languages) else: self.language_detector = AutoDetectLanguage( list(available_language_map.values()),", "settings=self._settings) return self._translated_date_with_formatting def _is_valid_date_obj(self, date_obj): if not isinstance(date_obj, dict):", "except TypeError: return None def _get_translated_date(self): if self._translated_date is None:", "if self._translated_date_with_formatting is None: self._translated_date_with_formatting = self.language.translate( self.date_string, keep_formatting=True, settings=self._settings)", "parsed_date: parsed_date['language'] = language.shortname return parsed_date else: return {'date_obj': None,", "return a dictionary with 'period' and 'obj_date'. :returns: :class:`datetime.datetime`, dict", "date_string = RE_SANITIZE_SKIP.sub(' ', date_string) date_string = RE_SANITIZE_RUSSIAN.sub(r'\\1 ', date_string)", "0 current_period_start = current_period_start.replace(**reset_arguments) if period == 'week': current_period_start \\", "kwargs else relativedelta(days=1) date = begin while date < end:", "Parse with formats and return a dictionary with 'period' and", "day information is present, the day is assumed to be", "iterating months and last interval is < 30 days if", "self._settings) def _try_parser(self): _order = self._settings.DATE_ORDER try: if self._settings.PREFER_LANGUAGE_DATE_ORDER: self._settings.DATE_ORDER", "%H:%M:%S', '%A, %B %d, %Y', '%Y-%m-%dT%H:%M:%S.%fZ' ] try: return parse_with_formats(", "'%Y-%m-%dT%H:%M:%S.%fZ' ] try: return parse_with_formats( self._get_translated_date_with_formatting(), hardcoded_date_formats, settings=self._settings ) except", "# If format does not include the day, use last", "months and last interval is < 30 days if kwargs.get('months',", "get_intersecting_periods(low, high, period='day'): if period not in ['year', 'month', 'week',", "elif period == 'year': current_period_start = current_period_start.replace(month=1, day=1) while current_period_start", "self._get_translated_date(), settings=self._settings) self._settings.DATE_ORDER = _order return { 'date_obj': date_obj, 'period':", "year) but not in words date_string = sanitize_spaces(date_string) date_string =", "return parse_with_formats( self._get_translated_date_with_formatting(), hardcoded_date_formats, settings=self._settings ) except TypeError: return None", "self.language_detector = AutoDetectLanguage( languages if languages else list(available_language_map.values()), allow_redetection=True) elif", "= [ u'\\N{RIGHT SINGLE QUOTATION MARK}', # u'\\u2019' u'\\N{MODIFIER LETTER", "if isinstance(languages, (list, tuple, collections.Set)): if all([language in available_language_map for", "2000, 1:21 PM CET') {'date_obj': datetime.datetime(2000, 3, 23, 14, 21),", "%I:%M:%S %p', '%b %d, %Y at %I:%M %p', '%d %B", "of range. if '%d' not in date_format: period = 'month'", "settings=self._settings ) except TypeError: return None def _get_translated_date(self): if self._translated_date", "languages and timezones. :param date_string: A string representing date and/or", "language(s): %s\" % ', '.join(map(repr, unsupported_languages))) elif languages is not", "def parse_with_formats(date_string, date_formats, settings): \"\"\" Parse with formats and return", "words date_string = sanitize_spaces(date_string) date_string = RE_SANITIZE_AMPM.sub(r'\\1m', date_string) date_string =", "= re.compile(r'^\\d{10}(?![^\\d.])') def sanitize_spaces(html_string): html_string = RE_NBSP.sub(' ', html_string) html_string", "', '.join(map(repr, unsupported_languages))) elif languages is not None: raise TypeError(\"languages", "string representing date and/or time in a recognizably valid format.", "Unknown Language, TypeError - Languages argument must be a list", "PM CET') {'date_obj': datetime.datetime(2000, 3, 23, 14, 21), 'period': 'day'}", "self.language_detector = AutoDetectLanguage( list(available_language_map.values()), allow_redetection=False) def get_date_data(self, date_string, date_formats=None): \"\"\"", "return date_string def get_date_from_timestamp(date_string, settings): if RE_SEARCH_TIMESTAMP.search(date_string): date_obj = datetime.fromtimestamp(int(date_string[:10]))", "u'\\u02bb' u'\\N{ARMENIAN APOSTROPHE}', # u'\\u055a' u'\\N{LATIN SMALL LETTER SALTILLO}', #", "21), 'period': 'day'} \"\"\" if not(isinstance(date_string, six.text_type) or isinstance(date_string, six.string_types)):", "settings=None): self._settings = settings if isinstance(date_formats, six.string_types): warn(self.DATE_FORMATS_ERROR_MESSAGE, FutureWarning) date_formats", ":raises: ValueError - Unknown Language, TypeError - Languages argument must", "return date_tuple(**date_data) @classmethod def _get_language_loader(cls): if not cls.language_loader: cls.language_loader =", "2015, at the moment of writing this). Hence, the level", "list \"\"\" language_loader = None @apply_settings def __init__(self, languages=None, allow_redetect_language=False,", ">>> DateDataParser().get_date_data(u'2014') {'date_obj': datetime.datetime(2014, 6, 16, 0, 0), 'period': u'year'}", "low if isinstance(current_period_start, datetime): reset_arguments = {} for test_period in", "object and *period*. For example: {'date_obj': datetime.datetime(2015, 6, 1, 0,", "# instead of first, because the first is usually out", "'period': 'day', 'language': None} def get_date_tuple(self, *args, **kwargs): date_tuple =", "arg in kwargs: raise ValueError(\"Invalid argument: %s\" % arg) step", "in date_format): today = datetime.today() date_obj = date_obj.replace(year=today.year) date_obj =", "for test_period in ['microsecond', 'second', 'minute', 'hour']: if test_period ==", "generic parsing of string representing date and/or time. :param languages:", "self.language_detector.iterate_applicable_languages( date_string, modify=True, settings=self._settings): parsed_date = _DateLanguageParser.parse( language, date_string, date_formats,", "period = date_parser.parse( self._get_translated_date(), settings=self._settings) self._settings.DATE_ORDER = _order return {", "edge-case when iterating months and last interval is < 30", "period == 'month': current_period_start = current_period_start.replace(day=1) elif period == 'year':", "include the day, use last day of the month #", "'period': period} class _DateLanguageParser(object): DATE_FORMATS_ERROR_MESSAGE = \"Date formats should be", "re.compile(u'\\xa0', flags=re.UNICODE) RE_SPACES = re.compile(r'\\s+') RE_TRIM_SPACES = re.compile(r'^\\s+(\\S.*?)\\s+$') RE_SANITIZE_SKIP =", "settings): \"\"\" Parse with formats and return a dictionary with", "step = relativedelta(**kwargs) if kwargs else relativedelta(days=1) date = begin", "of first, because the first is usually out of range.", "-*- coding: utf-8 -*- import calendar import collections from datetime", "if len(date_obj) != 2: return False if 'date_obj' not in", "def get_intersecting_periods(low, high, period='day'): if period not in ['year', 'month',", "Hence, the level of precision is ``month``: >>> DateDataParser().get_date_data(u'March 2015')", "in languages] else: unsupported_languages = set(languages) - set(available_language_map.keys()) raise ValueError(", "time zone indications or UTC offsets are returned in UTC", "this). Hence, the level of precision is ``month``: >>> DateDataParser().get_date_data(u'March", "period not in ['year', 'month', 'week', 'day', 'hour', 'minute', 'second',", "low: return step = relativedelta(**{period + 's': 1}) current_period_start =", "date_string: A string representing date and/or time in a recognizably", "(which is June 16, 2015, at the moment of writing", "# -*- coding: utf-8 -*- import calendar import collections from", "return self._translated_date_with_formatting def _is_valid_date_obj(self, date_obj): if not isinstance(date_obj, dict): return", "dict or None \"\"\" period = 'day' for date_format in", "import six import regex as re from dateutil.relativedelta import relativedelta", "usually out of range. if '%d' not in date_format: period", "1, 0, 0), 'period': u'day'} :raises: ValueError - Unknown Language", "u'\\N{MODIFIER LETTER TURNED COMMA}', # u'\\u02bb' u'\\N{ARMENIAN APOSTROPHE}', # u'\\u055a'", "detection, translation and subsequent generic parsing of string representing date", "'week', 'month', 'year'): return False return True class DateDataParser(object): \"\"\"", "RE_SPACES = re.compile(r'\\s+') RE_TRIM_SPACES = re.compile(r'^\\s+(\\S.*?)\\s+$') RE_SANITIZE_SKIP = re.compile(r'\\t|\\n|\\r|\\u00bb|,\\s\\u0432|\\u200e|\\xb7|\\u200f|\\u064e|\\u064f', flags=re.M)", "re.compile(r'\\b([ap])(\\.)?m(\\.)?\\b', flags=re.DOTALL | re.I) RE_SANITIZE_ON = re.compile(r'^.*?on:\\s+(.*)') RE_SANITIZE_APOSTROPHE = re.compile(u'|'.join(APOSTROPHE_LOOK_ALIKE_CHARS))", "Supports parsing multiple languages and timezones. :param date_string: A string", "use last day of the month # instead of first,", "not None: raise TypeError(\"languages argument must be a list (%r", "= None @apply_settings def __init__(self, languages=None, allow_redetect_language=False, settings=None): self._settings =", "and last interval is < 30 days if kwargs.get('months', 0)", "= _order return None def _try_given_formats(self): if not self.date_formats: return", "self._get_translated_date_with_formatting(), self.date_formats, settings=self._settings ) def _try_hardcoded_formats(self): hardcoded_date_formats = [ '%B", "self._settings.DATE_ORDER = _order return None def _try_given_formats(self): if not self.date_formats:", "res = parse_with_formats(date_string, date_formats or [], self._settings) if res['date_obj']: return", "len(date_obj) != 2: return False if 'date_obj' not in date_obj", "is None: self._translated_date_with_formatting = self.language.translate( self.date_string, keep_formatting=True, settings=self._settings) return self._translated_date_with_formatting", "is ``month``: >>> DateDataParser().get_date_data(u'March 2015') {'date_obj': datetime.datetime(2015, 3, 16, 0,", "date and/or time. :param languages: A list of two letters", "get_date_tuple(self, *args, **kwargs): date_tuple = collections.namedtuple('DateData', 'date_obj period language') date_data", "`Settings`_. >>> DateDataParser().get_date_data(u'23 March 2000, 1:21 PM CET') {'date_obj': datetime.datetime(2000,", "of string representing date and/or time. :param languages: A list", "current day ``16`` from *current date* (which is June 16,", "account the detected languages. :type date_formats: list :return: a dict", "unsupported_languages = set(languages) - set(available_language_map.keys()) raise ValueError( \"Unknown language(s): %s\"", "date_string, modify=True, settings=self._settings): parsed_date = _DateLanguageParser.parse( language, date_string, date_formats, settings=self._settings)", "language in languages]): languages = [available_language_map[language] for language in languages]", "else: reset_arguments[test_period] = 0 current_period_start = current_period_start.replace(**reset_arguments) if period ==", "'date_obj period language') date_data = self.get_date_data(*args, **kwargs) return date_tuple(**date_data) @classmethod", "RE_SEARCH_TIMESTAMP = re.compile(r'^\\d{10}(?![^\\d.])') def sanitize_spaces(html_string): html_string = RE_NBSP.sub(' ', html_string)", "Configure customized behavior using settings defined in :mod:`dateparser.conf.Settings`. :type settings:", "from *current_date*. >>> DateDataParser().get_date_data(u'2014') {'date_obj': datetime.datetime(2014, 6, 16, 0, 0),", "the day, use last day of the month # instead", "warn(self.DATE_FORMATS_ERROR_MESSAGE, FutureWarning) date_formats = [date_formats] elif not (date_formats is None", "\"\"\" Class which handles language detection, translation and subsequent generic", "\\ = current_period_start - timedelta(days=current_period_start.weekday()) elif period == 'month': current_period_start", "= RE_SANITIZE_SKIP.sub(' ', date_string) date_string = RE_SANITIZE_RUSSIAN.sub(r'\\1 ', date_string) #", "self.date_formats, settings=self._settings ) def _try_hardcoded_formats(self): hardcoded_date_formats = [ '%B %d,", "html_string def date_range(begin, end, **kwargs): dateutil_error_prone_args = ['year', 'month', 'week',", "sanitize_date(date_string): date_string = RE_SANITIZE_SKIP.sub(' ', date_string) date_string = RE_SANITIZE_RUSSIAN.sub(r'\\1 ',", "= ExactLanguages(languages=languages) else: self.language_detector = AutoDetectLanguage( list(available_language_map.values()), allow_redetection=False) def get_date_data(self,", "or None \"\"\" period = 'day' for date_format in date_formats:", "%I:%M %p', '%d %B %Y %H:%M:%S', '%A, %B %d, %Y',", "self._settings = settings if isinstance(date_formats, six.string_types): warn(self.DATE_FORMATS_ERROR_MESSAGE, FutureWarning) date_formats =", "AutoDetectLanguage( languages if languages else list(available_language_map.values()), allow_redetection=True) elif languages: self.language_detector", "date_string, date_formats=None, settings=None): instance = cls(language, date_string, date_formats, settings) return", "date_format): today = datetime.today() date_obj = date_obj.replace(year=today.year) date_obj = apply_timezone_from_settings(date_obj,", "six.text_type) or isinstance(date_string, six.string_types)): raise TypeError('Input type must be str", "or unicode') res = parse_with_formats(date_string, date_formats or [], self._settings) if", "return None def _try_timestamp(self): return { 'date_obj': get_date_from_timestamp(self.date_string, self._settings), 'period':", "step # handles edge-case when iterating months and last interval", "allow_redetection=False) def get_date_data(self, date_string, date_formats=None): \"\"\" Parse string representing date", "not in date_obj or 'period' not in date_obj: return False", "return html_string def date_range(begin, end, **kwargs): dateutil_error_prone_args = ['year', 'month',", "'microsecond']: raise ValueError(\"Invalid period: {}\".format(period)) if high <= low: return", "\"\"\" period = 'day' for date_format in date_formats: try: date_obj", "dict :return: A parser instance :raises: ValueError - Unknown Language,", "None @apply_settings def __init__(self, languages=None, allow_redetect_language=False, settings=None): self._settings = settings", "'second', 'microsecond']: raise ValueError(\"Invalid period: {}\".format(period)) if high <= low:", "(Russian for year) but not in words date_string = sanitize_spaces(date_string)", "date_formats: A list of format strings using directives as given", "{'date_obj': date_obj, 'period': period} else: return {'date_obj': None, 'period': period}", "= re.compile(r'\\s+') RE_TRIM_SPACES = re.compile(r'^\\s+(\\S.*?)\\s+$') RE_SANITIZE_SKIP = re.compile(r'\\t|\\n|\\r|\\u00bb|,\\s\\u0432|\\u200e|\\xb7|\\u200f|\\u064e|\\u064f', flags=re.M) RE_SANITIZE_RUSSIAN", "self._translated_date_with_formatting is None: self._translated_date_with_formatting = self.language.translate( self.date_string, keep_formatting=True, settings=self._settings) return", "date_string) date_string = RE_SANITIZE_ON.sub(r'\\1', date_string) date_string = RE_SANITIZE_APOSTROPHE.sub(u\"'\", date_string) return", "return { 'date_obj': get_date_from_timestamp(self.date_string, self._settings), 'period': 'day', } def _try_freshness_parser(self):", "not isinstance(date_obj, dict): return False if len(date_obj) != 2: return", "date_obj.replace( day=get_last_day_of_month(date_obj.year, date_obj.month)) if not ('%y' in date_format or '%Y'", "date_string = RE_SANITIZE_ON.sub(r'\\1', date_string) date_string = RE_SANITIZE_APOSTROPHE.sub(u\"'\", date_string) return date_string", "date_string) return date_string def get_date_from_timestamp(date_string, settings): if RE_SEARCH_TIMESTAMP.search(date_string): date_obj =", "SINGLE QUOTATION MARK}', # u'\\u2019' u'\\N{MODIFIER LETTER APOSTROPHE}', # u'\\u02bc'", "import AutoDetectLanguage, ExactLanguages from dateparser.conf import apply_settings from dateparser.utils import", "'minute', 'second', 'microsecond']: raise ValueError(\"Invalid period: {}\".format(period)) if high <=", "import calendar import collections from datetime import datetime, timedelta from", "not in ('day', 'week', 'month', 'year'): return False return True", "- Unknown Language, TypeError - Languages argument must be a", "'minute', 'hour']: if test_period == period: break else: reset_arguments[test_period] =", "period} class _DateLanguageParser(object): DATE_FORMATS_ERROR_MESSAGE = \"Date formats should be list,", "period: {}\".format(period)) if high <= low: return step = relativedelta(**{period", "in date_obj or 'period' not in date_obj: return False if", "date_formats: list :return: a dict mapping keys to :mod:`datetime.datetime` object", "= datetime.today() date_obj = date_obj.replace(year=today.year) date_obj = apply_timezone_from_settings(date_obj, settings) return", "moment of writing this). Hence, the level of precision is", "elif period == 'month': current_period_start = current_period_start.replace(day=1) elif period ==", "formats one by one, taking into account the detected languages.", "reset_arguments[test_period] = 0 current_period_start = current_period_start.replace(**reset_arguments) if period == 'week':", "relativedelta(**kwargs) if kwargs else relativedelta(days=1) date = begin while date", "# u'\\u02bb' u'\\N{ARMENIAN APOSTROPHE}', # u'\\u055a' u'\\N{LATIN SMALL LETTER SALTILLO}',", "not in ['year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'microsecond']:", "handles language detection, translation and subsequent generic parsing of string", "languages else list(available_language_map.values()), allow_redetection=True) elif languages: self.language_detector = ExactLanguages(languages=languages) else:", "datetime.datetime(2014, 6, 16, 0, 0), 'period': u'year'} Dates with time", "self._try_parser, self._try_hardcoded_formats, ): date_obj = parser() if self._is_valid_date_obj(date_obj): return date_obj", "of precision is ``year`` and day ``16`` and month ``6``", "languages: self.language_detector = ExactLanguages(languages=languages) else: self.language_detector = AutoDetectLanguage( list(available_language_map.values()), allow_redetection=False)", "datetime.strptime(date_string, date_format) except ValueError: continue else: # If format does", "%Y, %I:%M:%S %p', '%b %d, %Y at %I:%M %p', '%d", "March 2000, 1:21 PM CET') {'date_obj': datetime.datetime(2000, 3, 23, 14,", "attempt to detect the language. :type languages: list :param allow_redetect_language:", ":param settings: Configure customized behavior using settings defined in :mod:`dateparser.conf.Settings`.", "_order = self._settings.DATE_ORDER try: if self._settings.PREFER_LANGUAGE_DATE_ORDER: self._settings.DATE_ORDER = self.language.info.get('dateorder', _order)", "arg in dateutil_error_prone_args: if arg in kwargs: raise ValueError(\"Invalid argument:", "parse_with_formats(date_string, date_formats or [], self._settings) if res['date_obj']: return res if", "16, 0, 0), 'period': u'year'} Dates with time zone indications", "zone indications or UTC offsets are returned in UTC time", "[], self._settings) if res['date_obj']: return res if self._settings.NORMALIZE: date_string =", "allow_redetection=True) elif languages: self.language_detector = ExactLanguages(languages=languages) else: self.language_detector = AutoDetectLanguage(", "not attempt to detect the language. :type languages: list :param", "calendar import collections from datetime import datetime, timedelta from warnings", "out of range. if '%d' not in date_format: period =", "0, 0), 'period': u'day'} :raises: ValueError - Unknown Language ..", "\"Unknown language(s): %s\" % ', '.join(map(repr, unsupported_languages))) elif languages is", "APOSTROPHE}', # u'\\uff07' ] RE_NBSP = re.compile(u'\\xa0', flags=re.UNICODE) RE_SPACES =", "date_string = sanitize_date(date_string) for language in self.language_detector.iterate_applicable_languages( date_string, modify=True, settings=self._settings):", "date_obj else: return None def _try_timestamp(self): return { 'date_obj': get_date_from_timestamp(self.date_string,", "dateparser.languages.loader import LanguageDataLoader from dateparser.languages.detection import AutoDetectLanguage, ExactLanguages from dateparser.conf", "if kwargs.get('months', 0) > 0 and (date.year, date.month) == (end.year,", "from *current date* (which is June 16, 2015, at the", "set of strings\" def __init__(self, language, date_string, date_formats, settings=None): self._settings", "DateDataParser(object): \"\"\" Class which handles language detection, translation and subsequent", "dateparser.languages.detection import AutoDetectLanguage, ExactLanguages from dateparser.conf import apply_settings from dateparser.utils", "regex as re from dateutil.relativedelta import relativedelta from dateparser.date_parser import", "%s\" % arg) step = relativedelta(**kwargs) if kwargs else relativedelta(days=1)", "settings) return {'date_obj': date_obj, 'period': period} else: return {'date_obj': None,", "of precision is ``month``: >>> DateDataParser().get_date_data(u'March 2015') {'date_obj': datetime.datetime(2015, 3,", "Parse string representing date and/or time in recognizable localized formats.", "date_formats=None, settings=None): instance = cls(language, date_string, date_formats, settings) return instance._parse()", "re.I) RE_SANITIZE_ON = re.compile(r'^.*?on:\\s+(.*)') RE_SANITIZE_APOSTROPHE = re.compile(u'|'.join(APOSTROPHE_LOOK_ALIKE_CHARS)) RE_SEARCH_TIMESTAMP = re.compile(r'^\\d{10}(?![^\\d.])')", "date_formats, settings) return instance._parse() def _parse(self): for parser in (", "language in languages] else: unsupported_languages = set(languages) - set(available_language_map.keys()) raise", "= re.compile(r'^\\s+(\\S.*?)\\s+$') RE_SANITIZE_SKIP = re.compile(r'\\t|\\n|\\r|\\u00bb|,\\s\\u0432|\\u200e|\\xb7|\\u200f|\\u064e|\\u064f', flags=re.M) RE_SANITIZE_RUSSIAN = re.compile(r'([\\W\\d])\\u0433\\.', flags=re.I", "= datetime.strptime(date_string, date_format) except ValueError: continue else: # If format", "else: # If format does not include the day, use", "= _order return { 'date_obj': date_obj, 'period': period, } except", "day=get_last_day_of_month(date_obj.year, date_obj.month)) if not ('%y' in date_format or '%Y' in", "using directives as given `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_. The parser applies formats", "self._try_timestamp, self._try_freshness_parser, self._try_given_formats, self._try_parser, self._try_hardcoded_formats, ): date_obj = parser() if", "from dateparser.languages.loader import LanguageDataLoader from dateparser.languages.detection import AutoDetectLanguage, ExactLanguages from", "self._translated_date def _get_translated_date_with_formatting(self): if self._translated_date_with_formatting is None: self._translated_date_with_formatting = self.language.translate(", "= ['year', 'month', 'week', 'day', 'hour', 'minute', 'second'] for arg", "= language.shortname return parsed_date else: return {'date_obj': None, 'period': 'day',", "[available_language_map[language] for language in languages] else: unsupported_languages = set(languages) -", "language codes, e.g. ['en', 'es']. If languages are given, it", "note:: *Period* values can be a 'day' (default), 'week', 'month',", "try: date_obj = datetime.strptime(date_string, date_format) except ValueError: continue else: #", "given `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_. The parser applies formats one by one,", "month): return calendar.monthrange(year, month)[1] def parse_with_formats(date_string, date_formats, settings): \"\"\" Parse", "DateDataParser().get_date_data(u'2014') {'date_obj': datetime.datetime(2014, 6, 16, 0, 0), 'period': u'year'} Dates", "date_obj.replace(year=today.year) date_obj = apply_timezone_from_settings(date_obj, settings) return {'date_obj': date_obj, 'period': period}", "in recognizable localized formats. Supports parsing multiple languages and timezones.", "= date_parser.parse( self._get_translated_date(), settings=self._settings) self._settings.DATE_ORDER = _order return { 'date_obj':", "detect the language. :type languages: list :param allow_redetect_language: Enables/disables language", "ValueError - Unknown Language .. note:: *Period* values can be", "== (end.year, end.month): yield end def get_intersecting_periods(low, high, period='day'): if", "self.language_detector = ExactLanguages(languages=languages) else: self.language_detector = AutoDetectLanguage( list(available_language_map.values()), allow_redetection=False) def", "None: raise TypeError(\"languages argument must be a list (%r given)\"", "= re.compile(r'^.*?on:\\s+(.*)') RE_SANITIZE_APOSTROPHE = re.compile(u'|'.join(APOSTROPHE_LOOK_ALIKE_CHARS)) RE_SEARCH_TIMESTAMP = re.compile(r'^\\d{10}(?![^\\d.])') def sanitize_spaces(html_string):", "0), 'period': u'month'} Similarly, for date strings with no day", "A string representing date and/or time in a recognizably valid", "ExactLanguages(languages=languages) else: self.language_detector = AutoDetectLanguage( list(available_language_map.values()), allow_redetection=False) def get_date_data(self, date_string,", "res['date_obj']: return res if self._settings.NORMALIZE: date_string = normalize_unicode(date_string) date_string =", "= {} for test_period in ['microsecond', 'second', 'minute', 'hour']: if", "language. :type languages: list :param allow_redetect_language: Enables/disables language re-detection. :type", "None def _get_translated_date(self): if self._translated_date is None: self._translated_date = self.language.translate(", "# remove u'г.' (Russian for year) but not in words", "['year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'microsecond']: raise ValueError(\"Invalid", ":param allow_redetect_language: Enables/disables language re-detection. :type allow_redetect_language: bool :param settings:", "parser instance :raises: ValueError - Unknown Language, TypeError - Languages", "'month', 'week', 'day', 'hour', 'minute', 'second', 'microsecond']: raise ValueError(\"Invalid period:", "- Unknown Language .. note:: *Period* values can be a", "period == 'year': current_period_start = current_period_start.replace(month=1, day=1) while current_period_start <", "tuple or set of strings\" def __init__(self, language, date_string, date_formats,", "html_string) return html_string def date_range(begin, end, **kwargs): dateutil_error_prone_args = ['year',", "if self._is_valid_date_obj(date_obj): return date_obj else: return None def _try_timestamp(self): return", "current_period_start += step def sanitize_date(date_string): date_string = RE_SANITIZE_SKIP.sub(' ', date_string)", "are from *current_date*. >>> DateDataParser().get_date_data(u'2014') {'date_obj': datetime.datetime(2014, 6, 16, 0,", "re from dateutil.relativedelta import relativedelta from dateparser.date_parser import date_parser from", "= relativedelta(**kwargs) if kwargs else relativedelta(days=1) date = begin while", "class _DateLanguageParser(object): DATE_FORMATS_ERROR_MESSAGE = \"Date formats should be list, tuple", "APOSTROPHE}', # u'\\u055a' u'\\N{LATIN SMALL LETTER SALTILLO}', # u'\\ua78c' u'\\N{PRIME}',", "settings=None): self._settings = settings available_language_map = self._get_language_loader().get_language_map() if isinstance(languages, (list,", "in ( self._try_timestamp, self._try_freshness_parser, self._try_given_formats, self._try_parser, self._try_hardcoded_formats, ): date_obj =", "representing date and/or time in recognizable localized formats. Supports parsing", "information present, level of precision is ``year`` and day ``16``", "str|unicode :param date_formats: A list of format strings using directives", "argument must be a list \"\"\" language_loader = None @apply_settings", "unicode') res = parse_with_formats(date_string, date_formats or [], self._settings) if res['date_obj']:", "period: break else: reset_arguments[test_period] = 0 current_period_start = current_period_start.replace(**reset_arguments) if", "in a recognizably valid format. :type date_string: str|unicode :param date_formats:", "using settings defined in :mod:`dateparser.conf.Settings`. :type settings: dict :return: A", "flags=re.UNICODE) RE_SPACES = re.compile(r'\\s+') RE_TRIM_SPACES = re.compile(r'^\\s+(\\S.*?)\\s+$') RE_SANITIZE_SKIP = re.compile(r'\\t|\\n|\\r|\\u00bb|,\\s\\u0432|\\u200e|\\xb7|\\u200f|\\u064e|\\u064f',", "recognizably valid format. :type date_string: str|unicode :param date_formats: A list", "language in self.language_detector.iterate_applicable_languages( date_string, modify=True, settings=self._settings): parsed_date = _DateLanguageParser.parse( language,", "dateparser.date_parser import date_parser from dateparser.freshness_date_parser import freshness_date_parser from dateparser.languages.loader import", "= 'day' for date_format in date_formats: try: date_obj = datetime.strptime(date_string,", "return freshness_date_parser.get_date_data(self._get_translated_date(), self._settings) def _try_parser(self): _order = self._settings.DATE_ORDER try: if", "0, 0), 'period': u'month'} Similarly, for date strings with no", "else: return {'date_obj': None, 'period': 'day', 'language': None} def get_date_tuple(self,", "timedelta(days=current_period_start.weekday()) elif period == 'month': current_period_start = current_period_start.replace(day=1) elif period", "= parser() if self._is_valid_date_obj(date_obj): return date_obj else: return None def", "14, 21), 'period': 'day'} \"\"\" if not(isinstance(date_string, six.text_type) or isinstance(date_string,", "if 'date_obj' not in date_obj or 'period' not in date_obj:", "``16`` and month ``6`` are from *current_date*. >>> DateDataParser().get_date_data(u'2014') {'date_obj':", "six import regex as re from dateutil.relativedelta import relativedelta from", "= RE_SANITIZE_AMPM.sub(r'\\1m', date_string) date_string = RE_SANITIZE_ON.sub(r'\\1', date_string) date_string = RE_SANITIZE_APOSTROPHE.sub(u\"'\",", "indications or UTC offsets are returned in UTC time unless", "type(languages)) if allow_redetect_language: self.language_detector = AutoDetectLanguage( languages if languages else", "or isinstance(date_formats, (list, tuple, collections.Set))): raise TypeError(self.DATE_FORMATS_ERROR_MESSAGE) self.language = language", "<reponame>JKhakpour/dateparser # -*- coding: utf-8 -*- import calendar import collections", "date_formats=None): \"\"\" Parse string representing date and/or time in recognizable", "be str or unicode') res = parse_with_formats(date_string, date_formats or [],", "= [available_language_map[language] for language in languages] else: unsupported_languages = set(languages)", "argument must be a list (%r given)\" % type(languages)) if", "def get_date_tuple(self, *args, **kwargs): date_tuple = collections.namedtuple('DateData', 'date_obj period language')", "tuple, collections.Set))): raise TypeError(self.DATE_FORMATS_ERROR_MESSAGE) self.language = language self.date_string = date_string", "settings=self._settings): parsed_date = _DateLanguageParser.parse( language, date_string, date_formats, settings=self._settings) if parsed_date:", "== 'year': current_period_start = current_period_start.replace(month=1, day=1) while current_period_start < high:", "+= step # handles edge-case when iterating months and last", "or '%Y' in date_format): today = datetime.today() date_obj = date_obj.replace(year=today.year)", "collections from datetime import datetime, timedelta from warnings import warn", "all([language in available_language_map for language in languages]): languages = [available_language_map[language]" ]
[ "function_node from utils import clip_grad #class MixtureDensityNetworkFunction(function_node.FunctionNode): class MixtureDensityNetworkFunction(function.Function): def", "1e-10 for computational stability, != nan! self.gamma = gamma #", "+ 1e-10 # + 1e-10 for computational stability, != nan", "* xp.log(1. - z_eos + 1e-10) loss = loss_y +", "\"type(mu_x1_input): {3}, type(mu_x2_input): {4}, type(s_x1_input): {5}\" \"type(s_x2_input): {6}, type(rho_input): {7}\"", "/ self.z_s_x2 d_rho_norm_x1 = self.z_rho * d_norm_x1 d_rho_norm_x2 = self.z_rho", "(Variable): mixture components mu_x1 (Variable): mean of x1 mu_x2 (Variable):", "in_types type_check.expect( x_type.dtype.kind == 'f', eos_input_type.dtype.kind == 'f', pi_input_type.dtype.kind ==", "backward phase). Eq. 28-29 gamma = z_pi * n gamma", "+ 1e-10) # sum + 1e-10 for computational stability, !=", "= z # Normal function. Eq. 24. inv_ro = 1.", "loss_x # Mask guard to check if x3 == 2", "the gradient x1 = x[:, 0:1] x2 = x[:, 1:2]", "((C/self.z_s_x2) * (d_norm_x2 - d_rho_norm_x1)) * self.mask g_s_x1 = -", "g_s_x1, g_s_x2, g_rho = cuda.elementwise( # 'T x1, T x2,", "to differentiate g_eos = xp.empty_like(eos_input) g_s_x1 = xp.empty_like(s_x1_input) g_s_x2 =", "g_s_x1 = clip_grad(g_s_x1, th_min, th_max, xp) g_s_x2 = clip_grad(g_s_x2, th_min,", "Output the coefficient params Args: x (Variable): Tensor containing the", "mu_x1_input_type.shape[1], mu_x1_input_type.shape[1] == mu_x2_input_type.shape[1], mu_x2_input_type.shape[1] == s_x1_input_type.shape[1], s_x1_input_type.shape[1] == s_x2_input_type.shape[1],", "'x' is >0! z_s_x1 = xp.exp(s_x1_input) + 1e-10 z_s_x2 =", "(Variable) mu_x2 (Variable) s_x1 (Variable) s_x2 (Variable) rho (Variable) \"\"\"", "together\\n\" \"type(x): {0}, type(eos_input): {1}, type(pi_input): {2}\" \"type(mu_x1_input): {3}, type(mu_x2_input):", "= - self.gamma * ((C*d_norm_x1) * (d_norm_x1 - d_rho_norm_x2) -", "8) x_type, eos_input_type, pi_input_type, mu_x1_input_type, mu_x2_input_type, s_x1_input_type, s_x2_input_type, rho_input_type =", "z_eos = 1. / (1. + xp.exp(eos_input)) # F.sigmoid. NOTE:", "g_mu_x2 = - self.gamma * ((C/self.z_s_x2) * (d_norm_x2 - d_rho_norm_x1))", "containing the position [x1, x2, x3] to predict eos (Variable):", "self.mask = mask loss *= mask return loss, x, z_eos,", "rho_input_type.shape[0], pi_input_type.shape[1] == mu_x1_input_type.shape[1], mu_x1_input_type.shape[1] == mu_x2_input_type.shape[1], mu_x2_input_type.shape[1] == s_x1_input_type.shape[1],", "parameter (for the backward phase). Eq. 28-29 gamma = z_pi", "self.z_rho*self.z_rho + 1e-10) d_norm_x1 = (x1 - self.z_mu_x1) / self.z_s_x1", "# 'T g_eos, T g_pi, T g_mu_x1, T g_mu_x2, T", "# + 1e-10 for computational stability, != nan #epsilon =", "eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = self.get_retained_inputs() x,", "= xp.where(x3==2)[0] mask = xp.ones_like(x3) mask[idx_mask, 0] = 0. self.mask", "mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = inputs #self.retain_inputs(range(len(inputs))) # Retain", "{4}, type(s_x1_input): {5}\" \"type(s_x2_input): {6}, type(rho_input): {7}\" .format(type(x), type(eos_input), type(pi_input),", "== s_x2_input_type.shape[1], s_x2_input_type.shape[1] == rho_input_type.shape[1] ) pass def forward(self, inputs):", "g_s_x2 = clip_grad(g_s_x2, th_min, th_max, xp) g_rho = clip_grad(g_rho, th_min,", "= in_types type_check.expect( x_type.dtype.kind == 'f', eos_input_type.dtype.kind == 'f', pi_input_type.dtype.kind", "xp) g_pi = clip_grad(g_pi, th_min, th_max, xp) g_mu_x1 = clip_grad(g_mu_x1,", "forward(self, inputs): x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input", "2, eos_input_type.ndim >= 2, x_type.shape[0] == eos_input_type.shape[0], x_type.shape[0] == pi_input_type.shape[0],", "x2 rho (Variable): correlation parameter Returns: loss (Variable) y (Variable)", "1e-10 for computational stability, != nan #epsilon = xp.full(loss_y.shape, 1e-10,", "is >0! z_s_x1 = xp.exp(s_x1_input) + 1e-10 z_s_x2 = xp.exp(s_x2_input)", "Eq. 24. inv_ro = 1. - xp.square(z_rho) + 1e-10 n_left", "- 1.) * self.mask g_rho = - self.gamma * (d_norm_x1*d_norm_x2", "return exps / xp.sum(exps, 1, keepdims=True) # Get MDN coeff.", "self.z_eos) * self.mask g_pi = (self.z_pi - self.gamma) * self.mask", "x_type.shape[0] == mu_x1_input_type.shape[0], x_type.shape[0] == mu_x2_input_type.shape[0], x_type.shape[0] == s_x1_input_type.shape[0], x_type.shape[0]", "= cuda.get_array_module(*inputs) def softmax(x): shiftx = x - x.max() exps", "is 1/(1+e^-x). Here 'x' is >0! z_s_x1 = xp.exp(s_x1_input) +", "self.z_rho * d_norm_x2 g_eos = (x3 - self.z_eos) * self.mask", "chainer.functions from chainer.utils import type_check from chainer import cuda from", "P.23 th_min = -100.0 th_max = 100.0 g_eos = clip_grad(g_eos,", "n gamma = gamma / (xp.sum(gamma, 1, keepdims=True) + 1e-10)", "x1, T x2, T eos_input, T pi_input, T mu_x1_input, T", "type_check.expect(in_types.size() == 8) x_type, eos_input_type, pi_input_type, mu_x1_input_type, mu_x2_input_type, s_x1_input_type, s_x2_input_type,", "MDN coeff. Eq #18 to #22 z_eos = 1. /", "# Compute the loss. x1 = x[:, 0:1] x2 =", "25 norm_x1 = x1 - z_mu_x1 norm_x2 = x2 -", "phase). Eq. 28-29 gamma = z_pi * n gamma =", "= -100.0 th_max = 100.0 g_eos = clip_grad(g_eos, th_min, th_max,", "\"\"\" Mixture Density Network Output the coefficient params Args: x", "s_x2_input_type, rho_input_type = in_types type_check.expect( x_type.dtype.kind == 'f', eos_input_type.dtype.kind ==", "xp.empty_like(mu_x1_input) g_mu_x2 = xp.empty_like(mu_x2_input) # Compute the gradient x1 =", ">0! z_s_x1 = xp.exp(s_x1_input) + 1e-10 z_s_x2 = xp.exp(s_x2_input) +", "mixture components mu_x1 (Variable): mean of x1 mu_x2 (Variable): mean", "mu_x2_input_type.shape[1] == s_x1_input_type.shape[1], s_x1_input_type.shape[1] == s_x2_input_type.shape[1], s_x2_input_type.shape[1] == rho_input_type.shape[1] )", "norm_x2 = x2 - z_mu_x2 z_left = (xp.square(norm_x1)/xp.square(z_s_x1)) + (xp.square(norm_x2)/xp.square(z_s_x2))", "== s_x2_input_type.shape[0], x_type.shape[0] == rho_input_type.shape[0], pi_input_type.shape[1] == mu_x1_input_type.shape[1], mu_x1_input_type.shape[1] ==", "- d_rho_norm_x2) - 1.) * self.mask g_s_x2 = - self.gamma", "# From eq. 27 to 37 C = 1. /", "(Variable) \"\"\" return MixtureDensityNetworkFunction()(x, eos, pi, mu_x1, mu_x2, s_x1, s_x2,", "g_rho = cuda.elementwise( # 'T x1, T x2, T eos_input,", "pass def forward(self, inputs): x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input,", "- self.gamma * ((C/self.z_s_x1) * (d_norm_x1 - d_rho_norm_x2)) * self.mask", "g_rho = xp.empty_like(rho_input) g_pi = xp.empty_like(pi_input) g_mu_x1 = xp.empty_like(mu_x1_input) g_mu_x2", "1:2] x3 = x[:, 2:3] #if xp == np: #", "d_norm_x2 = (x2 - self.z_mu_x2) / self.z_s_x2 d_rho_norm_x1 = self.z_rho", "1e-10 # + 1e-10 for computational stability n_right = xp.exp(-z", "clip_grad(g_mu_x2, th_min, th_max, xp) g_s_x1 = clip_grad(g_s_x1, th_min, th_max, xp)", "Eq. 25 norm_x1 = x1 - z_mu_x1 norm_x2 = x2", "eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = inputs #", "xp.exp(pi_input) #z_pi = z_pi / xp.sum(z_pi, 1, keepdims=True) z_mu_x1 =", "+ 1e-10 z_rho = xp.tanh(rho_input) z_pi = softmax(pi_input) #z_pi =", "- x3) #loss_x = -xp.log(loss_x) loss_x = -x3 * xp.log(z_eos", "1e-10) d_norm_x1 = (x1 - self.z_mu_x1) / self.z_s_x1 d_norm_x2 =", "* n gamma = gamma / (xp.sum(gamma, 1, keepdims=True) +", "#loss_x = z_eos * x3 + (1. - z_eos) *", "type_check.expect( x_type.dtype.kind == 'f', eos_input_type.dtype.kind == 'f', pi_input_type.dtype.kind == 'f',", "+ 1e-10 z_s_x2 = xp.exp(s_x2_input) + 1e-10 z_rho = xp.tanh(rho_input)", "*= mask return loss, x, z_eos, z_pi, z_mu_x1, z_mu_x2, z_s_x1,", "mu_x1_input_type, mu_x2_input_type, s_x1_input_type, s_x2_input_type, rho_input_type = in_types type_check.expect( x_type.dtype.kind ==", "#22 z_eos = 1. / (1. + xp.exp(eos_input)) # F.sigmoid.", "= 0. self.mask = mask loss *= mask return loss,", "mu_x2_input_type.shape[1], mu_x2_input_type.shape[1] == s_x1_input_type.shape[1], s_x1_input_type.shape[1] == s_x2_input_type.shape[1], s_x2_input_type.shape[1] == rho_input_type.shape[1]", "= xp.exp(s_x1_input) + 1e-10 z_s_x2 = xp.exp(s_x2_input) + 1e-10 z_rho", "T rho_input', # 'T g_eos, T g_pi, T g_mu_x1, T", "(Variable) eos (Variable) pi (Variable) mu_x1 (Variable) mu_x2 (Variable) s_x1", "g_mu_x1, T g_mu_x2, T g_s_x1, T g_s_x2, T g_rho', #", "#loss_y = xp.maximum(loss_y, epsilon) # Because at the begining loss_y", "'f', pi_input_type.dtype.kind == 'f', mu_x1_input_type.dtype.kind == 'f', mu_x2_input_type.dtype.kind == 'f',", "z_mu_x2 = mu_x2_input # The MDN coeff are saved, because", "T s_x1_input, T s_x2_input, T rho_input', # 'T g_eos, T", "loss_y = xp.sum(loss_y, 1, keepdims=True) + 1e-10 # + 1e-10", "g_eos = clip_grad(g_eos, th_min, th_max, xp) g_pi = clip_grad(g_pi, th_min,", "2, x_type.shape[0] == eos_input_type.shape[0], x_type.shape[0] == pi_input_type.shape[0], x_type.shape[0] == mu_x1_input_type.shape[0],", "x2 - z_mu_x2 z_left = (xp.square(norm_x1)/xp.square(z_s_x1)) + (xp.square(norm_x2)/xp.square(z_s_x2)) z_right =", "+ 1e-10 # + 1e-10 for computational stability n_right =", "keepdims=True) + 1e-10 # + 1e-10 for computational stability, !=", "gamma / (xp.sum(gamma, 1, keepdims=True) + 1e-10) # sum +", "Eq. 26 loss_y = z_pi * n loss_y = xp.sum(loss_y,", "self.z_pi = z_pi self.z_mu_x1 = z_mu_x1 self.z_mu_x2 = z_mu_x2 #", "xp.exp(s_x1_input) + 1e-10 z_s_x2 = xp.exp(s_x2_input) + 1e-10 z_rho =", "C = 1. / (1. - self.z_rho*self.z_rho + 1e-10) d_norm_x1", "th_min, th_max, xp) g_mu_x2 = clip_grad(g_mu_x2, th_min, th_max, xp) g_s_x1", "xp.exp(-z / (2. * inv_ro)) n = n_right / n_left", "from chainer.utils import type_check from chainer import cuda from chainer", "s_x2 (Variable) rho (Variable) \"\"\" return MixtureDensityNetworkFunction()(x, eos, pi, mu_x1,", "* ((C/self.z_s_x1) * (d_norm_x1 - d_rho_norm_x2)) * self.mask g_mu_x2 =", "s_x2_input_type.dtype.kind == 'f', rho_input_type.dtype.kind == 'f', x_type.ndim >= 2, eos_input_type.ndim", "{0}, type(eos_input): {1}, type(pi_input): {2}\" \"type(mu_x1_input): {3}, type(mu_x2_input): {4}, type(s_x1_input):", "z_mu_x1 norm_x2 = x2 - z_mu_x2 z_left = (xp.square(norm_x1)/xp.square(z_s_x1)) +", "th_max, xp) return None, g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2,", "self.z)) * self.mask #else: # g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1,", "prediction pi (Variable): mixture components mu_x1 (Variable): mean of x1", "y (Variable) eos (Variable) pi (Variable) mu_x1 (Variable) mu_x2 (Variable)", "check_type_forward(self, in_types): type_check.expect(in_types.size() == 8) x_type, eos_input_type, pi_input_type, mu_x1_input_type, mu_x2_input_type,", "mu_x2 (Variable) s_x1 (Variable) s_x2 (Variable) rho (Variable) \"\"\" return", "= - self.gamma * (d_norm_x1*d_norm_x2 + self.z_rho*(1. - C *", "xp) g_s_x1 = clip_grad(g_s_x1, th_min, th_max, xp) g_s_x2 = clip_grad(g_s_x2,", "pi_input_type.dtype.kind == 'f', mu_x1_input_type.dtype.kind == 'f', mu_x2_input_type.dtype.kind == 'f', s_x1_input_type.dtype.kind", "check if x3 == 2 (added padding) idx_mask = xp.where(x3==2)[0]", "0. self.mask = mask loss *= mask return loss, x,", "self.z_mu_x1) / self.z_s_x1 d_norm_x2 = (x2 - self.z_mu_x2) / self.z_s_x2", "== 'f', s_x1_input_type.dtype.kind == 'f', s_x2_input_type.dtype.kind == 'f', rho_input_type.dtype.kind ==", "#from chainer import function_node from utils import clip_grad #class MixtureDensityNetworkFunction(function_node.FunctionNode):", "= clip_grad(g_s_x1, th_min, th_max, xp) g_s_x2 = clip_grad(g_s_x2, th_min, th_max,", "mu_x1_input_type.shape[1] == mu_x2_input_type.shape[1], mu_x2_input_type.shape[1] == s_x1_input_type.shape[1], s_x1_input_type.shape[1] == s_x2_input_type.shape[1], s_x2_input_type.shape[1]", "#z_pi = z_pi / xp.sum(z_pi, 1, keepdims=True) z_mu_x1 = mu_x1_input", "self.mask g_mu_x1 = - self.gamma * ((C/self.z_s_x1) * (d_norm_x1 -", "== s_x1_input_type.shape[1], s_x1_input_type.shape[1] == s_x2_input_type.shape[1], s_x2_input_type.shape[1] == rho_input_type.shape[1] ) pass", "nan #epsilon = xp.full(loss_y.shape, 1e-10, dtype=xp.float32) #loss_y = xp.maximum(loss_y, epsilon)", "1e-10) #loss_x = z_eos * x3 + (1. - z_eos)", "cuda.elementwise( # 'T x1, T x2, T eos_input, T pi_input,", "* self.mask #else: # g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2,", "keepdims=True) # Get MDN coeff. Eq #18 to #22 z_eos", "z_mu_x1, z_mu_x2, z_s_x1, z_s_x2, z_rho, def backward(self, inputs, grad_outputs): xp", "= z_pi * n gamma = gamma / (xp.sum(gamma, 1,", "# Mask guard to check if x3 == 2 (added", "self.gamma) * self.mask g_mu_x1 = - self.gamma * ((C/self.z_s_x1) *", "T g_mu_x2, T g_s_x1, T g_s_x2, T g_rho', # )", "mu_x1 (Variable): mean of x1 mu_x2 (Variable): mean of x2", "loss_y = z_pi * n loss_y = xp.sum(loss_y, 1, keepdims=True)", "stability n_right = xp.exp(-z / (2. * inv_ro)) n =", "- x.max() exps = xp.exp(shiftx) return exps / xp.sum(exps, 1,", "= xp.empty_like(s_x1_input) g_s_x2 = xp.empty_like(s_x2_input) g_rho = xp.empty_like(rho_input) g_pi =", "- C * self.z)) * self.mask #else: # g_eos, g_pi,", "= z_mu_x1 self.z_mu_x2 = z_mu_x2 # Compute the loss. x1", "'f', s_x2_input_type.dtype.kind == 'f', rho_input_type.dtype.kind == 'f', x_type.ndim >= 2,", "as np #from chainer import function_node from utils import clip_grad", "g_s_x1 = xp.empty_like(s_x1_input) g_s_x2 = xp.empty_like(s_x2_input) g_rho = xp.empty_like(rho_input) g_pi", "(Variable): mean of x1 mu_x2 (Variable): mean of x2 s_x1", "g_eos = xp.empty_like(eos_input) g_s_x1 = xp.empty_like(s_x1_input) g_s_x2 = xp.empty_like(s_x2_input) g_rho", "mu_x2, s_x1, s_x2, rho): \"\"\" Mixture Density Network Output the", "self.gamma * (d_norm_x1*d_norm_x2 + self.z_rho*(1. - C * self.z)) *", "1. / (1. + xp.exp(eos_input)) # F.sigmoid. NOTE: usually sigmoid", "variable. Eq. 25 norm_x1 = x1 - z_mu_x1 norm_x2 =", ">= 2, eos_input_type.ndim >= 2, x_type.shape[0] == eos_input_type.shape[0], x_type.shape[0] ==", "x3 == 2 (added padding) idx_mask = xp.where(x3==2)[0] mask =", "variance of x1 s_x2 (Variable): variance of x2 rho (Variable):", "xp.exp(shiftx) return exps / xp.sum(exps, 1, keepdims=True) # Get MDN", "gamma = z_pi * n gamma = gamma / (xp.sum(gamma,", "Retain everything for backward if not type_check.same_types(*inputs): raise ValueError(\"numpy and", "th_max, xp) g_s_x2 = clip_grad(g_s_x2, th_min, th_max, xp) g_rho =", "= xp.empty_like(mu_x1_input) g_mu_x2 = xp.empty_like(mu_x2_input) # Compute the gradient x1", "x - x.max() exps = xp.exp(shiftx) return exps / xp.sum(exps,", "- (1. - x3) * xp.log(1. - z_eos + 1e-10)", "pi (Variable): mixture components mu_x1 (Variable): mean of x1 mu_x2", "!= nan #epsilon = xp.full(loss_y.shape, 1e-10, dtype=xp.float32) #loss_y = xp.maximum(loss_y,", "x[:, 1:2] x3 = x[:, 2:3] # Z variable. Eq.", "z_s_x1 self.z_s_x2 = z_s_x2 self.z_rho = z_rho self.z_pi = z_pi", "import function import numpy as np #from chainer import function_node", "is exactly 0 sometime loss_y = -xp.log(loss_y + 1e-10) #loss_x", "+ loss_x # Mask guard to check if x3 ==", "#18 to #22 z_eos = 1. / (1. + xp.exp(eos_input))", "norm_x1 = x1 - z_mu_x1 norm_x2 = x2 - z_mu_x2", "pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = inputs # MDN", "d_rho_norm_x1 = self.z_rho * d_norm_x1 d_rho_norm_x2 = self.z_rho * d_norm_x2", "dtype=xp.float32) #loss_y = xp.maximum(loss_y, epsilon) # Because at the begining", "nan! self.gamma = gamma # Sequence loss. Eq. 26 loss_y", "padding) idx_mask = xp.where(x3==2)[0] mask = xp.ones_like(x3) mask[idx_mask, 0] =", "None, g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho, def mixture_density_network(x,", "(d_norm_x2 - d_rho_norm_x1) - 1.) * self.mask g_rho = -", "= x1 - z_mu_x1 norm_x2 = x2 - z_mu_x2 z_left", "self.z = z # Normal function. Eq. 24. inv_ro =", "th_min, th_max, xp) g_rho = clip_grad(g_rho, th_min, th_max, xp) return", "the coefficient params Args: x (Variable): Tensor containing the position", "Tensor containing the position [x1, x2, x3] to predict eos", "n_right / n_left # Gamma parameter (for the backward phase).", "= xp.exp(pi_input) #z_pi = z_pi / xp.sum(z_pi, 1, keepdims=True) z_mu_x1", "gamma # Sequence loss. Eq. 26 loss_y = z_pi *", "pi_input_type.shape[1] == mu_x1_input_type.shape[1], mu_x1_input_type.shape[1] == mu_x2_input_type.shape[1], mu_x2_input_type.shape[1] == s_x1_input_type.shape[1], s_x1_input_type.shape[1]", "= inputs # MDN coeff to differentiate g_eos = xp.empty_like(eos_input)", "self.gamma * ((C/self.z_s_x1) * (d_norm_x1 - d_rho_norm_x2)) * self.mask g_mu_x2", "if not type_check.same_types(*inputs): raise ValueError(\"numpy and cupy must not be", "the loss. x1 = x[:, 0:1] x2 = x[:, 1:2]", "g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho = cuda.elementwise( #", "- z_eos) * (1. - x3) #loss_x = -xp.log(loss_x) loss_x", "z_s_x2 * xp.sqrt(inv_ro) + 1e-10 # + 1e-10 for computational", "= z_mu_x2 # Compute the loss. x1 = x[:, 0:1]", "g_s_x2 = xp.empty_like(s_x2_input) g_rho = xp.empty_like(rho_input) g_pi = xp.empty_like(pi_input) g_mu_x1", "from chainer import cuda from chainer import function import numpy", "= softmax(pi_input) #z_pi = xp.exp(pi_input) #z_pi = z_pi / xp.sum(z_pi,", "Add grad_clipping here if it explodes P.23 th_min = -100.0", "th_min, th_max, xp) g_s_x2 = clip_grad(g_s_x2, th_min, th_max, xp) g_rho", "* (d_norm_x1 - d_rho_norm_x2)) * self.mask g_mu_x2 = - self.gamma", "- d_rho_norm_x1) - 1.) * self.mask g_rho = - self.gamma", "self.z_s_x1 = z_s_x1 self.z_s_x2 = z_s_x2 self.z_rho = z_rho self.z_pi", "loss_x = -x3 * xp.log(z_eos + 1e-10) - (1. -", "pi_input_type.shape[0], x_type.shape[0] == mu_x1_input_type.shape[0], x_type.shape[0] == mu_x2_input_type.shape[0], x_type.shape[0] == s_x1_input_type.shape[0],", "xp.tanh(rho_input) z_pi = softmax(pi_input) #z_pi = xp.exp(pi_input) #z_pi = z_pi", "s_x2_input, rho_input = inputs #self.retain_inputs(range(len(inputs))) # Retain everything for backward", "26 loss_y = z_pi * n loss_y = xp.sum(loss_y, 1,", "must not be used together\\n\" \"type(x): {0}, type(eos_input): {1}, type(pi_input):", "chainer import chainer.functions from chainer.utils import type_check from chainer import", "* self.mask g_mu_x2 = - self.gamma * ((C/self.z_s_x2) * (d_norm_x2", "pi_input, T mu_x1_input, T mu_x2_input, T s_x1_input, T s_x2_input, T", "z_s_x1 * z_s_x2 * xp.sqrt(inv_ro) + 1e-10 # + 1e-10", "* (d_norm_x1*d_norm_x2 + self.z_rho*(1. - C * self.z)) * self.mask", "g_s_x2, T g_rho', # ) # Add grad_clipping here if", "+ (xp.square(norm_x2)/xp.square(z_s_x2)) z_right = (2.*z_rho*norm_x1*norm_x2)/(z_s_x1*z_s_x2) z = z_left - z_right", "s_x2 (Variable): variance of x2 rho (Variable): correlation parameter Returns:", "type(s_x1_input), type(s_x2_input), type(rho_input))) xp = cuda.get_array_module(*inputs) def softmax(x): shiftx =", "xp.sqrt(inv_ro) + 1e-10 # + 1e-10 for computational stability n_right", "Eq #18 to #22 z_eos = 1. / (1. +", "shiftx = x - x.max() exps = xp.exp(shiftx) return exps", "eos, pi, mu_x1, mu_x2, s_x1, s_x2, rho): \"\"\" Mixture Density", "+ 1e-10) #loss_x = z_eos * x3 + (1. -", "((C*d_norm_x2) * (d_norm_x2 - d_rho_norm_x1) - 1.) * self.mask g_rho", "variance of x2 rho (Variable): correlation parameter Returns: loss (Variable)", "mask = xp.ones_like(x3) mask[idx_mask, 0] = 0. self.mask = mask", "# sum + 1e-10 for computational stability, != nan! self.gamma", "z_eos, z_pi, z_mu_x1, z_mu_x2, z_s_x1, z_s_x2, z_rho, def backward(self, inputs,", "- self.z_rho*self.z_rho + 1e-10) d_norm_x1 = (x1 - self.z_mu_x1) /", "xp) g_mu_x2 = clip_grad(g_mu_x2, th_min, th_max, xp) g_s_x1 = clip_grad(g_s_x1,", "(Variable) rho (Variable) \"\"\" return MixtureDensityNetworkFunction()(x, eos, pi, mu_x1, mu_x2,", "g_mu_x1 = xp.empty_like(mu_x1_input) g_mu_x2 = xp.empty_like(mu_x2_input) # Compute the gradient", "def softmax(x): shiftx = x - x.max() exps = xp.exp(shiftx)", "z_s_x2, z_rho, def backward(self, inputs, grad_outputs): xp = cuda.get_array_module(*inputs) #x,", "th_min, th_max, xp) g_pi = clip_grad(g_pi, th_min, th_max, xp) g_mu_x1", "if it explodes P.23 th_min = -100.0 th_max = 100.0", "s_x1, s_x2, rho): \"\"\" Mixture Density Network Output the coefficient", "'f', mu_x1_input_type.dtype.kind == 'f', mu_x2_input_type.dtype.kind == 'f', s_x1_input_type.dtype.kind == 'f',", "not type_check.same_types(*inputs): raise ValueError(\"numpy and cupy must not be used", "* x3 + (1. - z_eos) * (1. - x3)", "cuda.get_array_module(*inputs) #x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input =", "(d_norm_x1 - d_rho_norm_x2) - 1.) * self.mask g_s_x2 = -", "cuda from chainer import function import numpy as np #from", "# Compute the gradient x1 = x[:, 0:1] x2 =", "xp.ones_like(x3) mask[idx_mask, 0] = 0. self.mask = mask loss *=", "# Z variable. Eq. 25 norm_x1 = x1 - z_mu_x1", "x3) #loss_x = -xp.log(loss_x) loss_x = -x3 * xp.log(z_eos +", "self.mask g_s_x2 = - self.gamma * ((C*d_norm_x2) * (d_norm_x2 -", "g_rho, def mixture_density_network(x, eos, pi, mu_x1, mu_x2, s_x1, s_x2, rho):", "(Variable) s_x2 (Variable) rho (Variable) \"\"\" return MixtureDensityNetworkFunction()(x, eos, pi,", "z_left = (xp.square(norm_x1)/xp.square(z_s_x1)) + (xp.square(norm_x2)/xp.square(z_s_x2)) z_right = (2.*z_rho*norm_x1*norm_x2)/(z_s_x1*z_s_x2) z =", "= x - x.max() exps = xp.exp(shiftx) return exps /", "xp.empty_like(s_x2_input) g_rho = xp.empty_like(rho_input) g_pi = xp.empty_like(pi_input) g_mu_x1 = xp.empty_like(mu_x1_input)", "clip_grad(g_eos, th_min, th_max, xp) g_pi = clip_grad(g_pi, th_min, th_max, xp)", "in_types): type_check.expect(in_types.size() == 8) x_type, eos_input_type, pi_input_type, mu_x1_input_type, mu_x2_input_type, s_x1_input_type,", "mu_x2_input, s_x1_input, s_x2_input, rho_input = inputs # MDN coeff to", "- z_mu_x2 z_left = (xp.square(norm_x1)/xp.square(z_s_x1)) + (xp.square(norm_x2)/xp.square(z_s_x2)) z_right = (2.*z_rho*norm_x1*norm_x2)/(z_s_x1*z_s_x2)", "* z_s_x1 * z_s_x2 * xp.sqrt(inv_ro) + 1e-10 # +", "# Add grad_clipping here if it explodes P.23 th_min =", "+ self.z_rho*(1. - C * self.z)) * self.mask #else: #", "g_mu_x1 = clip_grad(g_mu_x1, th_min, th_max, xp) g_mu_x2 = clip_grad(g_mu_x2, th_min,", "{6}, type(rho_input): {7}\" .format(type(x), type(eos_input), type(pi_input), type(mu_x1_input), type(mu_x2_input), type(s_x1_input), type(s_x2_input),", "mu_x1 (Variable) mu_x2 (Variable) s_x1 (Variable) s_x2 (Variable) rho (Variable)", "s_x2_input, rho_input = self.get_retained_inputs() x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input,", "self.gamma = gamma # Sequence loss. Eq. 26 loss_y =", "xp.full(loss_y.shape, 1e-10, dtype=xp.float32) #loss_y = xp.maximum(loss_y, epsilon) # Because at", "27 to 37 C = 1. / (1. - self.z_rho*self.z_rho", "2:3] #if xp == np: # From eq. 27 to", "s_x1_input, s_x2_input, rho_input = inputs #self.retain_inputs(range(len(inputs))) # Retain everything for", "= z_pi / xp.sum(z_pi, 1, keepdims=True) z_mu_x1 = mu_x1_input z_mu_x2", "th_min, th_max, xp) g_mu_x1 = clip_grad(g_mu_x1, th_min, th_max, xp) g_mu_x2", "to check if x3 == 2 (added padding) idx_mask =", "= x[:, 1:2] x3 = x[:, 2:3] #if xp ==", "xp.empty_like(s_x1_input) g_s_x2 = xp.empty_like(s_x2_input) g_rho = xp.empty_like(rho_input) g_pi = xp.empty_like(pi_input)", "gradient x1 = x[:, 0:1] x2 = x[:, 1:2] x3", "mu_x2_input, s_x1_input, s_x2_input, rho_input = self.get_retained_inputs() x, eos_input, pi_input, mu_x1_input,", "type(mu_x1_input), type(mu_x2_input), type(s_x1_input), type(s_x2_input), type(rho_input))) xp = cuda.get_array_module(*inputs) def softmax(x):", "components mu_x1 (Variable): mean of x1 mu_x2 (Variable): mean of", "eos_input, T pi_input, T mu_x1_input, T mu_x2_input, T s_x1_input, T", "used together\\n\" \"type(x): {0}, type(eos_input): {1}, type(pi_input): {2}\" \"type(mu_x1_input): {3},", "- z_right self.z = z # Normal function. Eq. 24.", "the position [x1, x2, x3] to predict eos (Variable): End-of-stroke", "eq. 27 to 37 C = 1. / (1. -", "- self.gamma * ((C/self.z_s_x2) * (d_norm_x2 - d_rho_norm_x1)) * self.mask", "= x[:, 2:3] #if xp == np: # From eq.", "exps = xp.exp(shiftx) return exps / xp.sum(exps, 1, keepdims=True) #", "#if xp == np: # From eq. 27 to 37", "+ 1e-10 for computational stability, != nan! self.gamma = gamma", "= xp.exp(s_x2_input) + 1e-10 z_rho = xp.tanh(rho_input) z_pi = softmax(pi_input)", "mu_x2_input_type.dtype.kind == 'f', s_x1_input_type.dtype.kind == 'f', s_x2_input_type.dtype.kind == 'f', rho_input_type.dtype.kind", "(x3 - self.z_eos) * self.mask g_pi = (self.z_pi - self.gamma)", "xp) g_mu_x1 = clip_grad(g_mu_x1, th_min, th_max, xp) g_mu_x2 = clip_grad(g_mu_x2,", "# The MDN coeff are saved, because they're reused in", "function. Eq. 24. inv_ro = 1. - xp.square(z_rho) + 1e-10", "s_x2_input, T rho_input', # 'T g_eos, T g_pi, T g_mu_x1,", "#class MixtureDensityNetworkFunction(function_node.FunctionNode): class MixtureDensityNetworkFunction(function.Function): def check_type_forward(self, in_types): type_check.expect(in_types.size() == 8)", "# Gamma parameter (for the backward phase). Eq. 28-29 gamma", "z_eos) * (1. - x3) #loss_x = -xp.log(loss_x) loss_x =", "#else: # g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho =", "== mu_x2_input_type.shape[0], x_type.shape[0] == s_x1_input_type.shape[0], x_type.shape[0] == s_x2_input_type.shape[0], x_type.shape[0] ==", "th_max, xp) g_s_x1 = clip_grad(g_s_x1, th_min, th_max, xp) g_s_x2 =", "z_right = (2.*z_rho*norm_x1*norm_x2)/(z_s_x1*z_s_x2) z = z_left - z_right self.z =", "* n loss_y = xp.sum(loss_y, 1, keepdims=True) + 1e-10 #", "(1. + xp.exp(eos_input)) # F.sigmoid. NOTE: usually sigmoid is 1/(1+e^-x).", "z_mu_x1 self.z_mu_x2 = z_mu_x2 # Compute the loss. x1 =", "# g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho = cuda.elementwise(", "- self.gamma * ((C*d_norm_x2) * (d_norm_x2 - d_rho_norm_x1) - 1.)", "0:1] x2 = x[:, 1:2] x3 = x[:, 2:3] #if", "pi (Variable) mu_x1 (Variable) mu_x2 (Variable) s_x1 (Variable) s_x2 (Variable)", ") # Add grad_clipping here if it explodes P.23 th_min", "/ (1. + xp.exp(eos_input)) # F.sigmoid. NOTE: usually sigmoid is", "+ 1e-10 for computational stability n_right = xp.exp(-z / (2.", "From eq. 27 to 37 C = 1. / (1.", "== rho_input_type.shape[0], pi_input_type.shape[1] == mu_x1_input_type.shape[1], mu_x1_input_type.shape[1] == mu_x2_input_type.shape[1], mu_x2_input_type.shape[1] ==", "2:3] # Z variable. Eq. 25 norm_x1 = x1 -", "self.get_retained_inputs() x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input =", "np.pi * z_s_x1 * z_s_x2 * xp.sqrt(inv_ro) + 1e-10 #", "are saved, because they're reused in the backward phase self.z_eos", "g_mu_x2, g_s_x1, g_s_x2, g_rho = cuda.elementwise( # 'T x1, T", "T x2, T eos_input, T pi_input, T mu_x1_input, T mu_x2_input,", "from chainer import function import numpy as np #from chainer", "x3] to predict eos (Variable): End-of-stroke prediction pi (Variable): mixture", "for computational stability, != nan #epsilon = xp.full(loss_y.shape, 1e-10, dtype=xp.float32)", "xp.exp(s_x2_input) + 1e-10 z_rho = xp.tanh(rho_input) z_pi = softmax(pi_input) #z_pi", "th_max, xp) g_pi = clip_grad(g_pi, th_min, th_max, xp) g_mu_x1 =", "* self.z)) * self.mask #else: # g_eos, g_pi, g_mu_x1, g_mu_x2,", "(x2 - self.z_mu_x2) / self.z_s_x2 d_rho_norm_x1 = self.z_rho * d_norm_x1", "= self.get_retained_inputs() x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input", "s_x1_input, s_x2_input, rho_input = inputs # MDN coeff to differentiate", "xp.sum(loss_y, 1, keepdims=True) + 1e-10 # + 1e-10 for computational", "epsilon) # Because at the begining loss_y is exactly 0", "- self.gamma * ((C*d_norm_x1) * (d_norm_x1 - d_rho_norm_x2) - 1.)", "g_s_x2, g_rho, def mixture_density_network(x, eos, pi, mu_x1, mu_x2, s_x1, s_x2,", "coeff are saved, because they're reused in the backward phase", "-xp.log(loss_x) loss_x = -x3 * xp.log(z_eos + 1e-10) - (1.", "import chainer import chainer.functions from chainer.utils import type_check from chainer", "Density Network Output the coefficient params Args: x (Variable): Tensor", "g_s_x2, g_rho = cuda.elementwise( # 'T x1, T x2, T", "* inv_ro)) n = n_right / n_left # Gamma parameter", "mu_x1_input_type.shape[0], x_type.shape[0] == mu_x2_input_type.shape[0], x_type.shape[0] == s_x1_input_type.shape[0], x_type.shape[0] == s_x2_input_type.shape[0],", "xp = cuda.get_array_module(*inputs) def softmax(x): shiftx = x - x.max()", "clip_grad(g_rho, th_min, th_max, xp) return None, g_eos, g_pi, g_mu_x1, g_mu_x2,", "* ((C/self.z_s_x2) * (d_norm_x2 - d_rho_norm_x1)) * self.mask g_s_x1 =", "params Args: x (Variable): Tensor containing the position [x1, x2,", "np: # From eq. 27 to 37 C = 1.", "= clip_grad(g_eos, th_min, th_max, xp) g_pi = clip_grad(g_pi, th_min, th_max,", "raise ValueError(\"numpy and cupy must not be used together\\n\" \"type(x):", "1e-10, dtype=xp.float32) #loss_y = xp.maximum(loss_y, epsilon) # Because at the", "x_type.ndim >= 2, eos_input_type.ndim >= 2, x_type.shape[0] == eos_input_type.shape[0], x_type.shape[0]", "#loss_x = -xp.log(loss_x) loss_x = -x3 * xp.log(z_eos + 1e-10)", "Compute the loss. x1 = x[:, 0:1] x2 = x[:,", "+ 1e-10) d_norm_x1 = (x1 - self.z_mu_x1) / self.z_s_x1 d_norm_x2", "= z_left - z_right self.z = z # Normal function.", "= clip_grad(g_mu_x2, th_min, th_max, xp) g_s_x1 = clip_grad(g_s_x1, th_min, th_max,", "of x2 s_x1 (Variable): variance of x1 s_x2 (Variable): variance", "self.z_mu_x2) / self.z_s_x2 d_rho_norm_x1 = self.z_rho * d_norm_x1 d_rho_norm_x2 =", "* (d_norm_x2 - d_rho_norm_x1) - 1.) * self.mask g_rho =", "1.) * self.mask g_rho = - self.gamma * (d_norm_x1*d_norm_x2 +", "- self.gamma * (d_norm_x1*d_norm_x2 + self.z_rho*(1. - C * self.z))", "the backward phase self.z_eos = z_eos self.z_s_x1 = z_s_x1 self.z_s_x2", "type_check from chainer import cuda from chainer import function import", "x.max() exps = xp.exp(shiftx) return exps / xp.sum(exps, 1, keepdims=True)", "xp = cuda.get_array_module(*inputs) #x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input,", "g_mu_x1 = - self.gamma * ((C/self.z_s_x1) * (d_norm_x1 - d_rho_norm_x2))", "z_pi / xp.sum(z_pi, 1, keepdims=True) z_mu_x1 = mu_x1_input z_mu_x2 =", "T g_pi, T g_mu_x1, T g_mu_x2, T g_s_x1, T g_s_x2,", "g_s_x2 = - self.gamma * ((C*d_norm_x2) * (d_norm_x2 - d_rho_norm_x1)", "function import numpy as np #from chainer import function_node from", "g_s_x1 = - self.gamma * ((C*d_norm_x1) * (d_norm_x1 - d_rho_norm_x2)", "= 1. - xp.square(z_rho) + 1e-10 n_left = 2. *", "* self.mask g_s_x1 = - self.gamma * ((C*d_norm_x1) * (d_norm_x1", "not be used together\\n\" \"type(x): {0}, type(eos_input): {1}, type(pi_input): {2}\"", "mask loss *= mask return loss, x, z_eos, z_pi, z_mu_x1,", "type(mu_x2_input), type(s_x1_input), type(s_x2_input), type(rho_input))) xp = cuda.get_array_module(*inputs) def softmax(x): shiftx", "\"\"\" return MixtureDensityNetworkFunction()(x, eos, pi, mu_x1, mu_x2, s_x1, s_x2, rho)", "cupy must not be used together\\n\" \"type(x): {0}, type(eos_input): {1},", "d_rho_norm_x2)) * self.mask g_mu_x2 = - self.gamma * ((C/self.z_s_x2) *", "(Variable): Tensor containing the position [x1, x2, x3] to predict", "d_norm_x1 = (x1 - self.z_mu_x1) / self.z_s_x1 d_norm_x2 = (x2", "(Variable) y (Variable) eos (Variable) pi (Variable) mu_x1 (Variable) mu_x2", "= -xp.log(loss_x) loss_x = -x3 * xp.log(z_eos + 1e-10) -", "def mixture_density_network(x, eos, pi, mu_x1, mu_x2, s_x1, s_x2, rho): \"\"\"", "s_x2_input_type.shape[0], x_type.shape[0] == rho_input_type.shape[0], pi_input_type.shape[1] == mu_x1_input_type.shape[1], mu_x1_input_type.shape[1] == mu_x2_input_type.shape[1],", "'f', eos_input_type.dtype.kind == 'f', pi_input_type.dtype.kind == 'f', mu_x1_input_type.dtype.kind == 'f',", "import cuda from chainer import function import numpy as np", "0 sometime loss_y = -xp.log(loss_y + 1e-10) #loss_x = z_eos", "to predict eos (Variable): End-of-stroke prediction pi (Variable): mixture components", "type(eos_input), type(pi_input), type(mu_x1_input), type(mu_x2_input), type(s_x1_input), type(s_x2_input), type(rho_input))) xp = cuda.get_array_module(*inputs)", "(1. - x3) * xp.log(1. - z_eos + 1e-10) loss", "parameter Returns: loss (Variable) y (Variable) eos (Variable) pi (Variable)", "= (xp.square(norm_x1)/xp.square(z_s_x1)) + (xp.square(norm_x2)/xp.square(z_s_x2)) z_right = (2.*z_rho*norm_x1*norm_x2)/(z_s_x1*z_s_x2) z = z_left", "== eos_input_type.shape[0], x_type.shape[0] == pi_input_type.shape[0], x_type.shape[0] == mu_x1_input_type.shape[0], x_type.shape[0] ==", "xp.square(z_rho) + 1e-10 n_left = 2. * np.pi * z_s_x1", "self.gamma * ((C/self.z_s_x2) * (d_norm_x2 - d_rho_norm_x1)) * self.mask g_s_x1", "xp.log(z_eos + 1e-10) - (1. - x3) * xp.log(1. -", "clip_grad(g_s_x2, th_min, th_max, xp) g_rho = clip_grad(g_rho, th_min, th_max, xp)", "sometime loss_y = -xp.log(loss_y + 1e-10) #loss_x = z_eos *", "from utils import clip_grad #class MixtureDensityNetworkFunction(function_node.FunctionNode): class MixtureDensityNetworkFunction(function.Function): def check_type_forward(self,", "= (2.*z_rho*norm_x1*norm_x2)/(z_s_x1*z_s_x2) z = z_left - z_right self.z = z", "= x2 - z_mu_x2 z_left = (xp.square(norm_x1)/xp.square(z_s_x1)) + (xp.square(norm_x2)/xp.square(z_s_x2)) z_right", "g_s_x1, g_s_x2, g_rho, def mixture_density_network(x, eos, pi, mu_x1, mu_x2, s_x1,", "computational stability n_right = xp.exp(-z / (2. * inv_ro)) n", "T g_rho', # ) # Add grad_clipping here if it", "x3 = x[:, 2:3] #if xp == np: # From", "g_rho', # ) # Add grad_clipping here if it explodes", "(Variable) s_x1 (Variable) s_x2 (Variable) rho (Variable) \"\"\" return MixtureDensityNetworkFunction()(x,", "mu_x1_input, T mu_x2_input, T s_x1_input, T s_x2_input, T rho_input', #", "{2}\" \"type(mu_x1_input): {3}, type(mu_x2_input): {4}, type(s_x1_input): {5}\" \"type(s_x2_input): {6}, type(rho_input):", "* xp.sqrt(inv_ro) + 1e-10 # + 1e-10 for computational stability", "1.) * self.mask g_s_x2 = - self.gamma * ((C*d_norm_x2) *", "MixtureDensityNetworkFunction(function_node.FunctionNode): class MixtureDensityNetworkFunction(function.Function): def check_type_forward(self, in_types): type_check.expect(in_types.size() == 8) x_type,", "inputs): x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input =", "stability, != nan! self.gamma = gamma # Sequence loss. Eq.", "pi_input_type, mu_x1_input_type, mu_x2_input_type, s_x1_input_type, s_x2_input_type, rho_input_type = in_types type_check.expect( x_type.dtype.kind", "* self.mask g_pi = (self.z_pi - self.gamma) * self.mask g_mu_x1", "mu_x1, mu_x2, s_x1, s_x2, rho): \"\"\" Mixture Density Network Output", "grad_clipping here if it explodes P.23 th_min = -100.0 th_max", "- x3) * xp.log(1. - z_eos + 1e-10) loss =", "here if it explodes P.23 th_min = -100.0 th_max =", "MDN coeff are saved, because they're reused in the backward", "predict eos (Variable): End-of-stroke prediction pi (Variable): mixture components mu_x1", "g_rho = - self.gamma * (d_norm_x1*d_norm_x2 + self.z_rho*(1. - C", "eos (Variable) pi (Variable) mu_x1 (Variable) mu_x2 (Variable) s_x1 (Variable)", "s_x2_input_type.shape[1] == rho_input_type.shape[1] ) pass def forward(self, inputs): x, eos_input,", "rho_input_type.shape[1] ) pass def forward(self, inputs): x, eos_input, pi_input, mu_x1_input,", "- self.z_mu_x1) / self.z_s_x1 d_norm_x2 = (x2 - self.z_mu_x2) /", "== 'f', x_type.ndim >= 2, eos_input_type.ndim >= 2, x_type.shape[0] ==", "Args: x (Variable): Tensor containing the position [x1, x2, x3]", "g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho, def mixture_density_network(x, eos, pi,", "rho (Variable): correlation parameter Returns: loss (Variable) y (Variable) eos", "class MixtureDensityNetworkFunction(function.Function): def check_type_forward(self, in_types): type_check.expect(in_types.size() == 8) x_type, eos_input_type,", "(2.*z_rho*norm_x1*norm_x2)/(z_s_x1*z_s_x2) z = z_left - z_right self.z = z #", "guard to check if x3 == 2 (added padding) idx_mask", "self.gamma * ((C*d_norm_x1) * (d_norm_x1 - d_rho_norm_x2) - 1.) *", "Normal function. Eq. 24. inv_ro = 1. - xp.square(z_rho) +", "z_left - z_right self.z = z # Normal function. Eq.", "x_type.shape[0] == s_x1_input_type.shape[0], x_type.shape[0] == s_x2_input_type.shape[0], x_type.shape[0] == rho_input_type.shape[0], pi_input_type.shape[1]", "= self.z_rho * d_norm_x1 d_rho_norm_x2 = self.z_rho * d_norm_x2 g_eos", "self.gamma * ((C*d_norm_x2) * (d_norm_x2 - d_rho_norm_x1) - 1.) *", "((C/self.z_s_x1) * (d_norm_x1 - d_rho_norm_x2)) * self.mask g_mu_x2 = -", "clip_grad(g_s_x1, th_min, th_max, xp) g_s_x2 = clip_grad(g_s_x2, th_min, th_max, xp)", "the backward phase). Eq. 28-29 gamma = z_pi * n", "eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = inputs #self.retain_inputs(range(len(inputs)))", "self.z_mu_x2 = z_mu_x2 # Compute the loss. x1 = x[:,", "(self.z_pi - self.gamma) * self.mask g_mu_x1 = - self.gamma *", "* ((C*d_norm_x2) * (d_norm_x2 - d_rho_norm_x1) - 1.) * self.mask", "= (self.z_pi - self.gamma) * self.mask g_mu_x1 = - self.gamma", "Network Output the coefficient params Args: x (Variable): Tensor containing", "(for the backward phase). Eq. 28-29 gamma = z_pi *", "- self.gamma) * self.mask g_mu_x1 = - self.gamma * ((C/self.z_s_x1)", "= n_right / n_left # Gamma parameter (for the backward", "inputs # MDN coeff to differentiate g_eos = xp.empty_like(eos_input) g_s_x1", "1. - xp.square(z_rho) + 1e-10 n_left = 2. * np.pi", "{1}, type(pi_input): {2}\" \"type(mu_x1_input): {3}, type(mu_x2_input): {4}, type(s_x1_input): {5}\" \"type(s_x2_input):", "the begining loss_y is exactly 0 sometime loss_y = -xp.log(loss_y", "* ((C*d_norm_x1) * (d_norm_x1 - d_rho_norm_x2) - 1.) * self.mask", "s_x2_input_type.shape[1], s_x2_input_type.shape[1] == rho_input_type.shape[1] ) pass def forward(self, inputs): x,", "# MDN coeff to differentiate g_eos = xp.empty_like(eos_input) g_s_x1 =", "= xp.tanh(rho_input) z_pi = softmax(pi_input) #z_pi = xp.exp(pi_input) #z_pi =", "for computational stability n_right = xp.exp(-z / (2. * inv_ro))", "type(s_x1_input): {5}\" \"type(s_x2_input): {6}, type(rho_input): {7}\" .format(type(x), type(eos_input), type(pi_input), type(mu_x1_input),", "xp.empty_like(pi_input) g_mu_x1 = xp.empty_like(mu_x1_input) g_mu_x2 = xp.empty_like(mu_x2_input) # Compute the", "1e-10 z_s_x2 = xp.exp(s_x2_input) + 1e-10 z_rho = xp.tanh(rho_input) z_pi", "mask return loss, x, z_eos, z_pi, z_mu_x1, z_mu_x2, z_s_x1, z_s_x2,", "z = z_left - z_right self.z = z # Normal", "(Variable): correlation parameter Returns: loss (Variable) y (Variable) eos (Variable)", "be used together\\n\" \"type(x): {0}, type(eos_input): {1}, type(pi_input): {2}\" \"type(mu_x1_input):", "- self.z_mu_x2) / self.z_s_x2 d_rho_norm_x1 = self.z_rho * d_norm_x1 d_rho_norm_x2", "mean of x1 mu_x2 (Variable): mean of x2 s_x1 (Variable):", "== 'f', s_x2_input_type.dtype.kind == 'f', rho_input_type.dtype.kind == 'f', x_type.ndim >=", "z # Normal function. Eq. 24. inv_ro = 1. -", "computational stability, != nan #epsilon = xp.full(loss_y.shape, 1e-10, dtype=xp.float32) #loss_y", "+ 1e-10) - (1. - x3) * xp.log(1. - z_eos", "th_min = -100.0 th_max = 100.0 g_eos = clip_grad(g_eos, th_min,", "computational stability, != nan! self.gamma = gamma # Sequence loss.", "self.z_s_x2 = z_s_x2 self.z_rho = z_rho self.z_pi = z_pi self.z_mu_x1", "= cuda.get_array_module(*inputs) #x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input", "== mu_x1_input_type.shape[0], x_type.shape[0] == mu_x2_input_type.shape[0], x_type.shape[0] == s_x1_input_type.shape[0], x_type.shape[0] ==", "(xp.square(norm_x1)/xp.square(z_s_x1)) + (xp.square(norm_x2)/xp.square(z_s_x2)) z_right = (2.*z_rho*norm_x1*norm_x2)/(z_s_x1*z_s_x2) z = z_left -", "* self.mask g_s_x2 = - self.gamma * ((C*d_norm_x2) * (d_norm_x2", "z_rho = xp.tanh(rho_input) z_pi = softmax(pi_input) #z_pi = xp.exp(pi_input) #z_pi", "#x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = self.get_retained_inputs()", "= xp.maximum(loss_y, epsilon) # Because at the begining loss_y is", "(Variable) pi (Variable) mu_x1 (Variable) mu_x2 (Variable) s_x1 (Variable) s_x2", "(xp.square(norm_x2)/xp.square(z_s_x2)) z_right = (2.*z_rho*norm_x1*norm_x2)/(z_s_x1*z_s_x2) z = z_left - z_right self.z", "= xp.sum(loss_y, 1, keepdims=True) + 1e-10 # + 1e-10 for", "g_pi = clip_grad(g_pi, th_min, th_max, xp) g_mu_x1 = clip_grad(g_mu_x1, th_min,", "keepdims=True) + 1e-10) # sum + 1e-10 for computational stability,", "T g_s_x1, T g_s_x2, T g_rho', # ) # Add", "n_right = xp.exp(-z / (2. * inv_ro)) n = n_right", "* (d_norm_x1 - d_rho_norm_x2) - 1.) * self.mask g_s_x2 =", "#epsilon = xp.full(loss_y.shape, 1e-10, dtype=xp.float32) #loss_y = xp.maximum(loss_y, epsilon) #", "= - self.gamma * ((C/self.z_s_x1) * (d_norm_x1 - d_rho_norm_x2)) *", "100.0 g_eos = clip_grad(g_eos, th_min, th_max, xp) g_pi = clip_grad(g_pi,", "= z_pi * n loss_y = xp.sum(loss_y, 1, keepdims=True) +", "T mu_x2_input, T s_x1_input, T s_x2_input, T rho_input', # 'T", "rho_input_type = in_types type_check.expect( x_type.dtype.kind == 'f', eos_input_type.dtype.kind == 'f',", "/ (2. * inv_ro)) n = n_right / n_left #", "self.z_eos = z_eos self.z_s_x1 = z_s_x1 self.z_s_x2 = z_s_x2 self.z_rho", "= cuda.elementwise( # 'T x1, T x2, T eos_input, T", "24. inv_ro = 1. - xp.square(z_rho) + 1e-10 n_left =", "= gamma / (xp.sum(gamma, 1, keepdims=True) + 1e-10) # sum", "x[:, 1:2] x3 = x[:, 2:3] #if xp == np:", "loss_y is exactly 0 sometime loss_y = -xp.log(loss_y + 1e-10)", "= x[:, 2:3] # Z variable. Eq. 25 norm_x1 =", "/ n_left # Gamma parameter (for the backward phase). Eq.", "x1 - z_mu_x1 norm_x2 = x2 - z_mu_x2 z_left =", "-xp.log(loss_y + 1e-10) #loss_x = z_eos * x3 + (1.", "'f', rho_input_type.dtype.kind == 'f', x_type.ndim >= 2, eos_input_type.ndim >= 2,", "x_type.shape[0] == rho_input_type.shape[0], pi_input_type.shape[1] == mu_x1_input_type.shape[1], mu_x1_input_type.shape[1] == mu_x2_input_type.shape[1], mu_x2_input_type.shape[1]", "type(mu_x2_input): {4}, type(s_x1_input): {5}\" \"type(s_x2_input): {6}, type(rho_input): {7}\" .format(type(x), type(eos_input),", "* d_norm_x2 g_eos = (x3 - self.z_eos) * self.mask g_pi", "x2 s_x1 (Variable): variance of x1 s_x2 (Variable): variance of", "th_max, xp) g_rho = clip_grad(g_rho, th_min, th_max, xp) return None,", "xp == np: # From eq. 27 to 37 C", "coeff to differentiate g_eos = xp.empty_like(eos_input) g_s_x1 = xp.empty_like(s_x1_input) g_s_x2", "inv_ro)) n = n_right / n_left # Gamma parameter (for", "Here 'x' is >0! z_s_x1 = xp.exp(s_x1_input) + 1e-10 z_s_x2", "saved, because they're reused in the backward phase self.z_eos =", "1, keepdims=True) # Get MDN coeff. Eq #18 to #22", "= 1. / (1. + xp.exp(eos_input)) # F.sigmoid. NOTE: usually", "s_x1_input_type, s_x2_input_type, rho_input_type = in_types type_check.expect( x_type.dtype.kind == 'f', eos_input_type.dtype.kind", "# Retain everything for backward if not type_check.same_types(*inputs): raise ValueError(\"numpy", "1e-10) - (1. - x3) * xp.log(1. - z_eos +", "/ xp.sum(exps, 1, keepdims=True) # Get MDN coeff. Eq #18", "import clip_grad #class MixtureDensityNetworkFunction(function_node.FunctionNode): class MixtureDensityNetworkFunction(function.Function): def check_type_forward(self, in_types): type_check.expect(in_types.size()", "1e-10) # sum + 1e-10 for computational stability, != nan!", "clip_grad(g_pi, th_min, th_max, xp) g_mu_x1 = clip_grad(g_mu_x1, th_min, th_max, xp)", "(Variable): End-of-stroke prediction pi (Variable): mixture components mu_x1 (Variable): mean", "g_pi, T g_mu_x1, T g_mu_x2, T g_s_x1, T g_s_x2, T", "'f', mu_x2_input_type.dtype.kind == 'f', s_x1_input_type.dtype.kind == 'f', s_x2_input_type.dtype.kind == 'f',", "in the backward phase self.z_eos = z_eos self.z_s_x1 = z_s_x1", "x_type.dtype.kind == 'f', eos_input_type.dtype.kind == 'f', pi_input_type.dtype.kind == 'f', mu_x1_input_type.dtype.kind", "1e-10 for computational stability n_right = xp.exp(-z / (2. *", "self.z_rho = z_rho self.z_pi = z_pi self.z_mu_x1 = z_mu_x1 self.z_mu_x2", "mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = inputs # MDN coeff", "- z_eos + 1e-10) loss = loss_y + loss_x #", "import numpy as np #from chainer import function_node from utils", ">= 2, x_type.shape[0] == eos_input_type.shape[0], x_type.shape[0] == pi_input_type.shape[0], x_type.shape[0] ==", "grad_outputs): xp = cuda.get_array_module(*inputs) #x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input,", "self.mask g_pi = (self.z_pi - self.gamma) * self.mask g_mu_x1 =", "xp) g_s_x2 = clip_grad(g_s_x2, th_min, th_max, xp) g_rho = clip_grad(g_rho,", "loss. x1 = x[:, 0:1] x2 = x[:, 1:2] x3", "# 'T x1, T x2, T eos_input, T pi_input, T", "= clip_grad(g_rho, th_min, th_max, xp) return None, g_eos, g_pi, g_mu_x1,", "for computational stability, != nan! self.gamma = gamma # Sequence", "exps / xp.sum(exps, 1, keepdims=True) # Get MDN coeff. Eq", "== 'f', pi_input_type.dtype.kind == 'f', mu_x1_input_type.dtype.kind == 'f', mu_x2_input_type.dtype.kind ==", "* (1. - x3) #loss_x = -xp.log(loss_x) loss_x = -x3", "coeff. Eq #18 to #22 z_eos = 1. / (1.", "= mu_x1_input z_mu_x2 = mu_x2_input # The MDN coeff are", "th_max, xp) g_mu_x2 = clip_grad(g_mu_x2, th_min, th_max, xp) g_s_x1 =", "'T x1, T x2, T eos_input, T pi_input, T mu_x1_input,", "z_mu_x1 = mu_x1_input z_mu_x2 = mu_x2_input # The MDN coeff", "rho): \"\"\" Mixture Density Network Output the coefficient params Args:", "* xp.log(z_eos + 1e-10) - (1. - x3) * xp.log(1.", "/ self.z_s_x1 d_norm_x2 = (x2 - self.z_mu_x2) / self.z_s_x2 d_rho_norm_x1", "differentiate g_eos = xp.empty_like(eos_input) g_s_x1 = xp.empty_like(s_x1_input) g_s_x2 = xp.empty_like(s_x2_input)", "{3}, type(mu_x2_input): {4}, type(s_x1_input): {5}\" \"type(s_x2_input): {6}, type(rho_input): {7}\" .format(type(x),", "1, keepdims=True) + 1e-10 # + 1e-10 for computational stability,", "self.z_s_x1 d_norm_x2 = (x2 - self.z_mu_x2) / self.z_s_x2 d_rho_norm_x1 =", "eos (Variable): End-of-stroke prediction pi (Variable): mixture components mu_x1 (Variable):", "rho_input_type.dtype.kind == 'f', x_type.ndim >= 2, eos_input_type.ndim >= 2, x_type.shape[0]", "== 'f', mu_x1_input_type.dtype.kind == 'f', mu_x2_input_type.dtype.kind == 'f', s_x1_input_type.dtype.kind ==", "z_s_x1, z_s_x2, z_rho, def backward(self, inputs, grad_outputs): xp = cuda.get_array_module(*inputs)", "2. * np.pi * z_s_x1 * z_s_x2 * xp.sqrt(inv_ro) +", "cuda.get_array_module(*inputs) def softmax(x): shiftx = x - x.max() exps =", "/ (xp.sum(gamma, 1, keepdims=True) + 1e-10) # sum + 1e-10", "x2 = x[:, 1:2] x3 = x[:, 2:3] #if xp", "0:1] x2 = x[:, 1:2] x3 = x[:, 2:3] #", "self.mask g_s_x1 = - self.gamma * ((C*d_norm_x1) * (d_norm_x1 -", "return None, g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho, def", "(1. - z_eos) * (1. - x3) #loss_x = -xp.log(loss_x)", "* d_norm_x1 d_rho_norm_x2 = self.z_rho * d_norm_x2 g_eos = (x3", "== 'f', rho_input_type.dtype.kind == 'f', x_type.ndim >= 2, eos_input_type.ndim >=", "* z_s_x2 * xp.sqrt(inv_ro) + 1e-10 # + 1e-10 for", "(1. - x3) #loss_x = -xp.log(loss_x) loss_x = -x3 *", "d_rho_norm_x2) - 1.) * self.mask g_s_x2 = - self.gamma *", "sum + 1e-10 for computational stability, != nan! self.gamma =", "- xp.square(z_rho) + 1e-10 n_left = 2. * np.pi *", "x3 + (1. - z_eos) * (1. - x3) #loss_x", "z_eos + 1e-10) loss = loss_y + loss_x # Mask", "* (d_norm_x2 - d_rho_norm_x1)) * self.mask g_s_x1 = - self.gamma", "chainer.utils import type_check from chainer import cuda from chainer import", "usually sigmoid is 1/(1+e^-x). Here 'x' is >0! z_s_x1 =", "{7}\" .format(type(x), type(eos_input), type(pi_input), type(mu_x1_input), type(mu_x2_input), type(s_x1_input), type(s_x2_input), type(rho_input))) xp", "z_rho, def backward(self, inputs, grad_outputs): xp = cuda.get_array_module(*inputs) #x, eos_input,", "1e-10 n_left = 2. * np.pi * z_s_x1 * z_s_x2", "= xp.empty_like(s_x2_input) g_rho = xp.empty_like(rho_input) g_pi = xp.empty_like(pi_input) g_mu_x1 =", "/ (1. - self.z_rho*self.z_rho + 1e-10) d_norm_x1 = (x1 -", "d_rho_norm_x1) - 1.) * self.mask g_rho = - self.gamma *", "type_check.same_types(*inputs): raise ValueError(\"numpy and cupy must not be used together\\n\"", "= xp.ones_like(x3) mask[idx_mask, 0] = 0. self.mask = mask loss", "== 2 (added padding) idx_mask = xp.where(x3==2)[0] mask = xp.ones_like(x3)", "Mixture Density Network Output the coefficient params Args: x (Variable):", "of x1 mu_x2 (Variable): mean of x2 s_x1 (Variable): variance", "xp.sum(z_pi, 1, keepdims=True) z_mu_x1 = mu_x1_input z_mu_x2 = mu_x2_input #", "(1. - self.z_rho*self.z_rho + 1e-10) d_norm_x1 = (x1 - self.z_mu_x1)", "g_mu_x2, T g_s_x1, T g_s_x2, T g_rho', # ) #", "everything for backward if not type_check.same_types(*inputs): raise ValueError(\"numpy and cupy", "at the begining loss_y is exactly 0 sometime loss_y =", "g_pi = (self.z_pi - self.gamma) * self.mask g_mu_x1 = -", "loss_y + loss_x # Mask guard to check if x3", "x2, T eos_input, T pi_input, T mu_x1_input, T mu_x2_input, T", "!= nan! self.gamma = gamma # Sequence loss. Eq. 26", "self.z_rho * d_norm_x1 d_rho_norm_x2 = self.z_rho * d_norm_x2 g_eos =", "pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = self.get_retained_inputs() x, eos_input,", "(Variable): variance of x2 rho (Variable): correlation parameter Returns: loss", "pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = inputs #self.retain_inputs(range(len(inputs))) #", "reused in the backward phase self.z_eos = z_eos self.z_s_x1 =", "stability, != nan #epsilon = xp.full(loss_y.shape, 1e-10, dtype=xp.float32) #loss_y =", "/ xp.sum(z_pi, 1, keepdims=True) z_mu_x1 = mu_x1_input z_mu_x2 = mu_x2_input", "# Because at the begining loss_y is exactly 0 sometime", "= xp.empty_like(rho_input) g_pi = xp.empty_like(pi_input) g_mu_x1 = xp.empty_like(mu_x1_input) g_mu_x2 =", "and cupy must not be used together\\n\" \"type(x): {0}, type(eos_input):", "mu_x1_input_type.dtype.kind == 'f', mu_x2_input_type.dtype.kind == 'f', s_x1_input_type.dtype.kind == 'f', s_x2_input_type.dtype.kind", "clip_grad #class MixtureDensityNetworkFunction(function_node.FunctionNode): class MixtureDensityNetworkFunction(function.Function): def check_type_forward(self, in_types): type_check.expect(in_types.size() ==", "# ) # Add grad_clipping here if it explodes P.23", "(d_norm_x1 - d_rho_norm_x2)) * self.mask g_mu_x2 = - self.gamma *", "#z_pi = xp.exp(pi_input) #z_pi = z_pi / xp.sum(z_pi, 1, keepdims=True)", "= xp.empty_like(pi_input) g_mu_x1 = xp.empty_like(mu_x1_input) g_mu_x2 = xp.empty_like(mu_x2_input) # Compute", "g_eos = (x3 - self.z_eos) * self.mask g_pi = (self.z_pi", "loss. Eq. 26 loss_y = z_pi * n loss_y =", "type(s_x2_input), type(rho_input))) xp = cuda.get_array_module(*inputs) def softmax(x): shiftx = x", "x1 mu_x2 (Variable): mean of x2 s_x1 (Variable): variance of", "x3) * xp.log(1. - z_eos + 1e-10) loss = loss_y", "d_rho_norm_x1)) * self.mask g_s_x1 = - self.gamma * ((C*d_norm_x1) *", "x[:, 2:3] #if xp == np: # From eq. 27", "numpy as np #from chainer import function_node from utils import", "x_type.shape[0] == pi_input_type.shape[0], x_type.shape[0] == mu_x1_input_type.shape[0], x_type.shape[0] == mu_x2_input_type.shape[0], x_type.shape[0]", "2 (added padding) idx_mask = xp.where(x3==2)[0] mask = xp.ones_like(x3) mask[idx_mask,", "T g_s_x2, T g_rho', # ) # Add grad_clipping here", "= z_pi self.z_mu_x1 = z_mu_x1 self.z_mu_x2 = z_mu_x2 # Compute", "loss *= mask return loss, x, z_eos, z_pi, z_mu_x1, z_mu_x2,", "self.z_mu_x1 = z_mu_x1 self.z_mu_x2 = z_mu_x2 # Compute the loss.", "T s_x2_input, T rho_input', # 'T g_eos, T g_pi, T", "position [x1, x2, x3] to predict eos (Variable): End-of-stroke prediction", "(d_norm_x2 - d_rho_norm_x1)) * self.mask g_s_x1 = - self.gamma *", "z_right self.z = z # Normal function. Eq. 24. inv_ro", "= z_s_x1 self.z_s_x2 = z_s_x2 self.z_rho = z_rho self.z_pi =", "= xp.exp(-z / (2. * inv_ro)) n = n_right /", "def forward(self, inputs): x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input,", "1e-10) loss = loss_y + loss_x # Mask guard to", "= mask loss *= mask return loss, x, z_eos, z_pi,", "idx_mask = xp.where(x3==2)[0] mask = xp.ones_like(x3) mask[idx_mask, 0] = 0.", "g_eos, T g_pi, T g_mu_x1, T g_mu_x2, T g_s_x1, T", "z_rho self.z_pi = z_pi self.z_mu_x1 = z_mu_x1 self.z_mu_x2 = z_mu_x2", "= clip_grad(g_s_x2, th_min, th_max, xp) g_rho = clip_grad(g_rho, th_min, th_max,", "== mu_x1_input_type.shape[1], mu_x1_input_type.shape[1] == mu_x2_input_type.shape[1], mu_x2_input_type.shape[1] == s_x1_input_type.shape[1], s_x1_input_type.shape[1] ==", "chainer import cuda from chainer import function import numpy as", "\"type(s_x2_input): {6}, type(rho_input): {7}\" .format(type(x), type(eos_input), type(pi_input), type(mu_x1_input), type(mu_x2_input), type(s_x1_input),", "np #from chainer import function_node from utils import clip_grad #class", "mixture_density_network(x, eos, pi, mu_x1, mu_x2, s_x1, s_x2, rho): \"\"\" Mixture", "import chainer.functions from chainer.utils import type_check from chainer import cuda", "eos_input_type.dtype.kind == 'f', pi_input_type.dtype.kind == 'f', mu_x1_input_type.dtype.kind == 'f', mu_x2_input_type.dtype.kind", "mu_x2_input, s_x1_input, s_x2_input, rho_input = inputs #self.retain_inputs(range(len(inputs))) # Retain everything", "== np: # From eq. 27 to 37 C =", "= clip_grad(g_pi, th_min, th_max, xp) g_mu_x1 = clip_grad(g_mu_x1, th_min, th_max,", "x1 = x[:, 0:1] x2 = x[:, 1:2] x3 =", "x[:, 0:1] x2 = x[:, 1:2] x3 = x[:, 2:3]", "# Normal function. Eq. 24. inv_ro = 1. - xp.square(z_rho)", "(Variable): mean of x2 s_x1 (Variable): variance of x1 s_x2", "x2 = x[:, 1:2] x3 = x[:, 2:3] # Z", "= xp.exp(shiftx) return exps / xp.sum(exps, 1, keepdims=True) # Get", "to 37 C = 1. / (1. - self.z_rho*self.z_rho +", "T mu_x1_input, T mu_x2_input, T s_x1_input, T s_x2_input, T rho_input',", "== 'f', eos_input_type.dtype.kind == 'f', pi_input_type.dtype.kind == 'f', mu_x1_input_type.dtype.kind ==", "chainer import function_node from utils import clip_grad #class MixtureDensityNetworkFunction(function_node.FunctionNode): class", "#self.retain_inputs(range(len(inputs))) # Retain everything for backward if not type_check.same_types(*inputs): raise", "s_x1_input_type.shape[1] == s_x2_input_type.shape[1], s_x2_input_type.shape[1] == rho_input_type.shape[1] ) pass def forward(self,", "x_type.shape[0] == s_x2_input_type.shape[0], x_type.shape[0] == rho_input_type.shape[0], pi_input_type.shape[1] == mu_x1_input_type.shape[1], mu_x1_input_type.shape[1]", "= x[:, 0:1] x2 = x[:, 1:2] x3 = x[:,", "gamma = gamma / (xp.sum(gamma, 1, keepdims=True) + 1e-10) #", "= - self.gamma * ((C*d_norm_x2) * (d_norm_x2 - d_rho_norm_x1) -", "d_norm_x2 g_eos = (x3 - self.z_eos) * self.mask g_pi =", "xp.sum(exps, 1, keepdims=True) # Get MDN coeff. Eq #18 to", "x_type.shape[0] == eos_input_type.shape[0], x_type.shape[0] == pi_input_type.shape[0], x_type.shape[0] == mu_x1_input_type.shape[0], x_type.shape[0]", "rho_input = inputs # MDN coeff to differentiate g_eos =", "backward if not type_check.same_types(*inputs): raise ValueError(\"numpy and cupy must not", "x (Variable): Tensor containing the position [x1, x2, x3] to", "1, keepdims=True) + 1e-10) # sum + 1e-10 for computational", "- self.z_eos) * self.mask g_pi = (self.z_pi - self.gamma) *", "-100.0 th_max = 100.0 g_eos = clip_grad(g_eos, th_min, th_max, xp)", "because they're reused in the backward phase self.z_eos = z_eos", "s_x2, rho): \"\"\" Mixture Density Network Output the coefficient params", "keepdims=True) z_mu_x1 = mu_x1_input z_mu_x2 = mu_x2_input # The MDN", "+ 1e-10) loss = loss_y + loss_x # Mask guard", "backward(self, inputs, grad_outputs): xp = cuda.get_array_module(*inputs) #x, eos_input, pi_input, mu_x1_input,", "Mask guard to check if x3 == 2 (added padding)", "def check_type_forward(self, in_types): type_check.expect(in_types.size() == 8) x_type, eos_input_type, pi_input_type, mu_x1_input_type,", "= z_s_x2 self.z_rho = z_rho self.z_pi = z_pi self.z_mu_x1 =", "= gamma # Sequence loss. Eq. 26 loss_y = z_pi", "== 8) x_type, eos_input_type, pi_input_type, mu_x1_input_type, mu_x2_input_type, s_x1_input_type, s_x2_input_type, rho_input_type", "xp.where(x3==2)[0] mask = xp.ones_like(x3) mask[idx_mask, 0] = 0. self.mask =", "g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho = cuda.elementwise( # 'T", "d_norm_x1 d_rho_norm_x2 = self.z_rho * d_norm_x2 g_eos = (x3 -", "self.z_rho*(1. - C * self.z)) * self.mask #else: # g_eos,", "T pi_input, T mu_x1_input, T mu_x2_input, T s_x1_input, T s_x2_input,", "mu_x2_input, T s_x1_input, T s_x2_input, T rho_input', # 'T g_eos,", "1:2] x3 = x[:, 2:3] # Z variable. Eq. 25", "* np.pi * z_s_x1 * z_s_x2 * xp.sqrt(inv_ro) + 1e-10", "xp.exp(eos_input)) # F.sigmoid. NOTE: usually sigmoid is 1/(1+e^-x). Here 'x'", "correlation parameter Returns: loss (Variable) y (Variable) eos (Variable) pi", "xp) return None, g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho,", "\"type(x): {0}, type(eos_input): {1}, type(pi_input): {2}\" \"type(mu_x1_input): {3}, type(mu_x2_input): {4},", "z_pi = softmax(pi_input) #z_pi = xp.exp(pi_input) #z_pi = z_pi /", "d_rho_norm_x2 = self.z_rho * d_norm_x2 g_eos = (x3 - self.z_eos)", "x2, x3] to predict eos (Variable): End-of-stroke prediction pi (Variable):", "type(pi_input): {2}\" \"type(mu_x1_input): {3}, type(mu_x2_input): {4}, type(s_x1_input): {5}\" \"type(s_x2_input): {6},", "# Get MDN coeff. Eq #18 to #22 z_eos =", "self.mask g_mu_x2 = - self.gamma * ((C/self.z_s_x2) * (d_norm_x2 -", ".format(type(x), type(eos_input), type(pi_input), type(mu_x1_input), type(mu_x2_input), type(s_x1_input), type(s_x2_input), type(rho_input))) xp =", "explodes P.23 th_min = -100.0 th_max = 100.0 g_eos =", "z_eos self.z_s_x1 = z_s_x1 self.z_s_x2 = z_s_x2 self.z_rho = z_rho", "clip_grad(g_mu_x1, th_min, th_max, xp) g_mu_x2 = clip_grad(g_mu_x2, th_min, th_max, xp)", "= 2. * np.pi * z_s_x1 * z_s_x2 * xp.sqrt(inv_ro)", "eos_input_type.ndim >= 2, x_type.shape[0] == eos_input_type.shape[0], x_type.shape[0] == pi_input_type.shape[0], x_type.shape[0]", "mask[idx_mask, 0] = 0. self.mask = mask loss *= mask", "g_mu_x2 = clip_grad(g_mu_x2, th_min, th_max, xp) g_s_x1 = clip_grad(g_s_x1, th_min,", "xp.empty_like(mu_x2_input) # Compute the gradient x1 = x[:, 0:1] x2", "s_x1_input_type.dtype.kind == 'f', s_x2_input_type.dtype.kind == 'f', rho_input_type.dtype.kind == 'f', x_type.ndim", "x[:, 2:3] # Z variable. Eq. 25 norm_x1 = x1", "rho (Variable) \"\"\" return MixtureDensityNetworkFunction()(x, eos, pi, mu_x1, mu_x2, s_x1,", "- 1.) * self.mask g_s_x2 = - self.gamma * ((C*d_norm_x2)", "T eos_input, T pi_input, T mu_x1_input, T mu_x2_input, T s_x1_input,", "1e-10 # + 1e-10 for computational stability, != nan #epsilon", "coefficient params Args: x (Variable): Tensor containing the position [x1,", "+ 1e-10 n_left = 2. * np.pi * z_s_x1 *", "softmax(x): shiftx = x - x.max() exps = xp.exp(shiftx) return", "# + 1e-10 for computational stability n_right = xp.exp(-z /", "chainer import function import numpy as np #from chainer import", "utils import clip_grad #class MixtureDensityNetworkFunction(function_node.FunctionNode): class MixtureDensityNetworkFunction(function.Function): def check_type_forward(self, in_types):", "= (x3 - self.z_eos) * self.mask g_pi = (self.z_pi -", "1. / (1. - self.z_rho*self.z_rho + 1e-10) d_norm_x1 = (x1", "backward phase self.z_eos = z_eos self.z_s_x1 = z_s_x1 self.z_s_x2 =", "th_max = 100.0 g_eos = clip_grad(g_eos, th_min, th_max, xp) g_pi", "rho_input = inputs #self.retain_inputs(range(len(inputs))) # Retain everything for backward if", "= xp.full(loss_y.shape, 1e-10, dtype=xp.float32) #loss_y = xp.maximum(loss_y, epsilon) # Because", "self.z_s_x2 d_rho_norm_x1 = self.z_rho * d_norm_x1 d_rho_norm_x2 = self.z_rho *", "loss (Variable) y (Variable) eos (Variable) pi (Variable) mu_x1 (Variable)", "rho_input = self.get_retained_inputs() x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input,", "s_x1 (Variable) s_x2 (Variable) rho (Variable) \"\"\" return MixtureDensityNetworkFunction()(x, eos,", "type(rho_input))) xp = cuda.get_array_module(*inputs) def softmax(x): shiftx = x -", "'f', x_type.ndim >= 2, eos_input_type.ndim >= 2, x_type.shape[0] == eos_input_type.shape[0],", "mu_x2_input_type.shape[0], x_type.shape[0] == s_x1_input_type.shape[0], x_type.shape[0] == s_x2_input_type.shape[0], x_type.shape[0] == rho_input_type.shape[0],", "g_rho = clip_grad(g_rho, th_min, th_max, xp) return None, g_eos, g_pi,", "= z_rho self.z_pi = z_pi self.z_mu_x1 = z_mu_x1 self.z_mu_x2 =", "x3 = x[:, 2:3] # Z variable. Eq. 25 norm_x1", "g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho, def mixture_density_network(x, eos,", "mean of x2 s_x1 (Variable): variance of x1 s_x2 (Variable):", "g_mu_x2, g_s_x1, g_s_x2, g_rho, def mixture_density_network(x, eos, pi, mu_x1, mu_x2,", "- z_mu_x1 norm_x2 = x2 - z_mu_x2 z_left = (xp.square(norm_x1)/xp.square(z_s_x1))", "th_max, xp) g_mu_x1 = clip_grad(g_mu_x1, th_min, th_max, xp) g_mu_x2 =", "g_mu_x2 = xp.empty_like(mu_x2_input) # Compute the gradient x1 = x[:,", "MixtureDensityNetworkFunction(function.Function): def check_type_forward(self, in_types): type_check.expect(in_types.size() == 8) x_type, eos_input_type, pi_input_type,", "'T g_eos, T g_pi, T g_mu_x1, T g_mu_x2, T g_s_x1,", "s_x1_input_type.shape[0], x_type.shape[0] == s_x2_input_type.shape[0], x_type.shape[0] == rho_input_type.shape[0], pi_input_type.shape[1] == mu_x1_input_type.shape[1],", "g_s_x1, T g_s_x2, T g_rho', # ) # Add grad_clipping", "exactly 0 sometime loss_y = -xp.log(loss_y + 1e-10) #loss_x =", "xp) g_rho = clip_grad(g_rho, th_min, th_max, xp) return None, g_eos,", "s_x1 (Variable): variance of x1 s_x2 (Variable): variance of x2", "x_type.shape[0] == mu_x2_input_type.shape[0], x_type.shape[0] == s_x1_input_type.shape[0], x_type.shape[0] == s_x2_input_type.shape[0], x_type.shape[0]", "{5}\" \"type(s_x2_input): {6}, type(rho_input): {7}\" .format(type(x), type(eos_input), type(pi_input), type(mu_x1_input), type(mu_x2_input),", "Returns: loss (Variable) y (Variable) eos (Variable) pi (Variable) mu_x1", "Eq. 28-29 gamma = z_pi * n gamma = gamma", "mu_x2 (Variable): mean of x2 s_x1 (Variable): variance of x1", "- d_rho_norm_x1)) * self.mask g_s_x1 = - self.gamma * ((C*d_norm_x1)", "type(rho_input): {7}\" .format(type(x), type(eos_input), type(pi_input), type(mu_x1_input), type(mu_x2_input), type(s_x1_input), type(s_x2_input), type(rho_input)))", "= - self.gamma * ((C/self.z_s_x2) * (d_norm_x2 - d_rho_norm_x1)) *", "z_mu_x2 z_left = (xp.square(norm_x1)/xp.square(z_s_x1)) + (xp.square(norm_x2)/xp.square(z_s_x2)) z_right = (2.*z_rho*norm_x1*norm_x2)/(z_s_x1*z_s_x2) z", "(Variable): variance of x1 s_x2 (Variable): variance of x2 rho", "mu_x2_input_type, s_x1_input_type, s_x2_input_type, rho_input_type = in_types type_check.expect( x_type.dtype.kind == 'f',", "s_x1_input, T s_x2_input, T rho_input', # 'T g_eos, T g_pi,", "(d_norm_x1*d_norm_x2 + self.z_rho*(1. - C * self.z)) * self.mask #else:", "The MDN coeff are saved, because they're reused in the", "s_x1_input, s_x2_input, rho_input = self.get_retained_inputs() x, eos_input, pi_input, mu_x1_input, mu_x2_input,", "z_pi self.z_mu_x1 = z_mu_x1 self.z_mu_x2 = z_mu_x2 # Compute the", "= z_eos self.z_s_x1 = z_s_x1 self.z_s_x2 = z_s_x2 self.z_rho =", "= loss_y + loss_x # Mask guard to check if", "type(eos_input): {1}, type(pi_input): {2}\" \"type(mu_x1_input): {3}, type(mu_x2_input): {4}, type(s_x1_input): {5}\"", "z_eos * x3 + (1. - z_eos) * (1. -", "g_pi = xp.empty_like(pi_input) g_mu_x1 = xp.empty_like(mu_x1_input) g_mu_x2 = xp.empty_like(mu_x2_input) #", "z_mu_x2 # Compute the loss. x1 = x[:, 0:1] x2", "pi, mu_x1, mu_x2, s_x1, s_x2, rho): \"\"\" Mixture Density Network", "== mu_x2_input_type.shape[1], mu_x2_input_type.shape[1] == s_x1_input_type.shape[1], s_x1_input_type.shape[1] == s_x2_input_type.shape[1], s_x2_input_type.shape[1] ==", "F.sigmoid. NOTE: usually sigmoid is 1/(1+e^-x). Here 'x' is >0!", "Compute the gradient x1 = x[:, 0:1] x2 = x[:,", "inputs #self.retain_inputs(range(len(inputs))) # Retain everything for backward if not type_check.same_types(*inputs):", "* self.mask g_rho = - self.gamma * (d_norm_x1*d_norm_x2 + self.z_rho*(1.", "T g_mu_x1, T g_mu_x2, T g_s_x1, T g_s_x2, T g_rho',", "g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho, def mixture_density_network(x, eos, pi, mu_x1,", "0] = 0. self.mask = mask loss *= mask return", "== rho_input_type.shape[1] ) pass def forward(self, inputs): x, eos_input, pi_input,", "== s_x1_input_type.shape[0], x_type.shape[0] == s_x2_input_type.shape[0], x_type.shape[0] == rho_input_type.shape[0], pi_input_type.shape[1] ==", "th_min, th_max, xp) return None, g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1,", "xp.maximum(loss_y, epsilon) # Because at the begining loss_y is exactly", "mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = self.get_retained_inputs() x, eos_input, pi_input,", "phase self.z_eos = z_eos self.z_s_x1 = z_s_x1 self.z_s_x2 = z_s_x2", "1/(1+e^-x). Here 'x' is >0! z_s_x1 = xp.exp(s_x1_input) + 1e-10", "= (x1 - self.z_mu_x1) / self.z_s_x1 d_norm_x2 = (x2 -", "ValueError(\"numpy and cupy must not be used together\\n\" \"type(x): {0},", "return loss, x, z_eos, z_pi, z_mu_x1, z_mu_x2, z_s_x1, z_s_x2, z_rho,", "it explodes P.23 th_min = -100.0 th_max = 100.0 g_eos", "eos_input_type, pi_input_type, mu_x1_input_type, mu_x2_input_type, s_x1_input_type, s_x2_input_type, rho_input_type = in_types type_check.expect(", "x1 s_x2 (Variable): variance of x2 rho (Variable): correlation parameter", "= (x2 - self.z_mu_x2) / self.z_s_x2 d_rho_norm_x1 = self.z_rho *", "(2. * inv_ro)) n = n_right / n_left # Gamma", "= self.z_rho * d_norm_x2 g_eos = (x3 - self.z_eos) *", "s_x1_input_type.shape[1], s_x1_input_type.shape[1] == s_x2_input_type.shape[1], s_x2_input_type.shape[1] == rho_input_type.shape[1] ) pass def", "Sequence loss. Eq. 26 loss_y = z_pi * n loss_y", "(x1 - self.z_mu_x1) / self.z_s_x1 d_norm_x2 = (x2 - self.z_mu_x2)", "== 'f', mu_x2_input_type.dtype.kind == 'f', s_x1_input_type.dtype.kind == 'f', s_x2_input_type.dtype.kind ==", "= 100.0 g_eos = clip_grad(g_eos, th_min, th_max, xp) g_pi =", "(Variable) mu_x1 (Variable) mu_x2 (Variable) s_x1 (Variable) s_x2 (Variable) rho", "+ (1. - z_eos) * (1. - x3) #loss_x =", "self.mask g_rho = - self.gamma * (d_norm_x1*d_norm_x2 + self.z_rho*(1. -", "sigmoid is 1/(1+e^-x). Here 'x' is >0! z_s_x1 = xp.exp(s_x1_input)", "softmax(pi_input) #z_pi = xp.exp(pi_input) #z_pi = z_pi / xp.sum(z_pi, 1,", "z_pi * n gamma = gamma / (xp.sum(gamma, 1, keepdims=True)", "import function_node from utils import clip_grad #class MixtureDensityNetworkFunction(function_node.FunctionNode): class MixtureDensityNetworkFunction(function.Function):", "37 C = 1. / (1. - self.z_rho*self.z_rho + 1e-10)", "C * self.z)) * self.mask #else: # g_eos, g_pi, g_mu_x1,", "(xp.sum(gamma, 1, keepdims=True) + 1e-10) # sum + 1e-10 for", "28-29 gamma = z_pi * n gamma = gamma /", "= -xp.log(loss_y + 1e-10) #loss_x = z_eos * x3 +", "of x2 rho (Variable): correlation parameter Returns: loss (Variable) y", "eos_input_type.shape[0], x_type.shape[0] == pi_input_type.shape[0], x_type.shape[0] == mu_x1_input_type.shape[0], x_type.shape[0] == mu_x2_input_type.shape[0],", "1, keepdims=True) z_mu_x1 = mu_x1_input z_mu_x2 = mu_x2_input # The", "= mu_x2_input # The MDN coeff are saved, because they're", "= x[:, 1:2] x3 = x[:, 2:3] # Z variable.", "th_min, th_max, xp) g_s_x1 = clip_grad(g_s_x1, th_min, th_max, xp) g_s_x2", "loss, x, z_eos, z_pi, z_mu_x1, z_mu_x2, z_s_x1, z_s_x2, z_rho, def", "* self.mask g_mu_x1 = - self.gamma * ((C/self.z_s_x1) * (d_norm_x1", "n_left # Gamma parameter (for the backward phase). Eq. 28-29", "Because at the begining loss_y is exactly 0 sometime loss_y", "inv_ro = 1. - xp.square(z_rho) + 1e-10 n_left = 2.", "z_pi, z_mu_x1, z_mu_x2, z_s_x1, z_s_x2, z_rho, def backward(self, inputs, grad_outputs):", "[x1, x2, x3] to predict eos (Variable): End-of-stroke prediction pi", ") pass def forward(self, inputs): x, eos_input, pi_input, mu_x1_input, mu_x2_input,", "x, eos_input, pi_input, mu_x1_input, mu_x2_input, s_x1_input, s_x2_input, rho_input = inputs", "to #22 z_eos = 1. / (1. + xp.exp(eos_input)) #", "if x3 == 2 (added padding) idx_mask = xp.where(x3==2)[0] mask", "xp.log(1. - z_eos + 1e-10) loss = loss_y + loss_x", "n_left = 2. * np.pi * z_s_x1 * z_s_x2 *", "((C*d_norm_x1) * (d_norm_x1 - d_rho_norm_x2) - 1.) * self.mask g_s_x2", "self.mask #else: # g_eos, g_pi, g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho", "MDN coeff to differentiate g_eos = xp.empty_like(eos_input) g_s_x1 = xp.empty_like(s_x1_input)", "# F.sigmoid. NOTE: usually sigmoid is 1/(1+e^-x). Here 'x' is", "begining loss_y is exactly 0 sometime loss_y = -xp.log(loss_y +", "z_pi * n loss_y = xp.sum(loss_y, 1, keepdims=True) + 1e-10", "1e-10 z_rho = xp.tanh(rho_input) z_pi = softmax(pi_input) #z_pi = xp.exp(pi_input)", "(added padding) idx_mask = xp.where(x3==2)[0] mask = xp.ones_like(x3) mask[idx_mask, 0]", "z_s_x2 self.z_rho = z_rho self.z_pi = z_pi self.z_mu_x1 = z_mu_x1", "n = n_right / n_left # Gamma parameter (for the", "g_mu_x1, g_mu_x2, g_s_x1, g_s_x2, g_rho = cuda.elementwise( # 'T x1,", "mu_x2_input # The MDN coeff are saved, because they're reused", "z_s_x2 = xp.exp(s_x2_input) + 1e-10 z_rho = xp.tanh(rho_input) z_pi =", "+ 1e-10 for computational stability, != nan #epsilon = xp.full(loss_y.shape,", "NOTE: usually sigmoid is 1/(1+e^-x). Here 'x' is >0! z_s_x1", "of x1 s_x2 (Variable): variance of x2 rho (Variable): correlation", "type(pi_input), type(mu_x1_input), type(mu_x2_input), type(s_x1_input), type(s_x2_input), type(rho_input))) xp = cuda.get_array_module(*inputs) def", "inputs, grad_outputs): xp = cuda.get_array_module(*inputs) #x, eos_input, pi_input, mu_x1_input, mu_x2_input,", "= xp.empty_like(mu_x2_input) # Compute the gradient x1 = x[:, 0:1]", "= z_eos * x3 + (1. - z_eos) * (1.", "x_type, eos_input_type, pi_input_type, mu_x1_input_type, mu_x2_input_type, s_x1_input_type, s_x2_input_type, rho_input_type = in_types", "= xp.empty_like(eos_input) g_s_x1 = xp.empty_like(s_x1_input) g_s_x2 = xp.empty_like(s_x2_input) g_rho =", "loss_y = -xp.log(loss_y + 1e-10) #loss_x = z_eos * x3", "rho_input', # 'T g_eos, T g_pi, T g_mu_x1, T g_mu_x2,", "== pi_input_type.shape[0], x_type.shape[0] == mu_x1_input_type.shape[0], x_type.shape[0] == mu_x2_input_type.shape[0], x_type.shape[0] ==", "= -x3 * xp.log(z_eos + 1e-10) - (1. - x3)", "s_x2_input, rho_input = inputs # MDN coeff to differentiate g_eos", "n loss_y = xp.sum(loss_y, 1, keepdims=True) + 1e-10 # +", "xp.empty_like(rho_input) g_pi = xp.empty_like(pi_input) g_mu_x1 = xp.empty_like(mu_x1_input) g_mu_x2 = xp.empty_like(mu_x2_input)", "Z variable. Eq. 25 norm_x1 = x1 - z_mu_x1 norm_x2", "Gamma parameter (for the backward phase). Eq. 28-29 gamma =", "they're reused in the backward phase self.z_eos = z_eos self.z_s_x1", "-x3 * xp.log(z_eos + 1e-10) - (1. - x3) *", "'f', s_x1_input_type.dtype.kind == 'f', s_x2_input_type.dtype.kind == 'f', rho_input_type.dtype.kind == 'f',", "z_mu_x2, z_s_x1, z_s_x2, z_rho, def backward(self, inputs, grad_outputs): xp =", "xp.empty_like(eos_input) g_s_x1 = xp.empty_like(s_x1_input) g_s_x2 = xp.empty_like(s_x2_input) g_rho = xp.empty_like(rho_input)", "Get MDN coeff. Eq #18 to #22 z_eos = 1.", "# Sequence loss. Eq. 26 loss_y = z_pi * n", "x, z_eos, z_pi, z_mu_x1, z_mu_x2, z_s_x1, z_s_x2, z_rho, def backward(self,", "- d_rho_norm_x2)) * self.mask g_mu_x2 = - self.gamma * ((C/self.z_s_x2)", "+ xp.exp(eos_input)) # F.sigmoid. NOTE: usually sigmoid is 1/(1+e^-x). Here", "mu_x1_input z_mu_x2 = mu_x2_input # The MDN coeff are saved,", "import type_check from chainer import cuda from chainer import function", "= inputs #self.retain_inputs(range(len(inputs))) # Retain everything for backward if not", "= 1. / (1. - self.z_rho*self.z_rho + 1e-10) d_norm_x1 =", "= clip_grad(g_mu_x1, th_min, th_max, xp) g_mu_x2 = clip_grad(g_mu_x2, th_min, th_max,", "z_s_x1 = xp.exp(s_x1_input) + 1e-10 z_s_x2 = xp.exp(s_x2_input) + 1e-10", "End-of-stroke prediction pi (Variable): mixture components mu_x1 (Variable): mean of", "def backward(self, inputs, grad_outputs): xp = cuda.get_array_module(*inputs) #x, eos_input, pi_input,", "for backward if not type_check.same_types(*inputs): raise ValueError(\"numpy and cupy must", "loss = loss_y + loss_x # Mask guard to check" ]
[ "1 then handle each request in a new process #", "the process handle each request in a separate # thread?", "than 1 then handle each request in a new process", "__name__ == '__main__': app.debug = True # Localhost # port=0", "render_template('index.html') if __name__ == '__main__': app.debug = True # Localhost", "-*- __author__ = 'ipetrash' # SOURCE: https://github.com/twbs/bootstrap # SOURCE: https://github.com/gitbrent/bootstrap4-toggle", "each request in a new process # up to this", "if greater than 1 then handle each request in a", "greater than 1 then handle each request in a new", "SOURCE: https://gitbrent.github.io/bootstrap4-toggle/ from flask import Flask, render_template app = Flask(__name__)", "'ipetrash' # SOURCE: https://github.com/twbs/bootstrap # SOURCE: https://github.com/gitbrent/bootstrap4-toggle # SOURCE: https://gitbrent.github.io/bootstrap4-toggle/", "Flask, render_template app = Flask(__name__) import logging logging.basicConfig(level=logging.DEBUG) @app.route(\"/\") def", "# SOURCE: https://gitbrent.github.io/bootstrap4-toggle/ from flask import Flask, render_template app =", "a new process # up to this maximum number of", "<reponame>DazEB2/SimplePyScripts #!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ =", "in a new process # up to this maximum number", "= 'ipetrash' # SOURCE: https://github.com/twbs/bootstrap # SOURCE: https://github.com/gitbrent/bootstrap4-toggle # SOURCE:", "https://github.com/gitbrent/bootstrap4-toggle # SOURCE: https://gitbrent.github.io/bootstrap4-toggle/ from flask import Flask, render_template app", "random free port # app.run(port=0) app.run( port=5000, # :param threaded:", "# -*- coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE:", "-- random free port # app.run(port=0) app.run( port=5000, # :param", "should the process handle each request in a separate #", "def index(): return render_template('index.html') if __name__ == '__main__': app.debug =", "maximum number of concurrent processes. threaded=True, ) # # Public", "https://gitbrent.github.io/bootstrap4-toggle/ from flask import Flask, render_template app = Flask(__name__) import", "port=0 -- random free port # app.run(port=0) app.run( port=5000, #", "from flask import Flask, render_template app = Flask(__name__) import logging", "# port=0 -- random free port # app.run(port=0) app.run( port=5000,", "# up to this maximum number of concurrent processes. threaded=True,", "coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE: https://github.com/twbs/bootstrap #", "a separate # thread? # :param processes: if greater than", "in a separate # thread? # :param processes: if greater", "python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' #", "threaded: should the process handle each request in a separate", ":param processes: if greater than 1 then handle each request", "utf-8 -*- __author__ = 'ipetrash' # SOURCE: https://github.com/twbs/bootstrap # SOURCE:", "app.debug = True # Localhost # port=0 -- random free", "SOURCE: https://github.com/twbs/bootstrap # SOURCE: https://github.com/gitbrent/bootstrap4-toggle # SOURCE: https://gitbrent.github.io/bootstrap4-toggle/ from flask", "port=5000, # :param threaded: should the process handle each request", "# SOURCE: https://github.com/twbs/bootstrap # SOURCE: https://github.com/gitbrent/bootstrap4-toggle # SOURCE: https://gitbrent.github.io/bootstrap4-toggle/ from", ":param threaded: should the process handle each request in a", "handle each request in a separate # thread? # :param", "to this maximum number of concurrent processes. threaded=True, ) #", "up to this maximum number of concurrent processes. threaded=True, )", "Flask(__name__) import logging logging.basicConfig(level=logging.DEBUG) @app.route(\"/\") def index(): return render_template('index.html') if", "new process # up to this maximum number of concurrent", "processes: if greater than 1 then handle each request in", "request in a new process # up to this maximum", "this maximum number of concurrent processes. threaded=True, ) # #", "# app.run(port=0) app.run( port=5000, # :param threaded: should the process", "separate # thread? # :param processes: if greater than 1", "Localhost # port=0 -- random free port # app.run(port=0) app.run(", "flask import Flask, render_template app = Flask(__name__) import logging logging.basicConfig(level=logging.DEBUG)", "# thread? # :param processes: if greater than 1 then", "index(): return render_template('index.html') if __name__ == '__main__': app.debug = True", "logging logging.basicConfig(level=logging.DEBUG) @app.route(\"/\") def index(): return render_template('index.html') if __name__ ==", "__author__ = 'ipetrash' # SOURCE: https://github.com/twbs/bootstrap # SOURCE: https://github.com/gitbrent/bootstrap4-toggle #", "process # up to this maximum number of concurrent processes.", "free port # app.run(port=0) app.run( port=5000, # :param threaded: should", "app.run(port=0) app.run( port=5000, # :param threaded: should the process handle", "app.run( port=5000, # :param threaded: should the process handle each", "process handle each request in a separate # thread? #", "thread? # :param processes: if greater than 1 then handle", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash'", "render_template app = Flask(__name__) import logging logging.basicConfig(level=logging.DEBUG) @app.route(\"/\") def index():", "of concurrent processes. threaded=True, ) # # Public IP #", "if __name__ == '__main__': app.debug = True # Localhost #", "'__main__': app.debug = True # Localhost # port=0 -- random", "handle each request in a new process # up to", "return render_template('index.html') if __name__ == '__main__': app.debug = True #", "# :param threaded: should the process handle each request in", "each request in a separate # thread? # :param processes:", "= Flask(__name__) import logging logging.basicConfig(level=logging.DEBUG) @app.route(\"/\") def index(): return render_template('index.html')", "https://github.com/twbs/bootstrap # SOURCE: https://github.com/gitbrent/bootstrap4-toggle # SOURCE: https://gitbrent.github.io/bootstrap4-toggle/ from flask import", "concurrent processes. threaded=True, ) # # Public IP # app.run(host='0.0.0.0')", "SOURCE: https://github.com/gitbrent/bootstrap4-toggle # SOURCE: https://gitbrent.github.io/bootstrap4-toggle/ from flask import Flask, render_template", "request in a separate # thread? # :param processes: if", "then handle each request in a new process # up", "@app.route(\"/\") def index(): return render_template('index.html') if __name__ == '__main__': app.debug", "# Localhost # port=0 -- random free port # app.run(port=0)", "# SOURCE: https://github.com/gitbrent/bootstrap4-toggle # SOURCE: https://gitbrent.github.io/bootstrap4-toggle/ from flask import Flask,", "== '__main__': app.debug = True # Localhost # port=0 --", "-*- coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE: https://github.com/twbs/bootstrap", "port # app.run(port=0) app.run( port=5000, # :param threaded: should the", "logging.basicConfig(level=logging.DEBUG) @app.route(\"/\") def index(): return render_template('index.html') if __name__ == '__main__':", "app = Flask(__name__) import logging logging.basicConfig(level=logging.DEBUG) @app.route(\"/\") def index(): return", "import Flask, render_template app = Flask(__name__) import logging logging.basicConfig(level=logging.DEBUG) @app.route(\"/\")", "number of concurrent processes. threaded=True, ) # # Public IP", "# :param processes: if greater than 1 then handle each", "= True # Localhost # port=0 -- random free port", "True # Localhost # port=0 -- random free port #", "import logging logging.basicConfig(level=logging.DEBUG) @app.route(\"/\") def index(): return render_template('index.html') if __name__" ]
[ "as phonts # <---- additional classes and functions in which", "which to add top # <---- pypospack.io.phonts if __name__ ==", "import pypospack.io.phonts as phonts # <---- additional classes and functions", "functions in which to add top # <---- pypospack.io.phonts if", "<gh_stars>1-10 import pypospack.io.phonts as phonts # <---- additional classes and", "in which to add top # <---- pypospack.io.phonts if __name__", "# <---- additional classes and functions in which to add", "classes and functions in which to add top # <----", "phonts # <---- additional classes and functions in which to", "additional classes and functions in which to add top #", "to add top # <---- pypospack.io.phonts if __name__ == \"__main__\":", "<---- additional classes and functions in which to add top", "pypospack.io.phonts as phonts # <---- additional classes and functions in", "and functions in which to add top # <---- pypospack.io.phonts" ]
[ "msg = string.Template(msg).safe_substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, KEY=key, FULL_KEY=full_key, VALUE=value, VALUE_TYPE=type_str(type(value), include_module_name=True),", "cover else: return origin is list # pragma: no cover", "expensive grammar parsing to detect errors. parse(value) return ValueKind.INTERPOLATION else:", "ValueError(\"Key must only be provided when obj is a container\")", "= False) -> str: is_optional, t = _resolve_optional(t) if t", "def _ensure_container(target: Any, flags: Optional[Dict[str, bool]] = None) -> Any:", "dot_key, bracket_key in others] return tokens # Similar to Python", "{'baz': ${baz}}}\" :param value: Input to classify. :param strict_interpolation_validation: If", "a key starting with brackets, like [a], is purposedly *not*", "\"[dict,list,DictConfig,ListConfig,dataclass,dataclass instance,attr class,attr class instance]\" ) return target def is_generic_list(type_:", "object_type = None ref_type = None ref_type_str = None else:", "in keys: raise yaml.constructor.ConstructorError( \"while constructing a mapping\", node.start_mark, f\"found", "`key` has no other component: we are done. if first_stop", "Note that a key starting with brackets, like [a], is", "is True. if isinstance(value, str) and \"${\" in value: if", "the key. tokens = key[0:first_stop].split(\".\") # Optimization in case `key`", "ret = ( get_value_kind(v, strict_interpolation_validation) == ValueKind.INTERPOLATION ) assert isinstance(ret,", "def get_type_of(class_or_object: Any) -> Type[Any]: type_ = class_or_object if not", "# source: https://yaml.org/type/bool.html YAML_BOOL_TYPES = [ \"y\", \"Y\", \"yes\", \"Yes\",", "value = field.default_factory() # type: ignore if _is_union(type_): e =", "and issubclass(type_, Dict) def is_dict(obj: Any) -> bool: return is_primitive_dict(obj)", "is_list_annotation(type_) and get_list_element_type(type_) is not None def is_generic_dict(type_: Any) ->", "boxed = value._value() if boxed is None or _is_missing_literal(boxed) or", "or type_ in (int, float, bool, str, type(None)) def _is_interpolation(v:", "-> bool: return b in YAML_BOOL_TYPES def get_yaml_loader() -> Any:", "# type: ignore def _raise(ex: Exception, cause: Exception) -> None:", "if t._name is None: if t.__origin__ is not None: name", "cover else: # pragma: no cover # type_dict is a", "return origin is List or type_ is List # pragma:", "ignore if is_list_annotation(type_): et = get_list_element_type(type_) if et is not", "throw_on_resolution_failure: bool = True ) -> bool: from omegaconf import", "args = getattr(ref_type, \"__args__\", None) if ref_type is not List", "attr = None # type: ignore # pragma: no cover", "= OmegaConf.create(target, flags=flags) elif is_structured_config(target): target = OmegaConf.structured(target, flags=flags) elif", "detect. # this support is tentative, if it eventually causes", "or ref_type == Dict: key_type = Any element_type = Any", "Container) obj = obj._get_node(key) if isinstance(obj, Node): return obj._is_optional() else:", "if type_ is Any: return True, Any return False, type_", "_is_missing_value(value): return ValueKind.MANDATORY_MISSING value = _get_value(value) # We identify potential", "also works with the getitem syntax: \"a.b\" -> [\"a\", \"b\"]", "is not None: d.update(dict_subclass_data) return d def get_dataclass_field_names(obj: Any) ->", "s def is_primitive_list(obj: Any) -> bool: from .base import Container", "_get_value(value: Any) -> Any: from .base import Container from .nodes", "type_ = _resolve_forward(type_, obj.__module__) if hasattr(obj, name): value = getattr(obj,", "= \", \".join( [type_str(t, include_module_name=include_module_name) for t in t.__args__] )", "def get_omega_conf_dumper() -> Type[OmegaConfDumper]: if not OmegaConfDumper.str_representer_added: OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer) OmegaConfDumper.str_representer_added", "List # pragma: no cover else: return origin is list", "raise ValueError(\"Key must only be provided when obj is a", "def is_attr_frozen(type_: type) -> bool: # This is very hacky", "\"${\" in value: if strict_interpolation_validation: # First try the cheap", "ConfigValueError, GrammarParseError, OmegaConfBaseException, ValidationError, ) from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse", "def is_structured_config(obj: Any) -> bool: return is_attr_class(obj) or is_dataclass(obj) def", "# set end OC_CAUSE=1 for full backtrace def format_and_raise( node:", "type(None)) def _is_interpolation(v: Any, strict_interpolation_validation: bool = False) -> bool:", "the first part of the key (in docstring examples: a,", "a full key path into its individual components. This is", "Node): return obj._is_optional() else: # In case `obj` is not", "when `value` is a string containing \"${\", it is parsed", "Dict[str, Any]: if is_dataclass(obj): return get_dataclass_data(obj, allow_objects=allow_objects) elif is_attr_class(obj): return", "be handled in the next regex below (this # is", "type_override: Any = None, ) -> None: from omegaconf import", "def get_attr_data(obj: Any, allow_objects: Optional[bool] = None) -> Dict[str, Any]:", "return False return dataclasses.is_dataclass(obj) def is_attr_class(obj: Any) -> bool: from", "include_module_name=True), KEY_TYPE=f\"{type(key).__name__}\", ) if ref_type not in (None, Any): template", "def is_int(st: str) -> bool: try: int(st) return True except", "ignore def get_type_of(class_or_object: Any) -> Type[Any]: type_ = class_or_object if", "dict or typed_dict def is_list_annotation(type_: Any) -> bool: origin =", ") -> Dict[str, Any]: from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap", "== attr.NOTHING: value = MISSING if _is_union(type_): e = ConfigValueError(", "Any) -> bool: # Uses literal '???' instead of the", "can be non-empty. tokens += [dot_key if dot_key else bracket_key", "element_type = Any else: if args is not None: key_type", "# First try the cheap regex matching that detects common", "# This is used in `ListConfig.append` and `ListConfig.insert` # where", "msg=str(e)) try: d[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value, parent=dummy_parent,", "field in dataclasses.fields(obj): name = field.name is_optional, type_ = _resolve_optional(resolved_hints[field.name])", "misleading. Instead, we display it in the key. full_key =", "dict_subclass_data else: return None def get_attr_class_field_names(obj: Any) -> List[str]: is_type", "or isinstance(obj, Node): return False return attr.has(obj) def is_structured_config(obj: Any)", "type: ignore return type_ def extract_dict_subclass_data(obj: Any, parent: Any) ->", "\"ON\", \"off\", \"Off\", \"OFF\", ] class Marker: def __init__(self, desc:", "bool: \"\"\" Checks if a type is a generic list,", "-> Dict[str, Any]: from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap flags", "else: module_prefix = \"\" ret = module_prefix + ret if", "element_type = Any return element_type def get_dict_key_value_types(ref_type: Any) -> Tuple[Any,", "2.2 def decode_primitive(s: str) -> Any: if is_bool(s): return str.lower(s)", "first key starts with brackets, e.g. # [a] or ..[a].", "None if resolve: value = value._maybe_dereference_node( throw_on_resolution_failure=throw_on_resolution_failure ) if not", "- `[` followed by anything then `]` (ex: [b], [c])", "stacklevel=9, ) if is_type: return None elif subclasses_dict: dict_subclass_data =", "if sys.version_info < (3, 7, 0): return origin is Dict", "is_type: value = getattr(obj, name) else: value = attrib.default if", "is not None and args[0]: element_type = args[0] else: element_type", "elif not OmegaConf.is_config(target): raise ValueError( \"Invalid input. Supports one of", "and type_.__base__ == dict return origin is dict or typed_dict", "is not None: ex = type_override(str(cause)) ex.__dict__ = copy.deepcopy(cause.__dict__) _raise(ex,", "to validate the interpolation syntax. If `False`, this parsing step", "message ex.parent_node = node ex.child_node = child_node ex.key = key", "to Python 3.7+'s `contextlib.nullcontext` (which should be used instead, #", ".base import Container from .nodes import ValueNode if isinstance(value, ValueNode):", "is_int(s): return int(s) if is_float(s): return float(s) return s def", "types are not supported:\\n{name}: {type_str(type_)}\" ) format_and_raise(node=None, key=None, value=value, cause=e,", "str) -> bool: try: int(st) return True except ValueError: return", "key: Optional[Union[int, str]] = None) -> bool: \"\"\"Check `obj` metadata", "key elements (in docstring examples: b, b, b/c/d, b) others", "not isinstance(value, Node): return value is None if resolve: value", "treat it as optional by default. # This is used", "-> bool: return type_ is not None and isinstance(type_, type)", "ValueKind.MANDATORY_MISSING value = _get_value(value) # We identify potential interpolations by", "from omegaconf import MISSING d = {} is_type = isinstance(obj,", "Any: class OmegaConfLoader(yaml.SafeLoader): # type: ignore def construct_mapping(self, node: yaml.Node,", "the string to be properly un-escaped. # Keep in mind", "OmegaConf.get_type(node) object_type_str = type_str(object_type) ref_type = get_ref_type(node) ref_type_str = type_str(ref_type)", "not in (None, Any): template = dedent( \"\"\"\\ $MSG full_key:", "object_type ex.object_type_str = object_type_str ex.ref_type = ref_type ex.ref_type_str = ref_type_str", "OC_CAUSE=1 to get a stacktrace that includes the # causing", "False typing.List[T] returns True :param type_: variable type :return: bool", "ret if is_optional: return f\"Optional[{ret}]\" else: return ret def _ensure_container(target:", "no cover try: import attr except ImportError: # pragma: no", "Since we are handling an exception, raising a different one", "Python 3.6 if hasattr(t, \"__name__\"): name = str(t.__name__) else: if", "mind that invalid interpolations will only be detected when #", "is_optional: return f\"Optional[{ret}]\" else: return ret def _ensure_container(target: Any, flags:", "isinstance(target, (list, dict)) target = OmegaConf.create(target, flags=flags) elif is_structured_config(target): target", "def get_dict_key_value_types(ref_type: Any) -> Tuple[Any, Any]: args = getattr(ref_type, \"__args__\",", "it eventually causes issues in other areas it may be", "return dataclasses.is_dataclass(obj) def is_attr_class(obj: Any) -> bool: from omegaconf.base import", "type) and issubclass(type_, Dict) def is_dict(obj: Any) -> bool: return", "name if include_module_name: if ( hasattr(t, \"__module__\") and t.__module__ !=", "dict_subclass_data = {} key_type, element_type = get_dict_key_value_types(obj_type) for name, value", "Any]: from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap flags = {\"allow_objects\":", "== attr._make._frozen_setattrs # type: ignore def get_type_of(class_or_object: Any) -> Type[Any]:", "and one for keys starting with a bracket ([b], [c]).", "\"Off\", \"OFF\", ] class Marker: def __init__(self, desc: str): self.desc", "= \"\" ret = module_prefix + ret if is_optional: return", "= get_type_of(obj) dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type resolved_hints", "None) key_type: Any element_type: Any if ref_type is None or", "\"no\", \"No\", \"NO\", \"true\", \"True\", \"TRUE\", \"false\", \"False\", \"FALSE\", \"on\",", "import Node if not isinstance(value, Node): return value is None", "key is not None: obj = obj._get_node(key) else: if key", "str, type(None)) def _is_interpolation(v: Any, strict_interpolation_validation: bool = False) ->", "2 and args[1] == type(None): # noqa E721 return True,", "-> List[str]: \"\"\" Split a full key path into its", "or ..[a]. In that case there is an extra \"\"", "-> str: is_optional, t = _resolve_optional(t) if t is None:", "isinstance(obj, Node): ref_type = obj._metadata.ref_type if obj._is_optional() and ref_type is", "other component: we are done. if first_stop == len(key): return", "dot (.b, .d) and one for keys starting with a", "# Since we are handling an exception, raising a different", "ex.object_type_str = object_type_str ex.ref_type = ref_type ex.ref_type_str = ref_type_str _raise(ex,", "or might not be a Node. return True def _resolve_forward(type_:", "(3, 7, 0): return origin is Dict or type_ is", "None full_backtrace = (debugging and not env_var == \"0\") or", "data, style=(\"'\" if with_quotes else None), ) def get_omega_conf_dumper() ->", "import ( ConfigIndexError, ConfigTypeError, ConfigValueError, GrammarParseError, OmegaConfBaseException, ValidationError, ) from", "module_path, _, class_name = path.rpartition(\".\") mod = import_module(module_path) try: klass:", "cause=e, msg=str(e)) try: d[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value,", "else: if args is not None: key_type = args[0] element_type", "= _resolve_forward(type_, obj.__module__) if hasattr(obj, name): value = getattr(obj, name)", "else typing._ForwardRef # type: ignore if type(type_) is forward: return", "name[len(\"typing.\") :] else: # pragma: no cover # Python >=", "or (env_var == \"1\") if full_backtrace: ex.__cause__ = cause else:", "return origin is dict or typed_dict def is_list_annotation(type_: Any) ->", "= [\"\", \"\", \"\"] but we would like [\"\", \"\"]", "is None or type_ is Any or issubclass(type_, DictKeyType.__args__) #", "module: str) -> Type[Any]: import typing # lgtm [py/import-and-import-from] forward", "Union, get_type_hints, ) import yaml from .errors import ( ConfigIndexError,", "\"${\" in the string. # Note that escaped interpolations (ex:", "value=value, cause=ex, msg=str(ex) ) return dict_subclass_data else: return None def", "tentative, if it eventually causes issues in other areas it", "\".\" else: module_prefix = \"\" ret = module_prefix + ret", "include_module_name=include_module_name ) else: name = str(t._name) args = getattr(t, \"__args__\",", "in loader.yaml_implicit_resolvers.items() } return loader def _get_class(path: str) -> type:", "a string containing \"${\", it is parsed to validate the", "obj is an instance of a subclass of Dict. If", "template = dedent( \"\"\"\\ $MSG full_key: $FULL_KEY object_type=$OBJECT_TYPE\"\"\" ) s", "value=value, cause=ex, msg=str(ex) ) d[name]._set_parent(None) dict_subclass_data = extract_dict_subclass_data(obj=obj, parent=dummy_parent) if", "dict return origin is dict or typed_dict def is_list_annotation(type_: Any)", "is not in module {module_path}\") return klass def _is_union(type_: Any)", "not an option. _DEFAULT_MARKER_: Any = Marker(\"_DEFAULT_MARKER_\") class OmegaConfDumper(yaml.Dumper): #", "is_attr_class(obj): return get_attr_class_field_names(obj) else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\") def get_structured_config_data(", "return primitives and regular OmegaConf Containers as is return value", "Optional[Dict[str, bool]] = None) -> Any: from omegaconf import OmegaConf", "omegaconf.base import Node if dataclasses is None or isinstance(obj, Node):", "are handling an exception, raising a different one here would", "Subclassing `Dict` in Structured Config classes is deprecated,\" + \"", "return list(attr.fields_dict(obj_type)) def get_attr_data(obj: Any, allow_objects: Optional[bool] = None) ->", "return Any # type: ignore def _raise(ex: Exception, cause: Exception)", "valid_value_annotation_type(type_: Any) -> bool: return type_ is Any or is_primitive_type(type_)", "else: return Any # type: ignore def _raise(ex: Exception, cause:", "dict_subclass_data[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value, parent=parent, ) except", "a, .a, '') first = KEY_PATH_HEAD.match(key) assert first is not", "from .base import Container from .nodes import ValueNode if isinstance(value,", "contain all elements composing the key. tokens = key[0:first_stop].split(\".\") #", "if key is not None else \"\" object_type = None", "# this support is tentative, if it eventually causes issues", "[\"a\", \"b\"] \"\"\" # Obtain the first part of the", "isinstance(value, str) and \"${\" in value: if strict_interpolation_validation: # First", "bool = False ) -> ValueKind: \"\"\" Determine the kind", "True except ValueError: return False def is_int(st: str) -> bool:", "if not is_type: value = getattr(obj, name) else: value =", "= type_.__args__ if len(args) == 2 and args[1] == type(None):", "[c]). # Only one group can be non-empty. tokens +=", "from omegaconf.omegaconf import OmegaConf, _maybe_wrap flags = {\"allow_objects\": allow_objects} if", "YAML_BOOL_TYPES def get_yaml_loader() -> Any: class OmegaConfLoader(yaml.SafeLoader): # type: ignore", "forward: return _get_class(f\"{module}.{type_.__forward_arg__}\") else: if is_dict_annotation(type_): kt, vt = get_dict_key_value_types(type_)", "if is_type else type(obj) dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type =", "args[0] if type_ is Any: return True, Any return False,", "\"0\") or (env_var == \"1\") if full_backtrace: ex.__cause__ = cause", "bool = False) -> bool: if isinstance(v, str): ret =", "return True except ValueError: return False def is_int(st: str) ->", "-> Optional[Dict[str, Any]]: \"\"\"Check if obj is an instance of", "Split a full key path into its individual components. This", "\"NO\", \"true\", \"True\", \"TRUE\", \"false\", \"False\", \"FALSE\", \"on\", \"On\", \"ON\",", "= _resolve_forward(vt, module=module) return Dict[kt, vt] # type: ignore if", "format_and_raise( node=dummy_parent, key=name, value=value, cause=ex, msg=str(ex) ) d[name]._set_parent(None) dict_subclass_data =", ") else: template = dedent( \"\"\"\\ $MSG full_key: $FULL_KEY object_type=$OBJECT_TYPE\"\"\"", "\"a\", \"b\", \"c\", \"d\"] \"[a].b\" -> [\"a\", \"b\"] \"\"\" #", "{type_str(type_)}\" ) format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e)) try: d[name] =", "{module_path}\") return klass def _is_union(type_: Any) -> bool: return getattr(type_,", "= getattr(bases[0], \"__args__\", None) key_type: Any element_type: Any if ref_type", "constructing a mapping\", node.start_mark, f\"found duplicate key {key_node.value}\", key_node.start_mark, )", "_resolve_optional(type_: Any) -> Tuple[bool, Any]: \"\"\"Check whether `type_` is equivalent", "exception_type = ConfigIndexError ex = exception_type(f\"{message}\") if issubclass(exception_type, OmegaConfBaseException): ex._initialized", "None: if t.__origin__ is not None: name = type_str( t.__origin__,", "\"N\", \"no\", \"No\", \"NO\", \"true\", \"True\", \"TRUE\", \"false\", \"False\", \"FALSE\",", "$MSG full_key: $FULL_KEY object_type=$OBJECT_TYPE\"\"\" ) s = string.Template(template=template) message =", "except ImportError: # pragma: no cover attr = None #", "= get_dict_key_value_types(obj_type) for name, value in obj.items(): is_optional, type_ =", "is None or isinstance(obj, Node): return False return attr.has(obj) def", "vt = get_dict_key_value_types(type_) if kt is not None: kt =", "or is_primitive_dict(obj) def get_list_element_type(ref_type: Optional[Type[Any]]) -> Any: args = getattr(ref_type,", "import sys import warnings from contextlib import contextmanager from enum", "full backtrace def format_and_raise( node: Any, key: Any, value: Any,", "return isinstance(value, str) and value == \"???\" def _is_none( value:", "Python 3.6 is dropped). @contextmanager def nullcontext(enter_result: Any = None)", "AssertionError): raise if isinstance(cause, OmegaConfBaseException) and cause._initialized: ex = cause", "str) -> Any: if is_bool(s): return str.lower(s) == \"true\" if", "= _resolve_forward(type_, obj.__module__) if not is_type: value = getattr(obj, name)", "are two groups in the `KEY_PATH_OTHER` regex: one for keys", "assert isinstance(obj, Container) obj = obj._get_node(key) if isinstance(obj, Node): return", "if is_type: return None elif subclasses_dict: dict_subclass_data = {} key_type,", "import os import re import string import sys import warnings", "ValueKind.INTERPOLATION else: return ValueKind.VALUE # DEPRECATED: remove in 2.2 def", "format_and_raise( node=None, key=name, value=value, cause=ex, msg=str(ex) ) return dict_subclass_data else:", "in 2.2 def is_bool(st: str) -> bool: st = str.lower(st)", "isinstance(obj, Container) and isinstance(obj, (list, tuple)) def is_primitive_dict(obj: Any) ->", "None ref_type = None ref_type_str = None else: if key", "_resolve_forward(type_: Type[Any], module: str) -> Type[Any]: import typing # lgtm", "class_or_object if not isinstance(type_, type): type_ = type(class_or_object) assert isinstance(type_,", "and not node._is_none(): child_node = node._get_node(key, validate_access=False) try: full_key =", "-> bool: from omegaconf import Node if isinstance(value, Node): value", "ex.ref_type_str = ref_type_str _raise(ex, cause) def type_str(t: Any, include_module_name: bool", "Any, allow_objects: Optional[bool] = None ) -> Dict[str, Any]: if", "Uses literal '???' instead of the MISSING const for performance", "-> Tuple[bool, Any]: \"\"\"Check whether `type_` is equivalent to `typing.Optional[T]`", "yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, data, style=(\"'\" if with_quotes else None), ) def get_omega_conf_dumper()", "boxed # return primitives and regular OmegaConf Containers as is", "obj = obj._get_node(key) else: if key is not None: raise", "= typing.ForwardRef if hasattr(typing, \"ForwardRef\") else typing._ForwardRef # type: ignore", "|[-+]?\\\\.(?:inf|Inf|INF) |\\\\.(?:nan|NaN|NAN))$\"\"\", re.X, ), list(\"-+0123456789.\"), ) loader.yaml_implicit_resolvers = { key:", "not None full_backtrace = (debugging and not env_var == \"0\")", "it is *not* None. return False assert isinstance(value, Node) return", "(in docstring examples: b, b, b/c/d, b) others = KEY_PATH_OTHER.findall(key[first_stop:])", "etc. # We begin by matching the head (in these", "module_prefix = t.__module__ + \".\" else: module_prefix = \"\" ret", "the environment variable OC_CAUSE=1 to get a stacktrace that includes", "obj if is_type else type(obj) return list(attr.fields_dict(obj_type)) def get_attr_data(obj: Any,", "To be used as default value when `None` is not", "(ValidationError, GrammarParseError) as ex: format_and_raise( node=dummy_parent, key=name, value=value, cause=ex, msg=str(ex)", "False def is_int(st: str) -> bool: try: int(st) return True", "others = KEY_PATH_OTHER.findall(key[first_stop:]) # There are two groups in the", "${baz}}}\" :param value: Input to classify. :param strict_interpolation_validation: If `True`,", "ref_type: Optional[Type[Any]] ref_type_str: Optional[str] child_node: Optional[Node] = None if node", "\"Any\" if t is ...: return \"...\" if sys.version_info <", "None) is Union: args = type_.__args__ if len(args) == 2", "ex.__dict__ = copy.deepcopy(cause.__dict__) _raise(ex, cause) object_type: Optional[Type[Any]] object_type_str: Optional[str] =", "import OmegaConf if is_primitive_container(target): assert isinstance(target, (list, dict)) target =", "a bracket ([b], [c]). # Only one group can be", "self.desc # To be used as default value when `None`", "isinstance(obj, type) obj_type = obj if is_type else type(obj) subclasses_dict", "matched here and will instead be handled in the next", "ValueError(f\"Unsupported type: {type(obj).__name__}\") class ValueKind(Enum): VALUE = 0 MANDATORY_MISSING =", "# for the string to be properly un-escaped. # Keep", "type_ is not None and isinstance(type_, type) and issubclass(type_, Dict)", "isinstance(obj, Container): if key is not None: obj = obj._get_node(key)", "\" see github.com/omry/omegaconf/issues/663\", UserWarning, stacklevel=9, ) if is_type: return None", "if hasattr(obj, name): value = getattr(obj, name) if value ==", "E721 return True, args[0] if type_ is Any: return True,", "# type_dict is a bit hard to detect. # this", "not node._is_none(): child_node = node._get_node(key, validate_access=False) try: full_key = node._get_full_key(key=key)", "None ) -> Dict[str, Any]: if is_dataclass(obj): return get_dataclass_data(obj, allow_objects=allow_objects)", "== \"[\" and not tokens[-1]: # This is a special", "MANDATORY_MISSING = 1 INTERPOLATION = 2 def _is_missing_value(value: Any) ->", "github.com/omry/omegaconf/issues/663\", UserWarning, stacklevel=9, ) if is_type: return None elif subclasses_dict:", "Type[Any]: type_ = class_or_object if not isinstance(type_, type): type_ =", "= getattr(type_, \"__origin__\", None) if sys.version_info < (3, 7, 0):", "# Then we match other keys. The following expression matches", "Checks if a type is a generic list, for example:", "Dict # pragma: no cover else: # pragma: no cover", "hasattr(t, \"__name__\"): name = str(t.__name__) else: if t._name is None:", "case `key` has no other component: we are done. if", ") s = string.Template(template=template) message = s.substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg,", "keep this regex simple). KEY_PATH_HEAD = re.compile(r\"(\\.)*[^.[]*\") # Then we", "(tag, regexp) for tag, regexp in resolvers if tag !=", "`key.split(\".\")` but also works with the getitem syntax: \"a.b\" ->", "be read as a choice between two syntaxes: # -", "# DEPRECATED: remove in 2.2 def is_bool(st: str) -> bool:", "import contextmanager from enum import Enum from textwrap import dedent", "returns False typing.List returns False typing.List[T] returns True :param type_:", "# This is a special case where the first key", "not None and isinstance(type_, type) and issubclass(type_, Dict) def is_dict(obj:", "ConfigIndexError ex = exception_type(f\"{message}\") if issubclass(exception_type, OmegaConfBaseException): ex._initialized = True", "the Dict keys/values.\"\"\" from omegaconf.omegaconf import _maybe_wrap is_type = isinstance(obj,", "def _get_value(value: Any) -> Any: from .base import Container from", "detect errors. \"\"\" if _is_missing_value(value): return ValueKind.MANDATORY_MISSING value = _get_value(value)", "Dict[kt, vt] # type: ignore if is_list_annotation(type_): et = get_list_element_type(type_)", "a container\") if isinstance(obj, Node): ref_type = obj._metadata.ref_type if obj._is_optional()", "\"tag:yaml.org,2002:float\", re.compile( \"\"\"^(?: [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]* |[-+]?\\\\.(?:inf|Inf|INF) |\\\\.(?:nan|NaN|NAN))$\"\"\", re.X,", "parsed to validate the interpolation syntax. If `False`, this parsing", "import import_module module_path, _, class_name = path.rpartition(\".\") mod = import_module(module_path)", "Any, key: Optional[Union[int, str]] = None) -> bool: \"\"\"Check `obj`", "This is similar to `key.split(\".\")` but also works with the", "escaped interpolations (ex: \"esc: \\${bar}\") are identified as # interpolations:", "= OmegaConf.get_type(node) object_type_str = type_str(object_type) ref_type = get_ref_type(node) ref_type_str =", "obj.__module__) try: dict_subclass_data[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value, parent=parent,", "None or ref_type == Dict: key_type = Any element_type =", "# Python 3.6 if hasattr(t, \"__name__\"): name = str(t.__name__) else:", "= {} is_type = isinstance(obj, type) obj_type = obj if", "import typing # lgtm [py/import-and-import-from] forward = typing.ForwardRef if hasattr(typing,", "in dataclasses.fields(obj): name = field.name is_optional, type_ = _resolve_optional(resolved_hints[field.name]) type_", "the presence of \"${\" in the string. # Note that", "the appended/inserted value might or might not be a Node.", "if value == dataclasses.MISSING: value = MISSING else: if field.default_factory", "that case there is an extra \"\" in `tokens` that", "and cause._initialized: ex = cause if type_override is not None:", "= OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type resolved_hints = get_type_hints(obj_type) for", "type: ignore else: return ref_type else: return Any # type:", "= object_type ex.object_type_str = object_type_str ex.ref_type = ref_type ex.ref_type_str =", "None: return type(t).__name__ if t is Any: return \"Any\" if", "-> Any: keys = set() for key_node, value_node in node.value:", "yaml from .errors import ( ConfigIndexError, ConfigTypeError, ConfigValueError, GrammarParseError, OmegaConfBaseException,", "processed as interpolations # for the string to be properly", "\"\"\"\\ $MSG full_key: $FULL_KEY object_type=$OBJECT_TYPE\"\"\" ) s = string.Template(template=template) message", "ex = cause if type_override is not None: ex =", "import MISSING, OmegaConf, _maybe_wrap flags = {\"allow_objects\": allow_objects} if allow_objects", "bool: return type_.__dataclass_params__.frozen # type: ignore def is_attr_frozen(type_: type) ->", "return \"Any\" if t is ...: return \"...\" if sys.version_info", "no cover else: return origin is tuple # pragma: no", "value ex.object_type = object_type ex.object_type_str = object_type_str ex.ref_type = ref_type", "parent=dummy_parent, ) except (ValidationError, GrammarParseError) as ex: format_and_raise( node=dummy_parent, key=name,", "\"\"\" # Obtain the first part of the key (in", "Determine the kind of a value Examples: VALUE: \"10\", \"20\",", "will only be detected when # `strict_interpolation_validation` is True. if", "try: int(st) return True except ValueError: return False # DEPRECATED:", "is None if resolve: value = value._maybe_dereference_node( throw_on_resolution_failure=throw_on_resolution_failure ) if", "will contain all elements composing the key. tokens = key[0:first_stop].split(\".\")", "None) if ref_type is not List and args is not", "isinstance(cause, OmegaConfBaseException) and cause._initialized: ex = cause if type_override is", "dict_subclass_data is not None: d.update(dict_subclass_data) return d def is_dataclass(obj: Any)", "is purposedly *not* # matched here and will instead be", "not None: d.update(dict_subclass_data) return d def get_dataclass_field_names(obj: Any) -> List[str]:", "|\\\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]* |[-+]?\\\\.(?:inf|Inf|INF) |\\\\.(?:nan|NaN|NAN))$\"\"\", re.X, ), list(\"-+0123456789.\"), ) loader.yaml_implicit_resolvers =", "type is a generic dict, for example: list returns False", "interpolations (ex: \"esc: \\${bar}\") are identified as # interpolations: this", "None and args[0]: element_type = args[0] else: element_type = Any", "kt is not None: kt = _resolve_forward(kt, module=module) if vt", "vt = _resolve_forward(vt, module=module) return Dict[kt, vt] # type: ignore", "bool: \"\"\" Checks if a type is a generic dict,", "this is more efficient, but will not detect errors. \"\"\"", "with brackets, like [a], is purposedly *not* # matched here", "# pragma: no cover # Python 3.6 if hasattr(t, \"__name__\"):", "= key if key is not None else \"\" object_type", "is tentative, if it eventually causes issues in other areas", "VALUE=value, VALUE_TYPE=type_str(type(value), include_module_name=True), KEY_TYPE=f\"{type(key).__name__}\", ) if ref_type not in (None,", "return ret return False def _get_value(value: Any) -> Any: from", "|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]* |[-+]?\\\\.(?:inf|Inf|INF) |\\\\.(?:nan|NaN|NAN))$\"\"\", re.X, ), list(\"-+0123456789.\"), ) loader.yaml_implicit_resolvers = {", "element_type = args[0] else: element_type = Any return element_type def", "@contextmanager def nullcontext(enter_result: Any = None) -> Iterator[Any]: yield enter_result", "def get_ref_type(obj: Any, key: Any = None) -> Optional[Type[Any]]: from", "character but `.` or `[`\" # Note that a key", "desc: str): self.desc = desc def __repr__(self) -> str: return", "omegaconf.omegaconf import _maybe_wrap is_type = isinstance(obj, type) obj_type = obj", "return is_attr_frozen(type_) return False def get_structured_config_field_names(obj: Any) -> List[str]: if", "return get_dataclass_data(obj, allow_objects=allow_objects) elif is_attr_class(obj): return get_attr_data(obj, allow_objects=allow_objects) else: raise", "or type_ is Any or issubclass(type_, DictKeyType.__args__) # type: ignore", "= Marker(\"_DEFAULT_MARKER_\") class OmegaConfDumper(yaml.Dumper): # type: ignore str_representer_added = False", "and args is not None and args[0]: element_type = args[0]", "child_node: Optional[Node] = None if node is None: full_key =", "not None: name = type_str( t.__origin__, include_module_name=include_module_name ) else: name", "pragma: no cover else: return origin is list # pragma:", "ex: format_and_raise( node=None, key=name, value=value, cause=ex, msg=str(ex) ) return dict_subclass_data", "a.b, a[b], ..a[c].d, etc. # We begin by matching the", "not OmegaConfDumper.str_representer_added: OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer) OmegaConfDumper.str_representer_added = True return OmegaConfDumper def", "{} is_type = isinstance(obj, type) obj_type = obj if is_type", "_DEFAULT_MARKER_: Any = Marker(\"_DEFAULT_MARKER_\") class OmegaConfDumper(yaml.Dumper): # type: ignore str_representer_added", "pragma: no cover attr = None # type: ignore #", "handled in the next regex below (this # is to", "if key is not None: assert isinstance(obj, Container) obj =", "as ex: format_and_raise( node=None, key=name, value=value, cause=ex, msg=str(ex) ) return", "= (debugging and not env_var == \"0\") or (env_var ==", "obj._get_node(key) if isinstance(obj, Node): return obj._is_optional() else: # In case", "not None: vt = _resolve_forward(vt, module=module) return Dict[kt, vt] #", "_is_optional(obj: Any, key: Optional[Union[int, str]] = None) -> bool: \"\"\"Check", "if type(type_) is forward: return _get_class(f\"{module}.{type_.__forward_arg__}\") else: if is_dict_annotation(type_): kt,", "value._value() if boxed is None or _is_missing_literal(boxed) or _is_interpolation(boxed): return", "-> Type[Any]: import typing # lgtm [py/import-and-import-from] forward = typing.ForwardRef", "OBJECT_TYPE=object_type_str, KEY=key, FULL_KEY=full_key, VALUE=value, VALUE_TYPE=type_str(type(value), include_module_name=True), KEY_TYPE=f\"{type(key).__name__}\", ) if ref_type", "provided when obj is a container\") if isinstance(obj, Node): ref_type", "else: return ret def _ensure_container(target: Any, flags: Optional[Dict[str, bool]] =", "\"a.b\" -> [\"a\", \"b\"] \"a[b]\" -> [\"a, \"b\"] \".a.b[c].d\" ->", "-> ValueKind: \"\"\" Determine the kind of a value Examples:", "type: ignore str_representer_added = False @staticmethod def str_representer(dumper: yaml.Dumper, data:", "Any: return \"Any\" if t is ...: return \"...\" if", "very hacky and probably fragile as well. # Unfortunately currently", "T.\"\"\" if getattr(type_, \"__origin__\", None) is Union: args = type_.__args__", "_resolve_optional(resolved_hints[field.name]) type_ = _resolve_forward(type_, obj.__module__) if hasattr(obj, name): value =", "= 0 MANDATORY_MISSING = 1 INTERPOLATION = 2 def _is_missing_value(value:", "for the string to be properly un-escaped. # Keep in", "but also works with the getitem syntax: \"a.b\" -> [\"a\",", "# Note that escaped interpolations (ex: \"esc: \\${bar}\") are identified", "_raise(ex, cause) object_type: Optional[Type[Any]] object_type_str: Optional[str] = None ref_type: Optional[Type[Any]]", "Node): value = value._value() return _is_missing_literal(value) def _is_missing_literal(value: Any) ->", "value: Input to classify. :param strict_interpolation_validation: If `True`, then when", "args[0] element_type = args[1] else: key_type = Any element_type =", "continue if key_node.value in keys: raise yaml.constructor.ConstructorError( \"while constructing a", "Any) -> Tuple[bool, Any]: \"\"\"Check whether `type_` is equivalent to", "= str(t) if name.startswith(\"typing.\"): name = name[len(\"typing.\") :] else: #", "Checks if a type is a generic dict, for example:", "# type: ignore # pragma: no cover try: import attr", "if hasattr(t, \"__name__\"): name = str(t.__name__) else: if t.__origin__ is", "cause=ex, msg=str(ex) ) d[name]._set_parent(None) dict_subclass_data = extract_dict_subclass_data(obj=obj, parent=dummy_parent) if dict_subclass_data", "in attr.fields_dict(obj_type).items(): is_optional, type_ = _resolve_optional(attrib.type) type_ = _resolve_forward(type_, obj.__module__)", "env_var == \"0\") or (env_var == \"1\") if full_backtrace: ex.__cause__", "return type(t).__name__ if t is Any: return \"Any\" if t", "# Set the environment variable OC_CAUSE=1 to get a stacktrace", "None else \"\" object_type = None ref_type = None ref_type_str", "type_ = _resolve_optional(resolved_hints[field.name]) type_ = _resolve_forward(type_, obj.__module__) if hasattr(obj, name):", "not is_type: value = getattr(obj, name) else: value = attrib.default", "attr.has(obj) def is_structured_config(obj: Any) -> bool: return is_attr_class(obj) or is_dataclass(obj)", "bool = False) -> str: is_optional, t = _resolve_optional(t) if", "+ \"[dict,list,DictConfig,ListConfig,dataclass,dataclass instance,attr class,attr class instance]\" ) return target def", "isinstance(value, Node): value = value._value() return _is_missing_literal(value) def _is_missing_literal(value: Any)", "else: return ref_type else: return Any # type: ignore def", "{} key_type, element_type = get_dict_key_value_types(obj_type) for name, value in obj.items():", "True def _resolve_forward(type_: Type[Any], module: str) -> Type[Any]: import typing", "# interpolations: this is intended, since they must be processed", "or isinstance(obj, Node): return False return dataclasses.is_dataclass(obj) def is_attr_class(obj: Any)", "\"__base__\") and type_.__base__ == dict return origin is dict or", "pragma: no cover else: return origin is tuple # pragma:", "\"...\" if sys.version_info < (3, 7, 0): # pragma: no", "is not None first_stop = first.span()[1] # `tokens` will contain", "assert isinstance(ret, bool) return ret return False def _get_value(value: Any)", "None else: if key is not None and not node._is_none():", "is_optional, t = _resolve_optional(t) if t is None: return type(t).__name__", "= message ex.parent_node = node ex.child_node = child_node ex.key =", "return True, args[0] if type_ is Any: return True, Any", "\"[a].b\" -> [\"a\", \"b\"] \"\"\" # Obtain the first part", "omegaconf import MISSING d = {} is_type = isinstance(obj, type)", "strict_interpolation_validation: # First try the cheap regex matching that detects", "d.update(dict_subclass_data) return d def get_dataclass_field_names(obj: Any) -> List[str]: return [field.name", "else: ret = name if include_module_name: if ( hasattr(t, \"__module__\")", "\"__args__\", None) if args is None: bases = getattr(ref_type, \"__orig_bases__\",", "If no match, do the more expensive grammar parsing to", "an extra \"\" in `tokens` that we # need to", "b) others = KEY_PATH_OTHER.findall(key[first_stop:]) # There are two groups in", "\"\"\"Check if obj is an instance of a subclass of", ") if is_type: return None elif subclasses_dict: dict_subclass_data = {}", "== TypeError: exception_type = ConfigTypeError elif exception_type == IndexError: exception_type", "display it in the key. full_key = f\"<unresolvable due to", "sys.version_info < (3, 7, 0): return origin is Tuple or", "element_type: Any if ref_type is None or ref_type == Dict:", "getattr(ref_type, \"__args__\", None) if ref_type is not List and args", "def get_yaml_loader() -> Any: class OmegaConfLoader(yaml.SafeLoader): # type: ignore def", "from omegaconf import DictKeyType return type_ is None or type_", "dataclasses.MISSING: # type: ignore value = MISSING else: value =", "ref_type ex.ref_type_str = ref_type_str _raise(ex, cause) def type_str(t: Any, include_module_name:", "isn't an official API in attr that can detect that.", "et is not None: et = _resolve_forward(et, module=module) return List[et]", "obj.__module__) if hasattr(obj, name): value = getattr(obj, name) if value", "can detect that. # noinspection PyProtectedMember return type_.__setattr__ == attr._make._frozen_setattrs", "str.lower(st) return st == \"true\" or st == \"false\" def", "in (None, Any): template = dedent( \"\"\"\\ $MSG full_key: $FULL_KEY", "bool]] = None) -> Any: from omegaconf import OmegaConf if", "module_prefix = \"\" ret = module_prefix + ret if is_optional:", "obj_type resolved_hints = get_type_hints(obj_type) for field in dataclasses.fields(obj): name =", "tokens = [\"\", \"\", \"\"] but we would like [\"\",", "fragile as well. # Unfortunately currently there isn't an official", "string to be properly un-escaped. # Keep in mind that", "-> bool: origin = getattr(type_, \"__origin__\", None) if sys.version_info <", "we would like [] # ..[a] -> tokens = [\"\",", "value=value, parent=parent, ) except ValidationError as ex: format_and_raise( node=None, key=name,", "VALUE = 0 MANDATORY_MISSING = 1 INTERPOLATION = 2 def", "None: bases = getattr(ref_type, \"__orig_bases__\", None) if bases is not", "def is_float(st: str) -> bool: try: float(st) return True except", "type: ignore def construct_mapping(self, node: yaml.Node, deep: bool = False)", "_maybe_wrap flags = {\"allow_objects\": allow_objects} if allow_objects is not None", "from enum import Enum from textwrap import dedent from typing", "AttributeError: raise ImportError(f\"Class {class_name} is not in module {module_path}\") return", "-> bool: \"\"\"Check `obj` metadata to see if the given", "full_key: $FULL_KEY object_type=$OBJECT_TYPE\"\"\" ) s = string.Template(template=template) message = s.substitute(", "subclass of Dict. If so, extract the Dict keys/values.\"\"\" from", "throw_on_resolution_failure and value is None: # Resolution failure: consider that", "bool: origin = getattr(type_, \"__origin__\", None) if sys.version_info < (3,", "resolve: value = value._maybe_dereference_node( throw_on_resolution_failure=throw_on_resolution_failure ) if not throw_on_resolution_failure and", "return ret def _ensure_container(target: Any, flags: Optional[Dict[str, bool]] = None)", "def is_list_annotation(type_: Any) -> bool: origin = getattr(type_, \"__origin__\", None)", "# pragma: no cover attr = None # type: ignore", "followed by anything then `]` (ex: [b], [c]) KEY_PATH_OTHER =", "tokens[-1]: # This is a special case where the first", "is_type else type(obj) dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type", "\"\"\" return is_dict_annotation(type_) and len(get_dict_key_value_types(type_)) > 0 def is_container_annotation(type_: Any)", "ConfigIndexError, ConfigTypeError, ConfigValueError, GrammarParseError, OmegaConfBaseException, ValidationError, ) from .grammar_parser import", "is dict or typed_dict def is_list_annotation(type_: Any) -> bool: origin", "== len(key): return tokens if key[first_stop] == \"[\" and not", "a value Examples: VALUE: \"10\", \"20\", True MANDATORY_MISSING: \"???\" INTERPOLATION:", "cause: Exception, type_override: Any = None, ) -> None: from", "= {\"allow_objects\": allow_objects} if allow_objects is not None else {}", "bracket_key in others] return tokens # Similar to Python 3.7+'s", "origin is dict or typed_dict def is_list_annotation(type_: Any) -> bool:", "is_attr_class(obj: Any) -> bool: from omegaconf.base import Node if attr", "un-escaped. # Keep in mind that invalid interpolations will only", "\"${foo.bar}\", \"${foo.${bar}}\", \"${foo:bar}\", \"[${foo}, ${bar}]\", \"ftp://${host}/path\", \"${foo:${bar}, [true], {'baz': ${baz}}}\"", "node._get_node(key, validate_access=False) try: full_key = node._get_full_key(key=key) except Exception as exc:", "-> Any: from omegaconf import OmegaConf if is_primitive_container(target): assert isinstance(target,", "getattr(bases[0], \"__args__\", None) key_type: Any element_type: Any if ref_type is", "return super().construct_mapping(node, deep=deep) loader = OmegaConfLoader loader.add_implicit_resolver( \"tag:yaml.org,2002:float\", re.compile( \"\"\"^(?:", "split_key(key: str) -> List[str]: \"\"\" Split a full key path", "Node): return False return dataclasses.is_dataclass(obj) def is_attr_class(obj: Any) -> bool:", "regex below (this # is to keep this regex simple).", "False return attr.has(obj) def is_structured_config(obj: Any) -> bool: return is_attr_class(obj)", "will not detect errors. \"\"\" if _is_missing_value(value): return ValueKind.MANDATORY_MISSING value", "== dict return origin is dict or typed_dict def is_list_annotation(type_:", "elif is_attr_class(obj): return get_attr_data(obj, allow_objects=allow_objects) else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\")", "\"dots followed by any character but `.` or `[`\" #", "cause) object_type: Optional[Type[Any]] object_type_str: Optional[str] = None ref_type: Optional[Type[Any]] ref_type_str:", "key=name, value=value, cause=ex, msg=str(ex) ) d[name]._set_parent(None) dict_subclass_data = extract_dict_subclass_data(obj=obj, parent=dummy_parent)", "node._get_full_key(key=key) except Exception as exc: # Since we are handling", "if not isinstance(type_, type): type_ = type(class_or_object) assert isinstance(type_, type)", "and probably fragile as well. # Unfortunately currently there isn't", "object_type_str = type_str(object_type) ref_type = get_ref_type(node) ref_type_str = type_str(ref_type) msg", "keys starting with a bracket ([b], [c]). # Only one", "pragma: no cover def is_dict_subclass(type_: Any) -> bool: return type_", "optional by default. # This is used in `ListConfig.append` and", "float(s) return s def is_primitive_list(obj: Any) -> bool: from .base", "is_primitive_dict(obj) def get_list_element_type(ref_type: Optional[Type[Any]]) -> Any: args = getattr(ref_type, \"__args__\",", "get_type_hints, ) import yaml from .errors import ( ConfigIndexError, ConfigTypeError,", "# once support for Python 3.6 is dropped). @contextmanager def", "# type: ignore if _is_union(type_): e = ConfigValueError( f\"Union types", "Marker(\"_DEFAULT_MARKER_\") class OmegaConfDumper(yaml.Dumper): # type: ignore str_representer_added = False @staticmethod", "t is Any: return \"Any\" if t is ...: return", "There are two groups in the `KEY_PATH_OTHER` regex: one for", "is not None: vt = _resolve_forward(vt, module=module) return Dict[kt, vt]", "be processed as interpolations # for the string to be", "deep=deep) loader = OmegaConfLoader loader.add_implicit_resolver( \"tag:yaml.org,2002:float\", re.compile( \"\"\"^(?: [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)", "type(None): # noqa E721 return True, args[0] if type_ is", "Any]: if is_dataclass(obj): return get_dataclass_data(obj, allow_objects=allow_objects) elif is_attr_class(obj): return get_attr_data(obj,", "= full_key ex.value = value ex.object_type = object_type ex.object_type_str =", "try: d[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value, parent=dummy_parent, )", "is not None and isinstance(type_, type) and issubclass(type_, Dict) def", "\"False\", \"FALSE\", \"on\", \"On\", \"ON\", \"off\", \"Off\", \"OFF\", ] class", "str): self.desc = desc def __repr__(self) -> str: return self.desc", "allow_objects: Optional[bool] = None) -> Dict[str, Any]: from omegaconf.omegaconf import", "tuple # pragma: no cover def is_dict_subclass(type_: Any) -> bool:", "as optional by default. # This is used in `ListConfig.append`", "Dict keys/values.\"\"\" from omegaconf.omegaconf import _maybe_wrap is_type = isinstance(obj, type)", "if key_node.tag != yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG: continue if key_node.value in keys: raise", "\"\"\"Check whether `type_` is equivalent to `typing.Optional[T]` for some T.\"\"\"", "value: if strict_interpolation_validation: # First try the cheap regex matching", "First try the cheap regex matching that detects common interpolations.", "key (in docstring examples: a, a, .a, '') first =", "\"b\"] \"a[b]\" -> [\"a, \"b\"] \".a.b[c].d\" -> [\"\", \"a\", \"b\",", "import Node if dataclasses is None or isinstance(obj, Node): return", "to `typing.Optional[T]` for some T.\"\"\" if getattr(type_, \"__origin__\", None) is", "return dict_subclass_data else: return None def get_attr_class_field_names(obj: Any) -> List[str]:", "def get_structured_config_data( obj: Any, allow_objects: Optional[bool] = None ) ->", "= set() for key_node, value_node in node.value: if key_node.tag !=", "type(type_) is forward: return _get_class(f\"{module}.{type_.__forward_arg__}\") else: if is_dict_annotation(type_): kt, vt", "like [] # ..[a] -> tokens = [\"\", \"\", \"\"]", "obj_type = get_type_of(obj) dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type", "def __init__(self, desc: str): self.desc = desc def __repr__(self) ->", "2.2 def is_bool(st: str) -> bool: st = str.lower(st) return", "cover def is_tuple_annotation(type_: Any) -> bool: origin = getattr(type_, \"__origin__\",", "detect that. # noinspection PyProtectedMember return type_.__setattr__ == attr._make._frozen_setattrs #", "-> bool: # Uses literal '???' instead of the MISSING", "flags=flags) elif is_structured_config(target): target = OmegaConf.structured(target, flags=flags) elif not OmegaConf.is_config(target):", "type_ is Any or is_primitive_type(type_) or is_structured_config(type_) def _valid_dict_key_annotation_type(type_: Any)", "\"\"\"\\ $MSG full_key: $FULL_KEY reference_type=$REF_TYPE object_type=$OBJECT_TYPE\"\"\" ) else: template =", "= False) -> bool: if isinstance(v, str): ret = (", "get_dict_key_value_types(obj_type) for name, value in obj.items(): is_optional, type_ = _resolve_optional(element_type)", "issubclass(exception_type, OmegaConfBaseException): ex._initialized = True ex.msg = message ex.parent_node =", "# Note that a key starting with brackets, like [a],", "def get_structured_config_field_names(obj: Any) -> List[str]: if is_dataclass(obj): return get_dataclass_field_names(obj) elif", "value when `None` is not an option. _DEFAULT_MARKER_: Any =", "( get_value_kind(v, strict_interpolation_validation) == ValueKind.INTERPOLATION ) assert isinstance(ret, bool) return", "str_representer(dumper: yaml.Dumper, data: str) -> yaml.ScalarNode: with_quotes = yaml_is_bool(data) or", "$MSG full_key: $FULL_KEY reference_type=$REF_TYPE object_type=$OBJECT_TYPE\"\"\" ) else: template = dedent(", "raise yaml.constructor.ConstructorError( \"while constructing a mapping\", node.start_mark, f\"found duplicate key", "except ValidationError as ex: format_and_raise( node=None, key=name, value=value, cause=ex, msg=str(ex)", "if with_quotes else None), ) def get_omega_conf_dumper() -> Type[OmegaConfDumper]: if", "_ensure_container(target: Any, flags: Optional[Dict[str, bool]] = None) -> Any: from", "Any) -> bool: \"\"\" Checks if a type is a", "type_: variable type :return: bool \"\"\" return is_dict_annotation(type_) and len(get_dict_key_value_types(type_))", "is an extra \"\" in `tokens` that we # need", "def construct_mapping(self, node: yaml.Node, deep: bool = False) -> Any:", "is_primitive_list(obj: Any) -> bool: from .base import Container return not", "bool: try: int(st) return True except ValueError: return False #", "type_ = get_type_of(obj) if is_dataclass(type_): return is_dataclass_frozen(type_) if is_attr_class(type_): return", "resolve: bool = False, throw_on_resolution_failure: bool = True ) ->", "whether `type_` is equivalent to `typing.Optional[T]` for some T.\"\"\" if", "7, 0): return origin is List or type_ is List", "attr that can detect that. # noinspection PyProtectedMember return type_.__setattr__", "to see if the given node is optional.\"\"\" from .base", "include_module_name: bool = False) -> str: is_optional, t = _resolve_optional(t)", "with a dot (.b, .d) and one for keys starting", "exception, raising a different one here would # be misleading.", "key_type = args[0] element_type = args[1] else: key_type = Any", "variable type :return: bool \"\"\" return is_dict_annotation(type_) and len(get_dict_key_value_types(type_)) >", "is_primitive_dict(obj: Any) -> bool: t = get_type_of(obj) return t is", "strict_interpolation_validation) == ValueKind.INTERPOLATION ) assert isinstance(ret, bool) return ret return", "starts with brackets, e.g. # [a] or ..[a]. In that", "is not List and args is not None and args[0]:", "obj_type = obj if is_type else type(obj) dummy_parent = OmegaConf.create({},", "or is_float(data) return dumper.represent_scalar( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, data, style=(\"'\" if with_quotes else", "key. tokens = key[0:first_stop].split(\".\") # Optimization in case `key` has", "a special case where the first key starts with brackets,", "currently there isn't an official API in attr that can", "def is_structured_config_frozen(obj: Any) -> bool: type_ = get_type_of(obj) if is_dataclass(type_):", "= dedent( \"\"\"\\ $MSG full_key: $FULL_KEY object_type=$OBJECT_TYPE\"\"\" ) s =", "matches one key and can # be read as a", "type: ignore # pragma: no cover try: import attr except", "None else {} d = {} obj_type = get_type_of(obj) dummy_parent", "the first key starts with brackets, e.g. # [a] or", "str) -> Type[Any]: import typing # lgtm [py/import-and-import-from] forward =", "get_value_kind(v, strict_interpolation_validation) == ValueKind.INTERPOLATION ) assert isinstance(ret, bool) return ret", "two groups in the `KEY_PATH_OTHER` regex: one for keys starting", "a, a, .a, '') first = KEY_PATH_HEAD.match(key) assert first is", "\"c\", \"d\"] \"[a].b\" -> [\"a\", \"b\"] \"\"\" # Obtain the", "is list # pragma: no cover def is_tuple_annotation(type_: Any) ->", ") -> bool: from omegaconf import Node if not isinstance(value,", "KEY_TYPE=f\"{type(key).__name__}\", ) if ref_type not in (None, Any): template =", "causing exception. env_var = os.environ[\"OC_CAUSE\"] if \"OC_CAUSE\" in os.environ else", "\"${foo:bar}\", \"[${foo}, ${bar}]\", \"ftp://${host}/path\", \"${foo:${bar}, [true], {'baz': ${baz}}}\" :param value:", "is None or ref_type == Dict: key_type = Any element_type", "probably fragile as well. # Unfortunately currently there isn't an", "ignore else: return ref_type else: return Any # type: ignore", "[\"\", \"\"] tokens.pop() # Identify other key elements (in docstring", "cover def is_dict_subclass(type_: Any) -> bool: return type_ is not", "str.lower(s) == \"true\" if is_int(s): return int(s) if is_float(s): return", "False @staticmethod def str_representer(dumper: yaml.Dumper, data: str) -> yaml.ScalarNode: with_quotes", "type_ = _resolve_optional(element_type) type_ = _resolve_forward(type_, obj.__module__) try: dict_subclass_data[name] =", "is_optional, type_ = _resolve_optional(attrib.type) type_ = _resolve_forward(type_, obj.__module__) if not", "following expression matches one key and can # be read", "`ListConfig.insert` # where the appended/inserted value might or might not", "str) -> bool: try: float(st) return True except ValueError: return", "None) -> Any: from omegaconf import OmegaConf if is_primitive_container(target): assert", "potential interpolations by the presence of \"${\" in the string.", "invalid interpolations will only be detected when # `strict_interpolation_validation` is", "parent: Any) -> Optional[Dict[str, Any]]: \"\"\"Check if obj is an", "is return value def get_ref_type(obj: Any, key: Any = None)", "def _is_optional(obj: Any, key: Optional[Union[int, str]] = None) -> bool:", "def is_bool(st: str) -> bool: st = str.lower(st) return st", "to detect. # this support is tentative, if it eventually", "Optional[Node] = None if node is None: full_key = key", "is_list_annotation(type_) or is_dict_annotation(type_) def split_key(key: str) -> List[str]: \"\"\" Split", "True except ValueError: return False # DEPRECATED: remove in 2.2", "a stacktrace that includes the # causing exception. env_var =", "def is_dict_annotation(type_: Any) -> bool: origin = getattr(type_, \"__origin__\", None)", "key: [ (tag, regexp) for tag, regexp in resolvers if", "t is None: return type(t).__name__ if t is Any: return", "primitives and regular OmegaConf Containers as is return value def", "key_node, value_node in node.value: if key_node.tag != yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG: continue if", "to get a stacktrace that includes the # causing exception.", "def yaml_is_bool(b: str) -> bool: return b in YAML_BOOL_TYPES def", "ValueError: return False # DEPRECATED: remove in 2.2 def decode_primitive(s:", "f\"Union types are not supported:\\n{name}: {type_str(type_)}\" ) format_and_raise(node=None, key=None, value=value,", "b, b, b/c/d, b) others = KEY_PATH_OTHER.findall(key[first_stop:]) # There are", "type_ is Any: return True, Any return False, type_ def", "Note that escaped interpolations (ex: \"esc: \\${bar}\") are identified as", "return ref_type else: return Any # type: ignore def _raise(ex:", "generic dict, for example: list returns False typing.List returns False", "return False # DEPRECATED: remove in 2.2 def decode_primitive(s: str)", "is List or type_ is List # pragma: no cover", "= getattr(ref_type, \"__orig_bases__\", None) if bases is not None and", "(ex: [b], [c]) KEY_PATH_OTHER = re.compile(r\"\\.([^.[]*)|\\[(.*?)\\]\") # source: https://yaml.org/type/bool.html YAML_BOOL_TYPES", "= type(class_or_object) assert isinstance(type_, type) return type_ def is_structured_config_frozen(obj: Any)", "if name.startswith(\"typing.\"): name = name[len(\"typing.\") :] else: # pragma: no", "raise ValueError( \"Invalid input. Supports one of \" + \"[dict,list,DictConfig,ListConfig,dataclass,dataclass", ") format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e)) try: d[name] = _maybe_wrap(", "is skipped: this is more efficient, but will not detect", "dropped. typed_dict = hasattr(type_, \"__base__\") and type_.__base__ == dict return", "Node if not isinstance(value, Node): return value is None if", "None or _is_missing_literal(boxed) or _is_interpolation(boxed): return boxed # return primitives", "None raise ex.with_traceback(sys.exc_info()[2]) # set end OC_CAUSE=1 for full backtrace", "option. _DEFAULT_MARKER_: Any = Marker(\"_DEFAULT_MARKER_\") class OmegaConfDumper(yaml.Dumper): # type: ignore", "ret = name if include_module_name: if ( hasattr(t, \"__module__\") and", "docstring examples: b, b, b/c/d, b) others = KEY_PATH_OTHER.findall(key[first_stop:]) #", "return is_dict_annotation(type_) and len(get_dict_key_value_types(type_)) > 0 def is_container_annotation(type_: Any) ->", "if is_optional: return f\"Optional[{ret}]\" else: return ret def _ensure_container(target: Any,", "generic list, for example: list returns False typing.List returns False", "matching that detects common interpolations. if SIMPLE_INTERPOLATION_PATTERN.match(value) is None: #", "is_float(data) return dumper.represent_scalar( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, data, style=(\"'\" if with_quotes else None),", "desc def __repr__(self) -> str: return self.desc # To be", "t.__origin__ is not None: name = type_str( t.__origin__, include_module_name=include_module_name )", "can # be read as a choice between two syntaxes:", "in YAML_BOOL_TYPES def get_yaml_loader() -> Any: class OmegaConfLoader(yaml.SafeLoader): # type:", "key is not None else \"\" object_type = None ref_type", "Any, key: Any = None) -> Optional[Type[Any]]: from omegaconf import", "= getattr(t, \"__args__\", None) if args is not None: args", "== IndexError: exception_type = ConfigIndexError ex = exception_type(f\"{message}\") if issubclass(exception_type,", "from omegaconf.base import Node if isinstance(cause, AssertionError): raise if isinstance(cause,", "float(st) return True except ValueError: return False def is_int(st: str)", "= desc def __repr__(self) -> str: return self.desc # To", "can be read as \"dots followed by any character but", "\"\"\"Check `obj` metadata to see if the given node is", "is a bit hard to detect. # this support is", "and not t.__module__.startswith(\"omegaconf.\") ): module_prefix = t.__module__ + \".\" else:", "# pragma: no cover else: return origin is list #", "st == \"false\" def is_float(st: str) -> bool: try: float(st)", "that can detect that. # noinspection PyProtectedMember return type_.__setattr__ ==", "dict def is_dict_annotation(type_: Any) -> bool: origin = getattr(type_, \"__origin__\",", "-> bool: st = str.lower(st) return st == \"true\" or", "Any return key_type, element_type def valid_value_annotation_type(type_: Any) -> bool: return", "Node if isinstance(cause, AssertionError): raise if isinstance(cause, OmegaConfBaseException) and cause._initialized:", "class OmegaConfLoader(yaml.SafeLoader): # type: ignore def construct_mapping(self, node: yaml.Node, deep:", "# There are two groups in the `KEY_PATH_OTHER` regex: one", "be a Node. return True def _resolve_forward(type_: Type[Any], module: str)", "= field.default_factory() # type: ignore if _is_union(type_): e = ConfigValueError(", "= obj if is_type else type(obj) return list(attr.fields_dict(obj_type)) def get_attr_data(obj:", "is_generic_dict(type_: Any) -> bool: \"\"\" Checks if a type is", "bool: # This is very hacky and probably fragile as", "return obj._is_optional() else: # In case `obj` is not a", "True ex.msg = message ex.parent_node = node ex.child_node = child_node", "= get_type_hints(obj_type) for field in dataclasses.fields(obj): name = field.name is_optional,", "\"\"] but we would like [\"\", \"\"] tokens.pop() # Identify", "dataclasses = None # type: ignore # pragma: no cover", "cause) def type_str(t: Any, include_module_name: bool = False) -> str:", "from .errors import ( ConfigIndexError, ConfigTypeError, ConfigValueError, GrammarParseError, OmegaConfBaseException, ValidationError,", "DictKeyType.__args__) # type: ignore def is_primitive_type(type_: Any) -> bool: type_", "we are handling an exception, raising a different one here", "get_dataclass_field_names(obj) elif is_attr_class(obj): return get_attr_class_field_names(obj) else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\")", "identify potential interpolations by the presence of \"${\" in the", "omegaconf.base import Node if attr is None or isinstance(obj, Node):", "elif is_attr_class(obj): return get_attr_class_field_names(obj) else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\") def", "do the more expensive grammar parsing to detect errors. parse(value)", "SIMPLE_INTERPOLATION_PATTERN.match(value) is None: # If no match, do the more", "Obtain the first part of the key (in docstring examples:", "-> Dict[str, Any]: if is_dataclass(obj): return get_dataclass_data(obj, allow_objects=allow_objects) elif is_attr_class(obj):", "\"True\", \"TRUE\", \"false\", \"False\", \"FALSE\", \"on\", \"On\", \"ON\", \"off\", \"Off\",", "Enum) or type_ in (int, float, bool, str, type(None)) def", "None) if args is not None: args = \", \".join(", "get_yaml_loader() -> Any: class OmegaConfLoader(yaml.SafeLoader): # type: ignore def construct_mapping(self,", "def is_dataclass(obj: Any) -> bool: from omegaconf.base import Node if", "type(obj) return list(attr.fields_dict(obj_type)) def get_attr_data(obj: Any, allow_objects: Optional[bool] = None)", "will instead be handled in the next regex below (this", "yaml.Node, deep: bool = False) -> Any: keys = set()", "# This is very hacky and probably fragile as well.", "that we # need to get rid of: # [a]", "type_ = _resolve_optional(attrib.type) type_ = _resolve_forward(type_, obj.__module__) if not is_type:", "= os.environ[\"OC_CAUSE\"] if \"OC_CAUSE\" in os.environ else None debugging =", "is_dict_subclass(obj_type) if subclasses_dict: warnings.warn( f\"Class `{obj_type.__name__}` subclasses `Dict`.\" + \"", "_resolve_forward(vt, module=module) return Dict[kt, vt] # type: ignore if is_list_annotation(type_):", "== dataclasses.MISSING: value = MISSING else: if field.default_factory == dataclasses.MISSING:", "and regular OmegaConf Containers as is return value def get_ref_type(obj:", "allow_objects=allow_objects) elif is_attr_class(obj): return get_attr_data(obj, allow_objects=allow_objects) else: raise ValueError(f\"Unsupported type:", "is not None and len(bases) > 0: args = getattr(bases[0],", "= dedent( \"\"\"\\ $MSG full_key: $FULL_KEY reference_type=$REF_TYPE object_type=$OBJECT_TYPE\"\"\" ) else:", "= isinstance(obj, type) obj_type = obj if is_type else type(obj)", "to be properly un-escaped. # Keep in mind that invalid", "< (3, 7, 0): return origin is Tuple or type_", "type) return type_ def is_structured_config_frozen(obj: Any) -> bool: type_ =", "get_type_hints(obj_type) for field in dataclasses.fields(obj): name = field.name is_optional, type_", "args = \", \".join( [type_str(t, include_module_name=include_module_name) for t in t.__args__]", "interpolations. if SIMPLE_INTERPOLATION_PATTERN.match(value) is None: # If no match, do", "includes the # causing exception. env_var = os.environ[\"OC_CAUSE\"] if \"OC_CAUSE\"", "obj._is_optional() and ref_type is not Any: return Optional[ref_type] # type:", "allow_objects} if allow_objects is not None else {} from omegaconf", "ValueKind(Enum): VALUE = 0 MANDATORY_MISSING = 1 INTERPOLATION = 2", "type_ = get_type_of(type_) return issubclass(type_, Enum) or type_ in (int,", "if first_stop == len(key): return tokens if key[first_stop] == \"[\"", "return float(s) return s def is_primitive_list(obj: Any) -> bool: from", "ex.value = value ex.object_type = object_type ex.object_type_str = object_type_str ex.ref_type", "of Dict. If so, extract the Dict keys/values.\"\"\" from omegaconf.omegaconf", "bool = False, throw_on_resolution_failure: bool = True ) -> bool:", "cover attr = None # type: ignore # pragma: no", ":param type_: variable type :return: bool \"\"\" return is_dict_annotation(type_) and", "Identify other key elements (in docstring examples: b, b, b/c/d,", "and value is None: # Resolution failure: consider that it", "len(key): return tokens if key[first_stop] == \"[\" and not tokens[-1]:", "type: ignore def is_attr_frozen(type_: type) -> bool: # This is", "get_attr_class_field_names(obj) else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\") def get_structured_config_data( obj: Any,", "= None else: if key is not None and not", "\"\"] tokens.pop() # Identify other key elements (in docstring examples:", "\"true\" or st == \"false\" def is_float(st: str) -> bool:", "is_structured_config(type_) def _valid_dict_key_annotation_type(type_: Any) -> bool: from omegaconf import DictKeyType", "\"__module__\") and t.__module__ != \"builtins\" and t.__module__ != \"typing\" and", "str) -> type: from importlib import import_module module_path, _, class_name", "elif isinstance(value, Container): boxed = value._value() if boxed is None", "return f\"Optional[{ret}]\" else: return ret def _ensure_container(target: Any, flags: Optional[Dict[str,", "MISSING d = {} is_type = isinstance(obj, type) obj_type =", "is not Any: return Optional[ref_type] # type: ignore else: return", "None and len(bases) > 0: args = getattr(bases[0], \"__args__\", None)", "Optional[bool] = None ) -> Dict[str, Any]: if is_dataclass(obj): return", "{exc}>\" object_type = OmegaConf.get_type(node) object_type_str = type_str(object_type) ref_type = get_ref_type(node)", "set() for key_node, value_node in node.value: if key_node.tag != yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG:", "omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap flags = {\"allow_objects\": allow_objects} if", "= MISSING else: if field.default_factory == dataclasses.MISSING: # type: ignore", "from omegaconf.base import Node if attr is None or isinstance(obj,", "type: ignore def is_primitive_type(type_: Any) -> bool: type_ = get_type_of(type_)", "return ValueKind.VALUE # DEPRECATED: remove in 2.2 def is_bool(st: str)", "get rid of: # [a] -> tokens = [\"\"] but", "official API in attr that can detect that. # noinspection", "def is_generic_list(type_: Any) -> bool: \"\"\" Checks if a type", "throw_on_resolution_failure=throw_on_resolution_failure ) if not throw_on_resolution_failure and value is None: #", "object_type_str ex.ref_type = ref_type ex.ref_type_str = ref_type_str _raise(ex, cause) def", "or _is_interpolation(boxed): return boxed # return primitives and regular OmegaConf", "sys.gettrace() is not None full_backtrace = (debugging and not env_var", "not t.__module__.startswith(\"omegaconf.\") ): module_prefix = t.__module__ + \".\" else: module_prefix", "# [a] or ..[a]. In that case there is an", "value = MISSING else: if field.default_factory == dataclasses.MISSING: # type:", "field.default_factory == dataclasses.MISSING: # type: ignore value = MISSING else:", "is_dataclass(obj) def is_dataclass_frozen(type_: Any) -> bool: return type_.__dataclass_params__.frozen # type:", "def is_dict(obj: Any) -> bool: return is_primitive_dict(obj) or is_dict_annotation(obj) or", "source: https://yaml.org/type/bool.html YAML_BOOL_TYPES = [ \"y\", \"Y\", \"yes\", \"Yes\", \"YES\",", "`True`, then when `value` is a string containing \"${\", it", "purposedly *not* # matched here and will instead be handled", "str(t) if name.startswith(\"typing.\"): name = name[len(\"typing.\") :] else: # pragma:", "and not env_var == \"0\") or (env_var == \"1\") if", "bracket ([b], [c]). # Only one group can be non-empty.", "# `strict_interpolation_validation` is True. if isinstance(value, str) and \"${\" in", "bool: if isinstance(v, str): ret = ( get_value_kind(v, strict_interpolation_validation) ==", "allow_objects=allow_objects) else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\") class ValueKind(Enum): VALUE =", "\"1\") if full_backtrace: ex.__cause__ = cause else: ex.__cause__ = None", "Dict[str, Any]: from omegaconf.omegaconf import OmegaConf, _maybe_wrap flags = {\"allow_objects\":", "\"__orig_bases__\", None) if bases is not None and len(bases) >", "with the getitem syntax: \"a.b\" -> [\"a\", \"b\"] \"a[b]\" ->", "copy.deepcopy(cause.__dict__) _raise(ex, cause) object_type: Optional[Type[Any]] object_type_str: Optional[str] = None ref_type:", "..a). # This can be read as \"dots followed by", "3.7 if hasattr(t, \"__name__\"): name = str(t.__name__) else: if t._name", "Any) -> bool: from omegaconf import Node if isinstance(value, Node):", "typed_dict def is_list_annotation(type_: Any) -> bool: origin = getattr(type_, \"__origin__\",", ") loader.yaml_implicit_resolvers = { key: [ (tag, regexp) for tag,", "copy import os import re import string import sys import", "not in module {module_path}\") return klass def _is_union(type_: Any) ->", "in obj.items(): is_optional, type_ = _resolve_optional(element_type) type_ = _resolve_forward(type_, obj.__module__)", "MISSING if _is_union(type_): e = ConfigValueError( f\"Union types are not", "= key ex.full_key = full_key ex.value = value ex.object_type =", "# `tokens` will contain all elements composing the key. tokens", "t = _resolve_optional(t) if t is None: return type(t).__name__ if", "paths like: a.b, a[b], ..a[c].d, etc. # We begin by", "not None else {} from omegaconf import MISSING d =", "*not* # matched here and will instead be handled in", "all elements composing the key. tokens = key[0:first_stop].split(\".\") # Optimization", "if is_primitive_container(target): assert isinstance(target, (list, dict)) target = OmegaConf.create(target, flags=flags)", ":param value: Input to classify. :param strict_interpolation_validation: If `True`, then", "omegaconf import OmegaConf from omegaconf.base import Node if isinstance(cause, AssertionError):", "def get_dataclass_field_names(obj: Any) -> List[str]: return [field.name for field in", "import Node if isinstance(cause, AssertionError): raise if isinstance(cause, OmegaConfBaseException) and", "This is very hacky and probably fragile as well. #", "not be a Node. return True def _resolve_forward(type_: Type[Any], module:", "\"true\", \"True\", \"TRUE\", \"false\", \"False\", \"FALSE\", \"on\", \"On\", \"ON\", \"off\",", "Any or is_primitive_type(type_) or is_structured_config(type_) def _valid_dict_key_annotation_type(type_: Any) -> bool:", "type_override is not None: ex = type_override(str(cause)) ex.__dict__ = copy.deepcopy(cause.__dict__)", "ref_type_str: Optional[str] child_node: Optional[Node] = None if node is None:", ") d[name]._set_parent(None) dict_subclass_data = extract_dict_subclass_data(obj=obj, parent=dummy_parent) if dict_subclass_data is not", "return not isinstance(obj, Container) and isinstance(obj, (list, tuple)) def is_primitive_dict(obj:", "if is_float(s): return float(s) return s def is_primitive_list(obj: Any) ->", "full_key: $FULL_KEY reference_type=$REF_TYPE object_type=$OBJECT_TYPE\"\"\" ) else: template = dedent( \"\"\"\\", "isinstance(obj, type) obj_type = obj if is_type else type(obj) dummy_parent", "const for performance reasons. return isinstance(value, str) and value ==", "int(s) if is_float(s): return float(s) return s def is_primitive_list(obj: Any)", "\"Yes\", \"YES\", \"n\", \"N\", \"no\", \"No\", \"NO\", \"true\", \"True\", \"TRUE\",", "if dot_key else bracket_key for dot_key, bracket_key in others] return", "key_type: Any element_type: Any if ref_type is None or ref_type", "pragma: no cover # Python 3.6 if hasattr(t, \"__name__\"): name", "None: kt = _resolve_forward(kt, module=module) if vt is not None:", "dict_subclass_data = extract_dict_subclass_data(obj=obj, parent=dummy_parent) if dict_subclass_data is not None: d.update(dict_subclass_data)", "([b], [c]). # Only one group can be non-empty. tokens", "hacky and probably fragile as well. # Unfortunately currently there", "no cover def is_dict_subclass(type_: Any) -> bool: return type_ is", "Any]: \"\"\"Check whether `type_` is equivalent to `typing.Optional[T]` for some", "if key is not None and not node._is_none(): child_node =", "\"TRUE\", \"false\", \"False\", \"FALSE\", \"on\", \"On\", \"ON\", \"off\", \"Off\", \"OFF\",", "ref_type = get_ref_type(node) ref_type_str = type_str(ref_type) msg = string.Template(msg).safe_substitute( REF_TYPE=ref_type_str,", "loader.yaml_implicit_resolvers = { key: [ (tag, regexp) for tag, regexp", "for keys starting # with a dot (.b, .d) and", "starting # with a dot (.b, .d) and one for", "if et is not None: et = _resolve_forward(et, module=module) return", "it is parsed to validate the interpolation syntax. If `False`,", "str): ret = ( get_value_kind(v, strict_interpolation_validation) == ValueKind.INTERPOLATION ) assert", "some T.\"\"\" if getattr(type_, \"__origin__\", None) is Union: args =", "not None: key_type = args[0] element_type = args[1] else: key_type", "or issubclass(type_, DictKeyType.__args__) # type: ignore def is_primitive_type(type_: Any) ->", "len(bases) > 0: args = getattr(bases[0], \"__args__\", None) key_type: Any", "ValueError(f\"Unsupported type: {type(obj).__name__}\") def get_structured_config_data( obj: Any, allow_objects: Optional[bool] =", "= value._maybe_dereference_node( throw_on_resolution_failure=throw_on_resolution_failure ) if not throw_on_resolution_failure and value is", "= cause else: ex.__cause__ = None raise ex.with_traceback(sys.exc_info()[2]) # set", "except `.` or `[` (ex: .b, .d) # - `[`", "not Any: return Optional[ref_type] # type: ignore else: return ref_type", "In that case there is an extra \"\" in `tokens`", "in dataclasses.fields(obj)] def get_dataclass_data( obj: Any, allow_objects: Optional[bool] = None", "Optional[Type[Any]] object_type_str: Optional[str] = None ref_type: Optional[Type[Any]] ref_type_str: Optional[str] child_node:", "keys.add(key_node.value) return super().construct_mapping(node, deep=deep) loader = OmegaConfLoader loader.add_implicit_resolver( \"tag:yaml.org,2002:float\", re.compile(", "properly un-escaped. # Keep in mind that invalid interpolations will", "type(obj) subclasses_dict = is_dict_subclass(obj_type) if subclasses_dict: warnings.warn( f\"Class `{obj_type.__name__}` subclasses", "= f\"<unresolvable due to {type(exc).__name__}: {exc}>\" object_type = OmegaConf.get_type(node) object_type_str", "key_type = Any element_type = Any else: if args is", "this regex simple). KEY_PATH_HEAD = re.compile(r\"(\\.)*[^.[]*\") # Then we match", "warnings from contextlib import contextmanager from enum import Enum from", "or type_ is List # pragma: no cover else: return", "and ref_type is not Any: return Optional[ref_type] # type: ignore", "the cheap regex matching that detects common interpolations. if SIMPLE_INTERPOLATION_PATTERN.match(value)", "type(cause) if type_override is None else type_override if exception_type ==", "read as \"dots followed by any character but `.` or", "else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\") class ValueKind(Enum): VALUE = 0", "\" + \"[dict,list,DictConfig,ListConfig,dataclass,dataclass instance,attr class,attr class instance]\" ) return target", "value is None if resolve: value = value._maybe_dereference_node( throw_on_resolution_failure=throw_on_resolution_failure )", "ret def _ensure_container(target: Any, flags: Optional[Dict[str, bool]] = None) ->", "return origin is Dict or type_ is Dict # pragma:", ") except (ValidationError, GrammarParseError) as ex: format_and_raise( node=dummy_parent, key=name, value=value,", "not None: kt = _resolve_forward(kt, module=module) if vt is not", "def get_dataclass_data( obj: Any, allow_objects: Optional[bool] = None ) ->", "value == dataclasses.MISSING: value = MISSING else: if field.default_factory ==", "TypeError: exception_type = ConfigTypeError elif exception_type == IndexError: exception_type =", "bool: return type_ is not None and isinstance(type_, type) and", "key starting with brackets, like [a], is purposedly *not* #", "`.` or `[`\" # Note that a key starting with", "type) obj_type = obj if is_type else type(obj) dummy_parent =", "\"\"\" return is_list_annotation(type_) and get_list_element_type(type_) is not None def is_generic_dict(type_:", "\".join( [type_str(t, include_module_name=include_module_name) for t in t.__args__] ) ret =", "import SIMPLE_INTERPOLATION_PATTERN, parse try: import dataclasses except ImportError: # pragma:", "if field.default_factory == dataclasses.MISSING: # type: ignore value = MISSING", "expression matches one key and can # be read as", "klass def _is_union(type_: Any) -> bool: return getattr(type_, \"__origin__\", None)", "VALUE_TYPE=type_str(type(value), include_module_name=True), KEY_TYPE=f\"{type(key).__name__}\", ) if ref_type not in (None, Any):", "-> yaml.ScalarNode: with_quotes = yaml_is_bool(data) or is_int(data) or is_float(data) return", "List[et] # type: ignore return type_ def extract_dict_subclass_data(obj: Any, parent:", "tag != \"tag:yaml.org,2002:timestamp\" ] for key, resolvers in loader.yaml_implicit_resolvers.items() }", "attrib.default if value == attr.NOTHING: value = MISSING if _is_union(type_):", "skipped: this is more efficient, but will not detect errors.", "bool) return ret return False def _get_value(value: Any) -> Any:", "if isinstance(obj, Node): ref_type = obj._metadata.ref_type if obj._is_optional() and ref_type", "Any) -> List[str]: is_type = isinstance(obj, type) obj_type = obj", "pragma: no cover def is_tuple_annotation(type_: Any) -> bool: origin =", "Any, Dict, Iterator, List, Optional, Tuple, Type, Union, get_type_hints, )", "List[str]: return [field.name for field in dataclasses.fields(obj)] def get_dataclass_data( obj:", "Any) -> Tuple[Any, Any]: args = getattr(ref_type, \"__args__\", None) if", "if key_node.value in keys: raise yaml.constructor.ConstructorError( \"while constructing a mapping\",", "see if the given node is optional.\"\"\" from .base import", "data: str) -> yaml.ScalarNode: with_quotes = yaml_is_bool(data) or is_int(data) or", "d = {} obj_type = get_type_of(obj) dummy_parent = OmegaConf.create({}, flags=flags)", "interpolations # for the string to be properly un-escaped. #", "Any) -> bool: from .base import Container return not isinstance(obj,", "Any else: if args is not None: key_type = args[0]", "if issubclass(exception_type, OmegaConfBaseException): ex._initialized = True ex.msg = message ex.parent_node", "ex.msg = message ex.parent_node = node ex.child_node = child_node ex.key", "Unfortunately currently there isn't an official API in attr that", "= str.lower(st) return st == \"true\" or st == \"false\"", "( Any, Dict, Iterator, List, Optional, Tuple, Type, Union, get_type_hints,", "isinstance(value, str) and value == \"???\" def _is_none( value: Any,", "\"\"\"^(?: [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]* |[-+]?\\\\.(?:inf|Inf|INF) |\\\\.(?:nan|NaN|NAN))$\"\"\", re.X, ), list(\"-+0123456789.\"),", "Only one group can be non-empty. tokens += [dot_key if", "== ValueKind.INTERPOLATION ) assert isinstance(ret, bool) return ret return False", "might not be a Node. return True def _resolve_forward(type_: Type[Any],", "return get_attr_class_field_names(obj) else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\") def get_structured_config_data( obj:", "None # type: ignore # pragma: no cover try: import", "value = attrib.default if value == attr.NOTHING: value = MISSING", "= True return OmegaConfDumper def yaml_is_bool(b: str) -> bool: return", ") -> Dict[str, Any]: if is_dataclass(obj): return get_dataclass_data(obj, allow_objects=allow_objects) elif", "else: if field.default_factory == dataclasses.MISSING: # type: ignore value =", "field.name is_optional, type_ = _resolve_optional(resolved_hints[field.name]) type_ = _resolve_forward(type_, obj.__module__) if", "\"\", \"\"] but we would like [\"\", \"\"] tokens.pop() #", "container\") if isinstance(obj, Node): ref_type = obj._metadata.ref_type if obj._is_optional() and", "used instead, # once support for Python 3.6 is dropped).", "not None: raise ValueError(\"Key must only be provided when obj", "is not None: d.update(dict_subclass_data) return d def is_dataclass(obj: Any) ->", "Any: return True, Any return False, type_ def _is_optional(obj: Any,", "a bit hard to detect. # this support is tentative,", "if obj._is_optional() and ref_type is not Any: return Optional[ref_type] #", "interpolation syntax. If `False`, this parsing step is skipped: this", "getattr(mod, class_name) except AttributeError: raise ImportError(f\"Class {class_name} is not in", "string.Template(msg).safe_substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, KEY=key, FULL_KEY=full_key, VALUE=value, VALUE_TYPE=type_str(type(value), include_module_name=True), KEY_TYPE=f\"{type(key).__name__}\", )", "\\${bar}\") are identified as # interpolations: this is intended, since", "name) if value == dataclasses.MISSING: value = MISSING else: if", "is_dataclass(obj: Any) -> bool: from omegaconf.base import Node if dataclasses", "is_dict_subclass(type_: Any) -> bool: return type_ is not None and", "isinstance(value, ValueNode): return value._value() elif isinstance(value, Container): boxed = value._value()", "return \"...\" if sys.version_info < (3, 7, 0): # pragma:", "brackets, e.g. # [a] or ..[a]. In that case there", "-> [\"a, \"b\"] \".a.b[c].d\" -> [\"\", \"a\", \"b\", \"c\", \"d\"]", ") assert isinstance(ret, bool) return ret return False def _get_value(value:", "str) and value == \"???\" def _is_none( value: Any, resolve:", ") -> None: from omegaconf import OmegaConf from omegaconf.base import", "if dict_subclass_data is not None: d.update(dict_subclass_data) return d def is_dataclass(obj:", "else {} d = {} obj_type = get_type_of(obj) dummy_parent =", "`False`, this parsing step is skipped: this is more efficient,", "Dict) def is_dict(obj: Any) -> bool: return is_primitive_dict(obj) or is_dict_annotation(obj)", "boxed is None or _is_missing_literal(boxed) or _is_interpolation(boxed): return boxed #", "field in dataclasses.fields(obj)] def get_dataclass_data( obj: Any, allow_objects: Optional[bool] =", "None) if bases is not None and len(bases) > 0:", "def is_primitive_container(obj: Any) -> bool: return is_primitive_list(obj) or is_primitive_dict(obj) def", "_is_union(type_: Any) -> bool: return getattr(type_, \"__origin__\", None) is Union", "+ \" see github.com/omry/omegaconf/issues/663\", UserWarning, stacklevel=9, ) if is_type: return", "name = str(t.__name__) else: if t._name is None: if t.__origin__", "else: if t._name is None: if t.__origin__ is not None:", "return value._is_none() def get_value_kind( value: Any, strict_interpolation_validation: bool = False", "else: if key is not None: raise ValueError(\"Key must only", "get_list_element_type(type_) if et is not None: et = _resolve_forward(et, module=module)", "name = str(t._name) args = getattr(t, \"__args__\", None) if args", "List, Optional, Tuple, Type, Union, get_type_hints, ) import yaml from", "module {module_path}\") return klass def _is_union(type_: Any) -> bool: return", "False typing.List returns False typing.List[T] returns True :param type_: variable", "is deprecated,\" + \" see github.com/omry/omegaconf/issues/663\", UserWarning, stacklevel=9, ) if", "\"__origin__\", None) is Union: args = type_.__args__ if len(args) ==", "t.__module__ != \"typing\" and not t.__module__.startswith(\"omegaconf.\") ): module_prefix = t.__module__", "!= \"builtins\" and t.__module__ != \"typing\" and not t.__module__.startswith(\"omegaconf.\") ):", "ref_type_str _raise(ex, cause) def type_str(t: Any, include_module_name: bool = False)", "`]` (ex: [b], [c]) KEY_PATH_OTHER = re.compile(r\"\\.([^.[]*)|\\[(.*?)\\]\") # source: https://yaml.org/type/bool.html", "# Uses literal '???' instead of the MISSING const for", "if is_list_annotation(type_): et = get_list_element_type(type_) if et is not None:", "ValueError( \"Invalid input. Supports one of \" + \"[dict,list,DictConfig,ListConfig,dataclass,dataclass instance,attr", "Type[OmegaConfDumper]: if not OmegaConfDumper.str_representer_added: OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer) OmegaConfDumper.str_representer_added = True return", "obj_type for name, attrib in attr.fields_dict(obj_type).items(): is_optional, type_ = _resolve_optional(attrib.type)", "= node._get_full_key(key=key) except Exception as exc: # Since we are", "if include_module_name: if ( hasattr(t, \"__module__\") and t.__module__ != \"builtins\"", "strict_interpolation_validation: bool = False) -> bool: if isinstance(v, str): ret", "noinspection PyProtectedMember return type_.__setattr__ == attr._make._frozen_setattrs # type: ignore def", "None: d.update(dict_subclass_data) return d def get_dataclass_field_names(obj: Any) -> List[str]: return", "may be dropped. typed_dict = hasattr(type_, \"__base__\") and type_.__base__ ==", "None: ex = type_override(str(cause)) ex.__dict__ = copy.deepcopy(cause.__dict__) _raise(ex, cause) object_type:", "and isinstance(type_, type) and issubclass(type_, Dict) def is_dict(obj: Any) ->", "def decode_primitive(s: str) -> Any: if is_bool(s): return str.lower(s) ==", "warnings.warn( f\"Class `{obj_type.__name__}` subclasses `Dict`.\" + \" Subclassing `Dict` in", "obj._is_optional() else: # In case `obj` is not a Node,", "[ (tag, regexp) for tag, regexp in resolvers if tag", "is_dataclass(obj): return get_dataclass_field_names(obj) elif is_attr_class(obj): return get_attr_class_field_names(obj) else: raise ValueError(f\"Unsupported", "as default value when `None` is not an option. _DEFAULT_MARKER_:", "-> List[str]: if is_dataclass(obj): return get_dataclass_field_names(obj) elif is_attr_class(obj): return get_attr_class_field_names(obj)", "if tag != \"tag:yaml.org,2002:timestamp\" ] for key, resolvers in loader.yaml_implicit_resolvers.items()", "return type_.__setattr__ == attr._make._frozen_setattrs # type: ignore def get_type_of(class_or_object: Any)", "str(t.__name__) else: if t._name is None: if t.__origin__ is not", "the # causing exception. env_var = os.environ[\"OC_CAUSE\"] if \"OC_CAUSE\" in", "Any) -> bool: from omegaconf.base import Node if dataclasses is", "def _is_union(type_: Any) -> bool: return getattr(type_, \"__origin__\", None) is", "0): return origin is Dict or type_ is Dict #", "ValueKind.INTERPOLATION ) assert isinstance(ret, bool) return ret return False def", "is_primitive_type(type_: Any) -> bool: type_ = get_type_of(type_) return issubclass(type_, Enum)", "ex = type_override(str(cause)) ex.__dict__ = copy.deepcopy(cause.__dict__) _raise(ex, cause) object_type: Optional[Type[Any]]", "return int(s) if is_float(s): return float(s) return s def is_primitive_list(obj:", ">= 3.7 if hasattr(t, \"__name__\"): name = str(t.__name__) else: if", "def is_generic_dict(type_: Any) -> bool: \"\"\" Checks if a type", "be non-empty. tokens += [dot_key if dot_key else bracket_key for", "str(t.__name__) else: if t.__origin__ is not None: name = type_str(t.__origin__)", "None), ) def get_omega_conf_dumper() -> Type[OmegaConfDumper]: if not OmegaConfDumper.str_representer_added: OmegaConfDumper.add_representer(str,", "# type: ignore def construct_mapping(self, node: yaml.Node, deep: bool =", "# Regexprs to match key paths like: a.b, a[b], ..a[c].d,", "= None ref_type = None ref_type_str = None else: if", "cause else: ex.__cause__ = None raise ex.with_traceback(sys.exc_info()[2]) # set end", "child_node = node._get_node(key, validate_access=False) try: full_key = node._get_full_key(key=key) except Exception", "# pragma: no cover else: return origin is tuple #", "= ConfigValueError( f\"Union types are not supported:\\n{name}: {type_str(type_)}\" ) format_and_raise(node=None,", "is None or _is_missing_literal(boxed) or _is_interpolation(boxed): return boxed # return", "tokens # Similar to Python 3.7+'s `contextlib.nullcontext` (which should be", "raising a different one here would # be misleading. Instead,", "@staticmethod def str_representer(dumper: yaml.Dumper, data: str) -> yaml.ScalarNode: with_quotes =", "# causing exception. env_var = os.environ[\"OC_CAUSE\"] if \"OC_CAUSE\" in os.environ", "include_module_name=include_module_name) for t in t.__args__] ) ret = f\"{name}[{args}]\" else:", "None) if sys.version_info < (3, 7, 0): return origin is", "done. if first_stop == len(key): return tokens if key[first_stop] ==", "= KEY_PATH_OTHER.findall(key[first_stop:]) # There are two groups in the `KEY_PATH_OTHER`", "hasattr(t, \"__name__\"): name = str(t.__name__) else: if t.__origin__ is not", "is not None: name = type_str( t.__origin__, include_module_name=include_module_name ) else:", "<reponame>sugatoray/omegaconf<gh_stars>1000+ import copy import os import re import string import", "key is not None: raise ValueError(\"Key must only be provided", "isinstance(value, Node) return value._is_none() def get_value_kind( value: Any, strict_interpolation_validation: bool", "tokens if key[first_stop] == \"[\" and not tokens[-1]: # This", "Set the environment variable OC_CAUSE=1 to get a stacktrace that", "yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG: continue if key_node.value in keys: raise yaml.constructor.ConstructorError( \"while constructing", "getattr(type_, \"__origin__\", None) if sys.version_info < (3, 7, 0): return", "If so, extract the Dict keys/values.\"\"\" from omegaconf.omegaconf import _maybe_wrap", "ValueError: return False def is_int(st: str) -> bool: try: int(st)", "import string import sys import warnings from contextlib import contextmanager", "match, do the more expensive grammar parsing to detect errors.", "== 2 and args[1] == type(None): # noqa E721 return", "a type is a generic list, for example: list returns", "Any element_type: Any if ref_type is None or ref_type ==", "ret = module_prefix + ret if is_optional: return f\"Optional[{ret}]\" else:", "is_structured_config_frozen(obj: Any) -> bool: type_ = get_type_of(obj) if is_dataclass(type_): return", "composing the key. tokens = key[0:first_stop].split(\".\") # Optimization in case", "Node if dataclasses is None or isinstance(obj, Node): return False", "else: # pragma: no cover # Python >= 3.7 if", "def _is_none( value: Any, resolve: bool = False, throw_on_resolution_failure: bool", "detect errors. parse(value) return ValueKind.INTERPOLATION else: return ValueKind.VALUE # DEPRECATED:", "None: assert isinstance(obj, Container) obj = obj._get_node(key) if isinstance(obj, Node):", "(3, 7, 0): # pragma: no cover # Python 3.6", "def is_primitive_list(obj: Any) -> bool: from .base import Container return", "isinstance(obj, Node): return False return dataclasses.is_dataclass(obj) def is_attr_class(obj: Any) ->", "in 2.2 def decode_primitive(s: str) -> Any: if is_bool(s): return", "key is not None and not node._is_none(): child_node = node._get_node(key,", "is not None: args = \", \".join( [type_str(t, include_module_name=include_module_name) for", "= object_type_str ex.ref_type = ref_type ex.ref_type_str = ref_type_str _raise(ex, cause)", "not List and args is not None and args[0]: element_type", "= value._value() if boxed is None or _is_missing_literal(boxed) or _is_interpolation(boxed):", "would like [] # ..[a] -> tokens = [\"\", \"\",", "and t.__module__ != \"builtins\" and t.__module__ != \"typing\" and not", "\"__args__\", None) key_type: Any element_type: Any if ref_type is None", "with_quotes = yaml_is_bool(data) or is_int(data) or is_float(data) return dumper.represent_scalar( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG,", "import yaml from .errors import ( ConfigIndexError, ConfigTypeError, ConfigValueError, GrammarParseError,", "-> Optional[Type[Any]]: from omegaconf import Container, Node if isinstance(obj, Container):", "try: import attr except ImportError: # pragma: no cover attr", "default. # This is used in `ListConfig.append` and `ListConfig.insert` #", "instance of a subclass of Dict. If so, extract the", "when `None` is not an option. _DEFAULT_MARKER_: Any = Marker(\"_DEFAULT_MARKER_\")", "instance,attr class,attr class instance]\" ) return target def is_generic_list(type_: Any)", "try: dict_subclass_data[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value, parent=parent, )", "sys.version_info < (3, 7, 0): return origin is List or", "# pragma: no cover # Python >= 3.7 if hasattr(t,", "is_dict_annotation(type_): kt, vt = get_dict_key_value_types(type_) if kt is not None:", "else: if is_dict_annotation(type_): kt, vt = get_dict_key_value_types(type_) if kt is", "and `ListConfig.insert` # where the appended/inserted value might or might", "type: ignore if is_list_annotation(type_): et = get_list_element_type(type_) if et is", "ex.full_key = full_key ex.value = value ex.object_type = object_type ex.object_type_str", "bool: return getattr(type_, \"__origin__\", None) is Union def _resolve_optional(type_: Any)", "flags: Optional[Dict[str, bool]] = None) -> Any: from omegaconf import", "|[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]* |[-+]?\\\\.(?:inf|Inf|INF) |\\\\.(?:nan|NaN|NAN))$\"\"\", re.X, ), list(\"-+0123456789.\"), ) loader.yaml_implicit_resolvers", "List[str]: is_type = isinstance(obj, type) obj_type = obj if is_type", "_resolve_forward(type_, obj.__module__) if not is_type: value = getattr(obj, name) else:", "a generic dict, for example: list returns False typing.List returns", "# noinspection PyProtectedMember return type_.__setattr__ == attr._make._frozen_setattrs # type: ignore", "Any) -> bool: origin = getattr(type_, \"__origin__\", None) if sys.version_info", "return value._value() elif isinstance(value, Container): boxed = value._value() if boxed", "node is optional.\"\"\" from .base import Container, Node if key", "key path into its individual components. This is similar to", "ret = f\"{name}[{args}]\" else: ret = name if include_module_name: if", "a, a, ..a). # This can be read as \"dots", "+ \".\" else: module_prefix = \"\" ret = module_prefix +", "= None if node is None: full_key = key if", "raise ImportError(f\"Class {class_name} is not in module {module_path}\") return klass", "OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer) OmegaConfDumper.str_representer_added = True return OmegaConfDumper def yaml_is_bool(b: str)", "bool: return is_list_annotation(type_) or is_dict_annotation(type_) def split_key(key: str) -> List[str]:", "args[0]: element_type = args[0] else: element_type = Any return element_type", "value = MISSING else: value = field.default_factory() # type: ignore", "bracket_key for dot_key, bracket_key in others] return tokens # Similar", "YAML_BOOL_TYPES = [ \"y\", \"Y\", \"yes\", \"Yes\", \"YES\", \"n\", \"N\",", "other key elements (in docstring examples: b, b, b/c/d, b)", "else: return origin is list # pragma: no cover def", "GrammarParseError) as ex: format_and_raise( node=dummy_parent, key=name, value=value, cause=ex, msg=str(ex) )", "then when `value` is a string containing \"${\", it is", "is a container\") if isinstance(obj, Node): ref_type = obj._metadata.ref_type if", "from .base import Container return not isinstance(obj, Container) and isinstance(obj,", "# type: ignore # pragma: no cover # Regexprs to", "value = value._value() return _is_missing_literal(value) def _is_missing_literal(value: Any) -> bool:", "efficient, but will not detect errors. \"\"\" if _is_missing_value(value): return", "Container from .nodes import ValueNode if isinstance(value, ValueNode): return value._value()", "in other areas it may be dropped. typed_dict = hasattr(type_,", "return type_ is not None and isinstance(type_, type) and issubclass(type_,", "obj if is_type else type(obj) dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type", "sys import warnings from contextlib import contextmanager from enum import", "try: import dataclasses except ImportError: # pragma: no cover dataclasses", "True :param type_: variable type :return: bool \"\"\" return is_dict_annotation(type_)", "t is dict def is_dict_annotation(type_: Any) -> bool: origin =", "OmegaConf, _maybe_wrap flags = {\"allow_objects\": allow_objects} if allow_objects is not", "syntax. If `False`, this parsing step is skipped: this is", "object_type=$OBJECT_TYPE\"\"\" ) s = string.Template(template=template) message = s.substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str,", "# type: ignore value = MISSING else: value = field.default_factory()", "if boxed is None or _is_missing_literal(boxed) or _is_interpolation(boxed): return boxed", "-> bool: return is_list_annotation(type_) or is_dict_annotation(type_) def split_key(key: str) ->", "of the MISSING const for performance reasons. return isinstance(value, str)", "component: we are done. if first_stop == len(key): return tokens", "no match, do the more expensive grammar parsing to detect", "(list, tuple)) def is_primitive_dict(obj: Any) -> bool: t = get_type_of(obj)", "not isinstance(obj, Container) and isinstance(obj, (list, tuple)) def is_primitive_dict(obj: Any)", "_resolve_forward(et, module=module) return List[et] # type: ignore return type_ def", "= None, ) -> None: from omegaconf import OmegaConf from", "is_dict_annotation(obj) or is_dict_subclass(obj) def is_primitive_container(obj: Any) -> bool: return is_primitive_list(obj)", "import Container, Node if isinstance(obj, Container): if key is not", "anything then `]` (ex: [b], [c]) KEY_PATH_OTHER = re.compile(r\"\\.([^.[]*)|\\[(.*?)\\]\") #", "format_and_raise( node: Any, key: Any, value: Any, msg: str, cause:", "loader.add_implicit_resolver( \"tag:yaml.org,2002:float\", re.compile( \"\"\"^(?: [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]* |[-+]?\\\\.(?:inf|Inf|INF) |\\\\.(?:nan|NaN|NAN))$\"\"\",", "if bases is not None and len(bases) > 0: args", "node is None: full_key = key if key is not", "support for Python 3.6 is dropped). @contextmanager def nullcontext(enter_result: Any", "DEPRECATED: remove in 2.2 def is_bool(st: str) -> bool: st", "Any, strict_interpolation_validation: bool = False) -> bool: if isinstance(v, str):", "extra \"\" in `tokens` that we # need to get", "one group can be non-empty. tokens += [dot_key if dot_key", "pragma: no cover try: import attr except ImportError: # pragma:", "assert isinstance(type_, type) return type_ def is_structured_config_frozen(obj: Any) -> bool:", "PyProtectedMember return type_.__setattr__ == attr._make._frozen_setattrs # type: ignore def get_type_of(class_or_object:", "t.__module__ != \"builtins\" and t.__module__ != \"typing\" and not t.__module__.startswith(\"omegaconf.\")", "type_str(t: Any, include_module_name: bool = False) -> str: is_optional, t", "None if node is None: full_key = key if key", "get_attr_data(obj, allow_objects=allow_objects) else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\") class ValueKind(Enum): VALUE", "ref_type not in (None, Any): template = dedent( \"\"\"\\ $MSG", "if ( hasattr(t, \"__module__\") and t.__module__ != \"builtins\" and t.__module__", "# type: ignore def is_primitive_type(type_: Any) -> bool: type_ =", "performance reasons. return isinstance(value, str) and value == \"???\" def", "else: # In case `obj` is not a Node, treat", "get_attr_class_field_names(obj: Any) -> List[str]: is_type = isinstance(obj, type) obj_type =", "# matched here and will instead be handled in the", "-> [\"\", \"a\", \"b\", \"c\", \"d\"] \"[a].b\" -> [\"a\", \"b\"]", "_is_missing_literal(boxed) or _is_interpolation(boxed): return boxed # return primitives and regular", "This is a special case where the first key starts", "key starts with brackets, e.g. # [a] or ..[a]. In", "ValueNode if isinstance(value, ValueNode): return value._value() elif isinstance(value, Container): boxed", "\"b\"] \".a.b[c].d\" -> [\"\", \"a\", \"b\", \"c\", \"d\"] \"[a].b\" ->", "if obj is an instance of a subclass of Dict.", "True. if isinstance(value, str) and \"${\" in value: if strict_interpolation_validation:", "is_float(s): return float(s) return s def is_primitive_list(obj: Any) -> bool:", "None: obj = obj._get_node(key) else: if key is not None:", "and isinstance(obj, (list, tuple)) def is_primitive_dict(obj: Any) -> bool: t", "brackets, like [a], is purposedly *not* # matched here and", "and not tokens[-1]: # This is a special case where", "st == \"true\" or st == \"false\" def is_float(st: str)", "= string.Template(msg).safe_substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, KEY=key, FULL_KEY=full_key, VALUE=value, VALUE_TYPE=type_str(type(value), include_module_name=True), KEY_TYPE=f\"{type(key).__name__}\",", "but will not detect errors. \"\"\" if _is_missing_value(value): return ValueKind.MANDATORY_MISSING", "would like [\"\", \"\"] tokens.pop() # Identify other key elements", "no cover dataclasses = None # type: ignore # pragma:", "[-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]* |[-+]?\\\\.(?:inf|Inf|INF) |\\\\.(?:nan|NaN|NAN))$\"\"\", re.X, ), list(\"-+0123456789.\"), )", "-> bool: from .base import Container return not isinstance(obj, Container)", "when obj is a container\") if isinstance(obj, Node): ref_type =", "type_ is Tuple # pragma: no cover else: return origin", "by default. # This is used in `ListConfig.append` and `ListConfig.insert`", "if not OmegaConfDumper.str_representer_added: OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer) OmegaConfDumper.str_representer_added = True return OmegaConfDumper", "bool: from omegaconf.base import Node if attr is None or", ":] else: # pragma: no cover # Python >= 3.7", "is Any or issubclass(type_, DictKeyType.__args__) # type: ignore def is_primitive_type(type_:", "keys starting # with a dot (.b, .d) and one", "-> bool: return is_primitive_dict(obj) or is_dict_annotation(obj) or is_dict_subclass(obj) def is_primitive_container(obj:", "return None def get_attr_class_field_names(obj: Any) -> List[str]: is_type = isinstance(obj,", "MSG=msg, FULL_KEY=full_key ) exception_type = type(cause) if type_override is None", "default value when `None` is not an option. _DEFAULT_MARKER_: Any", "else: key_type = Any element_type = Any return key_type, element_type", "\"\" ret = module_prefix + ret if is_optional: return f\"Optional[{ret}]\"", "= False) -> Any: keys = set() for key_node, value_node", "try: float(st) return True except ValueError: return False def is_int(st:", "List[str]: \"\"\" Split a full key path into its individual", "= _resolve_optional(element_type) type_ = _resolve_forward(type_, obj.__module__) try: dict_subclass_data[name] = _maybe_wrap(", "# pragma: no cover else: # pragma: no cover #", "full_backtrace = (debugging and not env_var == \"0\") or (env_var", "ValidationError as ex: format_and_raise( node=None, key=name, value=value, cause=ex, msg=str(ex) )", "type): type_ = type(class_or_object) assert isinstance(type_, type) return type_ def", "or `[` (ex: .b, .d) # - `[` followed by", "Optimization in case `key` has no other component: we are", "value == \"???\" def _is_none( value: Any, resolve: bool =", "= obj_type for name, attrib in attr.fields_dict(obj_type).items(): is_optional, type_ =", "return tokens if key[first_stop] == \"[\" and not tokens[-1]: #", "elif is_structured_config(target): target = OmegaConf.structured(target, flags=flags) elif not OmegaConf.is_config(target): raise", "{\"allow_objects\": allow_objects} if allow_objects is not None else {} from", "one key and can # be read as a choice", "Dict[str, Any]: from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap flags =", "returns False typing.List[T] returns True :param type_: variable type :return:", "str(t._name) args = getattr(t, \"__args__\", None) if args is not", "are identified as # interpolations: this is intended, since they", "Optional[Type[Any]] ref_type_str: Optional[str] child_node: Optional[Node] = None if node is", "if getattr(type_, \"__origin__\", None) is Union: args = type_.__args__ if", "if ref_type is None or ref_type == Dict: key_type =", "= f\"{name}[{args}]\" else: ret = name if include_module_name: if (", "MANDATORY_MISSING: \"???\" INTERPOLATION: \"${foo.bar}\", \"${foo.${bar}}\", \"${foo:bar}\", \"[${foo}, ${bar}]\", \"ftp://${host}/path\", \"${foo:${bar},", "return [field.name for field in dataclasses.fields(obj)] def get_dataclass_data( obj: Any,", "return is_primitive_list(obj) or is_primitive_dict(obj) def get_list_element_type(ref_type: Optional[Type[Any]]) -> Any: args", "is_optional=is_optional, key=name, value=value, parent=dummy_parent, ) except (ValidationError, GrammarParseError) as ex:", "ex._initialized = True ex.msg = message ex.parent_node = node ex.child_node", "the getitem syntax: \"a.b\" -> [\"a\", \"b\"] \"a[b]\" -> [\"a,", "== Dict: key_type = Any element_type = Any else: if", "# Keep in mind that invalid interpolations will only be", "= True ) -> bool: from omegaconf import Node if", ":param type_: variable type :return: bool \"\"\" return is_list_annotation(type_) and", "used in `ListConfig.append` and `ListConfig.insert` # where the appended/inserted value", "= name[len(\"typing.\") :] else: # pragma: no cover # Python", "vt is not None: vt = _resolve_forward(vt, module=module) return Dict[kt,", "to match key paths like: a.b, a[b], ..a[c].d, etc. #", "ref_type=type_, is_optional=is_optional, key=name, value=value, parent=parent, ) except ValidationError as ex:", "> 0: args = getattr(bases[0], \"__args__\", None) key_type: Any element_type:", "case `obj` is not a Node, treat it as optional", "string.Template(template=template) message = s.substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key ) exception_type", "pragma: no cover dataclasses = None # type: ignore #", "dedent( \"\"\"\\ $MSG full_key: $FULL_KEY object_type=$OBJECT_TYPE\"\"\" ) s = string.Template(template=template)", "import OmegaConf from omegaconf.base import Node if isinstance(cause, AssertionError): raise", "loader.yaml_implicit_resolvers.items() } return loader def _get_class(path: str) -> type: from", "*not* None. return False assert isinstance(value, Node) return value._is_none() def", "Any: keys = set() for key_node, value_node in node.value: if", "cover # type_dict is a bit hard to detect. #", "raise ValueError(f\"Unsupported type: {type(obj).__name__}\") class ValueKind(Enum): VALUE = 0 MANDATORY_MISSING", "omegaconf import DictKeyType return type_ is None or type_ is", "resolved_hints = get_type_hints(obj_type) for field in dataclasses.fields(obj): name = field.name", "-> Any: class OmegaConfLoader(yaml.SafeLoader): # type: ignore def construct_mapping(self, node:", "(debugging and not env_var == \"0\") or (env_var == \"1\")", "is_int(data) or is_float(data) return dumper.represent_scalar( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, data, style=(\"'\" if with_quotes", "is_attr_frozen(type_: type) -> bool: # This is very hacky and", "is_attr_class(obj) or is_dataclass(obj) def is_dataclass_frozen(type_: Any) -> bool: return type_.__dataclass_params__.frozen", "re import string import sys import warnings from contextlib import", "return origin is tuple # pragma: no cover def is_dict_subclass(type_:", "into its individual components. This is similar to `key.split(\".\")` but", "args = getattr(t, \"__args__\", None) if args is not None:", "as is return value def get_ref_type(obj: Any, key: Any =", "a subclass of Dict. If so, extract the Dict keys/values.\"\"\"", "if isinstance(cause, OmegaConfBaseException) and cause._initialized: ex = cause if type_override", "( hasattr(t, \"__module__\") and t.__module__ != \"builtins\" and t.__module__ !=", "style=(\"'\" if with_quotes else None), ) def get_omega_conf_dumper() -> Type[OmegaConfDumper]:", "== type(None): # noqa E721 return True, args[0] if type_", "construct_mapping(self, node: yaml.Node, deep: bool = False) -> Any: keys", "typed_dict = hasattr(type_, \"__base__\") and type_.__base__ == dict return origin", "`value` is a string containing \"${\", it is parsed to", "# Optimization in case `key` has no other component: we", "is a special case where the first key starts with", "None) if args is None: bases = getattr(ref_type, \"__orig_bases__\", None)", "# type: ignore if type(type_) is forward: return _get_class(f\"{module}.{type_.__forward_arg__}\") else:", "# Only one group can be non-empty. tokens += [dot_key", "\"\"\" Split a full key path into its individual components.", "is_type else type(obj) subclasses_dict = is_dict_subclass(obj_type) if subclasses_dict: warnings.warn( f\"Class", "docstring examples: a, a, .a, '') first = KEY_PATH_HEAD.match(key) assert", "for field in dataclasses.fields(obj)] def get_dataclass_data( obj: Any, allow_objects: Optional[bool]", "debugging = sys.gettrace() is not None full_backtrace = (debugging and", "> 0 def is_container_annotation(type_: Any) -> bool: return is_list_annotation(type_) or", "format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e)) try: d[name] = _maybe_wrap( ref_type=type_,", "\"[${foo}, ${bar}]\", \"ftp://${host}/path\", \"${foo:${bar}, [true], {'baz': ${baz}}}\" :param value: Input", "= first.span()[1] # `tokens` will contain all elements composing the", "is dict def is_dict_annotation(type_: Any) -> bool: origin = getattr(type_,", "= Any return key_type, element_type def valid_value_annotation_type(type_: Any) -> bool:", "IndexError: exception_type = ConfigIndexError ex = exception_type(f\"{message}\") if issubclass(exception_type, OmegaConfBaseException):", "ex.ref_type = ref_type ex.ref_type_str = ref_type_str _raise(ex, cause) def type_str(t:", "return get_attr_data(obj, allow_objects=allow_objects) else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\") class ValueKind(Enum):", "node=dummy_parent, key=name, value=value, cause=ex, msg=str(ex) ) d[name]._set_parent(None) dict_subclass_data = extract_dict_subclass_data(obj=obj,", "-> bool: # This is very hacky and probably fragile", "getattr(obj, name) else: value = attrib.default if value == attr.NOTHING:", "type :return: bool \"\"\" return is_dict_annotation(type_) and len(get_dict_key_value_types(type_)) > 0", "= obj if is_type else type(obj) subclasses_dict = is_dict_subclass(obj_type) if", "is_list_annotation(type_): et = get_list_element_type(type_) if et is not None: et", "except ValueError: return False # DEPRECATED: remove in 2.2 def", "Container): if key is not None: obj = obj._get_node(key) else:", "else: template = dedent( \"\"\"\\ $MSG full_key: $FULL_KEY object_type=$OBJECT_TYPE\"\"\" )", "KEY_PATH_HEAD.match(key) assert first is not None first_stop = first.span()[1] #", "`type_` is equivalent to `typing.Optional[T]` for some T.\"\"\" if getattr(type_,", "this is intended, since they must be processed as interpolations", "OmegaConfDumper.str_representer) OmegaConfDumper.str_representer_added = True return OmegaConfDumper def yaml_is_bool(b: str) ->", "is_primitive_list(obj) or is_primitive_dict(obj) def get_list_element_type(ref_type: Optional[Type[Any]]) -> Any: args =", "errors. \"\"\" if _is_missing_value(value): return ValueKind.MANDATORY_MISSING value = _get_value(value) #", "value def get_ref_type(obj: Any, key: Any = None) -> Optional[Type[Any]]:", "{class_name} is not in module {module_path}\") return klass def _is_union(type_:", "Any) -> bool: return type_ is not None and isinstance(type_,", "Tuple[bool, Any]: \"\"\"Check whether `type_` is equivalent to `typing.Optional[T]` for", "OmegaConf Containers as is return value def get_ref_type(obj: Any, key:", "isinstance(value, Container): boxed = value._value() if boxed is None or", "isinstance(cause, AssertionError): raise if isinstance(cause, OmegaConfBaseException) and cause._initialized: ex =", "a choice between two syntaxes: # - `.` followed by", "= field.name is_optional, type_ = _resolve_optional(resolved_hints[field.name]) type_ = _resolve_forward(type_, obj.__module__)", "__init__(self, desc: str): self.desc = desc def __repr__(self) -> str:", "isinstance(obj, (list, tuple)) def is_primitive_dict(obj: Any) -> bool: t =", "if isinstance(value, ValueNode): return value._value() elif isinstance(value, Container): boxed =", "= None) -> Optional[Type[Any]]: from omegaconf import Container, Node if", "to get rid of: # [a] -> tokens = [\"\"]", "= node ex.child_node = child_node ex.key = key ex.full_key =", "isinstance(obj, Container) obj = obj._get_node(key) if isinstance(obj, Node): return obj._is_optional()", "Structured Config classes is deprecated,\" + \" see github.com/omry/omegaconf/issues/663\", UserWarning,", "value=value, cause=e, msg=str(e)) try: d[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name,", "the more expensive grammar parsing to detect errors. parse(value) return", "by matching the head (in these examples: a, a, ..a).", "if hasattr(typing, \"ForwardRef\") else typing._ForwardRef # type: ignore if type(type_)", "MISSING, OmegaConf, _maybe_wrap flags = {\"allow_objects\": allow_objects} if allow_objects is", "..[a]. In that case there is an extra \"\" in", "if hasattr(t, \"__name__\"): name = str(t.__name__) else: if t._name is", "Any) -> bool: from omegaconf import DictKeyType return type_ is", "[field.name for field in dataclasses.fields(obj)] def get_dataclass_data( obj: Any, allow_objects:", "group can be non-empty. tokens += [dot_key if dot_key else", "return type_ def is_structured_config_frozen(obj: Any) -> bool: type_ = get_type_of(obj)", "is_attr_class(obj): return get_attr_data(obj, allow_objects=allow_objects) else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\") class", "_is_missing_literal(value: Any) -> bool: # Uses literal '???' instead of", "full_key = key if key is not None else \"\"", "None or type_ is Any or issubclass(type_, DictKeyType.__args__) # type:", "return Dict[kt, vt] # type: ignore if is_list_annotation(type_): et =", "Any) -> List[str]: if is_dataclass(obj): return get_dataclass_field_names(obj) elif is_attr_class(obj): return", "type_ = _resolve_forward(type_, obj.__module__) if not is_type: value = getattr(obj,", "to `key.split(\".\")` but also works with the getitem syntax: \"a.b\"", "d = {} is_type = isinstance(obj, type) obj_type = obj", "MISSING const for performance reasons. return isinstance(value, str) and value", "import Node if attr is None or isinstance(obj, Node): return", "is_primitive_container(obj: Any) -> bool: return is_primitive_list(obj) or is_primitive_dict(obj) def get_list_element_type(ref_type:", "key=name, value=value, parent=dummy_parent, ) except (ValidationError, GrammarParseError) as ex: format_and_raise(", "detects common interpolations. if SIMPLE_INTERPOLATION_PATTERN.match(value) is None: # If no", "and len(bases) > 0: args = getattr(bases[0], \"__args__\", None) key_type:", "type_ def is_structured_config_frozen(obj: Any) -> bool: type_ = get_type_of(obj) if", "instead be handled in the next regex below (this #", "If `True`, then when `value` is a string containing \"${\",", "is not None: name = type_str(t.__origin__) else: name = str(t)", "similar to `key.split(\".\")` but also works with the getitem syntax:", "-> List[str]: is_type = isinstance(obj, type) obj_type = obj if", "or typed_dict def is_list_annotation(type_: Any) -> bool: origin = getattr(type_,", "str, cause: Exception, type_override: Any = None, ) -> None:", "get_dataclass_data( obj: Any, allow_objects: Optional[bool] = None ) -> Dict[str,", "This is used in `ListConfig.append` and `ListConfig.insert` # where the", "= _get_value(value) # We identify potential interpolations by the presence", "key, resolvers in loader.yaml_implicit_resolvers.items() } return loader def _get_class(path: str)", "= Any element_type = Any else: if args is not", "for performance reasons. return isinstance(value, str) and value == \"???\"", "Iterator, List, Optional, Tuple, Type, Union, get_type_hints, ) import yaml", "is_float(st: str) -> bool: try: float(st) return True except ValueError:", "-> bool: \"\"\" Checks if a type is a generic", "import OmegaConf, _maybe_wrap flags = {\"allow_objects\": allow_objects} if allow_objects is", "key[first_stop] == \"[\" and not tokens[-1]: # This is a", "`ListConfig.append` and `ListConfig.insert` # where the appended/inserted value might or", "element_type def valid_value_annotation_type(type_: Any) -> bool: return type_ is Any", "Node): return False return attr.has(obj) def is_structured_config(obj: Any) -> bool:", "more expensive grammar parsing to detect errors. parse(value) return ValueKind.INTERPOLATION", "in mind that invalid interpolations will only be detected when", "ignore def construct_mapping(self, node: yaml.Node, deep: bool = False) ->", "bool: from .base import Container return not isinstance(obj, Container) and", "else: name = str(t) if name.startswith(\"typing.\"): name = name[len(\"typing.\") :]", "if allow_objects is not None else {} from omegaconf import", "bool = False) -> Any: keys = set() for key_node,", "node: yaml.Node, deep: bool = False) -> Any: keys =", "cover # Python 3.6 if hasattr(t, \"__name__\"): name = str(t.__name__)", "flags = {\"allow_objects\": allow_objects} if allow_objects is not None else", "get_dataclass_field_names(obj: Any) -> List[str]: return [field.name for field in dataclasses.fields(obj)]", "def split_key(key: str) -> List[str]: \"\"\" Split a full key", "is_tuple_annotation(type_: Any) -> bool: origin = getattr(type_, \"__origin__\", None) if", "def extract_dict_subclass_data(obj: Any, parent: Any) -> Optional[Dict[str, Any]]: \"\"\"Check if", "def is_tuple_annotation(type_: Any) -> bool: origin = getattr(type_, \"__origin__\", None)", "not throw_on_resolution_failure and value is None: # Resolution failure: consider", "-> Any: if is_bool(s): return str.lower(s) == \"true\" if is_int(s):", "os import re import string import sys import warnings from", "regexp in resolvers if tag != \"tag:yaml.org,2002:timestamp\" ] for key,", "[] # ..[a] -> tokens = [\"\", \"\", \"\"] but", "detected when # `strict_interpolation_validation` is True. if isinstance(value, str) and", "OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key ) exception_type = type(cause) if type_override is", "-> bool: t = get_type_of(obj) return t is dict def", "== \"true\" if is_int(s): return int(s) if is_float(s): return float(s)", "{} d = {} obj_type = get_type_of(obj) dummy_parent = OmegaConf.create({},", "class_name = path.rpartition(\".\") mod = import_module(module_path) try: klass: type =", "type(obj) dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type for name,", "is_structured_config(target): target = OmegaConf.structured(target, flags=flags) elif not OmegaConf.is_config(target): raise ValueError(", "but `.` or `[`\" # Note that a key starting", "get_attr_data(obj: Any, allow_objects: Optional[bool] = None) -> Dict[str, Any]: from", "-> Tuple[Any, Any]: args = getattr(ref_type, \"__args__\", None) if args", "ref_type_str = type_str(ref_type) msg = string.Template(msg).safe_substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, KEY=key, FULL_KEY=full_key,", "keys/values.\"\"\" from omegaconf.omegaconf import _maybe_wrap is_type = isinstance(obj, type) obj_type", "is_dict_annotation(type_) def split_key(key: str) -> List[str]: \"\"\" Split a full", "classes is deprecated,\" + \" see github.com/omry/omegaconf/issues/663\", UserWarning, stacklevel=9, )", "= Any return element_type def get_dict_key_value_types(ref_type: Any) -> Tuple[Any, Any]:", "importlib import import_module module_path, _, class_name = path.rpartition(\".\") mod =", "subclasses_dict: dict_subclass_data = {} key_type, element_type = get_dict_key_value_types(obj_type) for name,", "import DictKeyType return type_ is None or type_ is Any", "bool: return is_primitive_dict(obj) or is_dict_annotation(obj) or is_dict_subclass(obj) def is_primitive_container(obj: Any)", "b, b/c/d, b) others = KEY_PATH_OTHER.findall(key[first_stop:]) # There are two", "no cover # Python >= 3.7 if hasattr(t, \"__name__\"): name", "0 MANDATORY_MISSING = 1 INTERPOLATION = 2 def _is_missing_value(value: Any)", "the interpolation syntax. If `False`, this parsing step is skipped:", "isinstance(obj, Node): return False return attr.has(obj) def is_structured_config(obj: Any) ->", "is intended, since they must be processed as interpolations #", "list # pragma: no cover def is_tuple_annotation(type_: Any) -> bool:", "is not None: et = _resolve_forward(et, module=module) return List[et] #", "= hasattr(type_, \"__base__\") and type_.__base__ == dict return origin is", "ValidationError, ) from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse try: import dataclasses", "attr._make._frozen_setattrs # type: ignore def get_type_of(class_or_object: Any) -> Type[Any]: type_", "getattr(obj, name) if value == dataclasses.MISSING: value = MISSING else:", "\"false\" def is_float(st: str) -> bool: try: float(st) return True", "-> None: from omegaconf import OmegaConf from omegaconf.base import Node", "except ValueError: return False def is_int(st: str) -> bool: try:", "Marker: def __init__(self, desc: str): self.desc = desc def __repr__(self)", "= s.substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key ) exception_type = type(cause)", "7, 0): return origin is Dict or type_ is Dict", "(int, float, bool, str, type(None)) def _is_interpolation(v: Any, strict_interpolation_validation: bool", "in the key. full_key = f\"<unresolvable due to {type(exc).__name__}: {exc}>\"", "# Similar to Python 3.7+'s `contextlib.nullcontext` (which should be used", "else: ex.__cause__ = None raise ex.with_traceback(sys.exc_info()[2]) # set end OC_CAUSE=1", "is not None full_backtrace = (debugging and not env_var ==", "Any = None) -> Optional[Type[Any]]: from omegaconf import Container, Node", "OmegaConfDumper def yaml_is_bool(b: str) -> bool: return b in YAML_BOOL_TYPES", "containing \"${\", it is parsed to validate the interpolation syntax.", "False) -> bool: if isinstance(v, str): ret = ( get_value_kind(v,", "= [\"\"] but we would like [] # ..[a] ->", "None: d.update(dict_subclass_data) return d def is_dataclass(obj: Any) -> bool: from", "INTERPOLATION = 2 def _is_missing_value(value: Any) -> bool: from omegaconf", "a type is a generic dict, for example: list returns", "Container) and isinstance(obj, (list, tuple)) def is_primitive_dict(obj: Any) -> bool:", "import Container, Node if key is not None: assert isinstance(obj,", "if allow_objects is not None else {} d = {}", "not isinstance(type_, type): type_ = type(class_or_object) assert isinstance(type_, type) return", "for full backtrace def format_and_raise( node: Any, key: Any, value:", "not None def is_generic_dict(type_: Any) -> bool: \"\"\" Checks if", "_maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value, parent=dummy_parent, ) except (ValidationError, GrammarParseError)", "Dict. If so, extract the Dict keys/values.\"\"\" from omegaconf.omegaconf import", "def valid_value_annotation_type(type_: Any) -> bool: return type_ is Any or", "dot_key else bracket_key for dot_key, bracket_key in others] return tokens", ":return: bool \"\"\" return is_dict_annotation(type_) and len(get_dict_key_value_types(type_)) > 0 def", "# with a dot (.b, .d) and one for keys", "= False @staticmethod def str_representer(dumper: yaml.Dumper, data: str) -> yaml.ScalarNode:", "first = KEY_PATH_HEAD.match(key) assert first is not None first_stop =", "= getattr(obj, name) else: value = attrib.default if value ==", "OmegaConf if is_primitive_container(target): assert isinstance(target, (list, dict)) target = OmegaConf.create(target,", "dummy_parent._metadata.object_type = obj_type resolved_hints = get_type_hints(obj_type) for field in dataclasses.fields(obj):", "None # type: ignore # pragma: no cover # Regexprs", "a dot (.b, .d) and one for keys starting with", "name = str(t) if name.startswith(\"typing.\"): name = name[len(\"typing.\") :] else:", "a[b], ..a[c].d, etc. # We begin by matching the head", "getattr(type_, \"__origin__\", None) is Union def _resolve_optional(type_: Any) -> Tuple[bool,", "\"y\", \"Y\", \"yes\", \"Yes\", \"YES\", \"n\", \"N\", \"no\", \"No\", \"NO\",", "return str.lower(s) == \"true\" if is_int(s): return int(s) if is_float(s):", "{} from omegaconf import MISSING d = {} is_type =", "for t in t.__args__] ) ret = f\"{name}[{args}]\" else: ret", "get_ref_type(node) ref_type_str = type_str(ref_type) msg = string.Template(msg).safe_substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, KEY=key,", "if t.__origin__ is not None: name = type_str(t.__origin__) else: name", "= KEY_PATH_HEAD.match(key) assert first is not None first_stop = first.span()[1]", "is not None: obj = obj._get_node(key) else: if key is", "{key_node.value}\", key_node.start_mark, ) keys.add(key_node.value) return super().construct_mapping(node, deep=deep) loader = OmegaConfLoader", "first.span()[1] # `tokens` will contain all elements composing the key.", ") from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse try: import dataclasses except", "see github.com/omry/omegaconf/issues/663\", UserWarning, stacklevel=9, ) if is_type: return None elif", "attr except ImportError: # pragma: no cover attr = None", "None. return False assert isinstance(value, Node) return value._is_none() def get_value_kind(", "vt] # type: ignore if is_list_annotation(type_): et = get_list_element_type(type_) if", "= True ex.msg = message ex.parent_node = node ex.child_node =", "OC_CAUSE=1 for full backtrace def format_and_raise( node: Any, key: Any,", "ConfigTypeError elif exception_type == IndexError: exception_type = ConfigIndexError ex =", "part of the key (in docstring examples: a, a, .a,", "ret return False def _get_value(value: Any) -> Any: from .base", "Union: args = type_.__args__ if len(args) == 2 and args[1]", "== \"true\" or st == \"false\" def is_float(st: str) ->", "type) -> bool: # This is very hacky and probably", "== dataclasses.MISSING: # type: ignore value = MISSING else: value", "= _resolve_forward(kt, module=module) if vt is not None: vt =", "between two syntaxes: # - `.` followed by anything except", "it in the key. full_key = f\"<unresolvable due to {type(exc).__name__}:", "`tokens` that we # need to get rid of: #", "value._maybe_dereference_node( throw_on_resolution_failure=throw_on_resolution_failure ) if not throw_on_resolution_failure and value is None:", "support is tentative, if it eventually causes issues in other", "if not throw_on_resolution_failure and value is None: # Resolution failure:", "else: value = attrib.default if value == attr.NOTHING: value =", "issubclass(type_, DictKeyType.__args__) # type: ignore def is_primitive_type(type_: Any) -> bool:", "import ValueNode if isinstance(value, ValueNode): return value._value() elif isinstance(value, Container):", "the head (in these examples: a, a, ..a). # This", "= _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value, parent=dummy_parent, ) except (ValidationError,", "[true], {'baz': ${baz}}}\" :param value: Input to classify. :param strict_interpolation_validation:", "class,attr class instance]\" ) return target def is_generic_list(type_: Any) ->", "except AttributeError: raise ImportError(f\"Class {class_name} is not in module {module_path}\")", "is_dict_subclass(obj) def is_primitive_container(obj: Any) -> bool: return is_primitive_list(obj) or is_primitive_dict(obj)", "return ValueKind.MANDATORY_MISSING value = _get_value(value) # We identify potential interpolations", "the key. full_key = f\"<unresolvable due to {type(exc).__name__}: {exc}>\" object_type", "Any if ref_type is None or ref_type == Dict: key_type", "str) -> List[str]: \"\"\" Split a full key path into", "bool = True ) -> bool: from omegaconf import Node", "import dedent from typing import ( Any, Dict, Iterator, List,", "] class Marker: def __init__(self, desc: str): self.desc = desc", "isinstance(value, Node): return value is None if resolve: value =", "name = type_str( t.__origin__, include_module_name=include_module_name ) else: name = str(t._name)", "is_container_annotation(type_: Any) -> bool: return is_list_annotation(type_) or is_dict_annotation(type_) def split_key(key:", "= str(t._name) args = getattr(t, \"__args__\", None) if args is", "except Exception as exc: # Since we are handling an", "if is_type else type(obj) return list(attr.fields_dict(obj_type)) def get_attr_data(obj: Any, allow_objects:", "is None: # Resolution failure: consider that it is *not*", "bool: st = str.lower(st) return st == \"true\" or st", "isinstance(type_, type): type_ = type(class_or_object) assert isinstance(type_, type) return type_", "[\"\", \"\", \"\"] but we would like [\"\", \"\"] tokens.pop()", "f\"found duplicate key {key_node.value}\", key_node.start_mark, ) keys.add(key_node.value) return super().construct_mapping(node, deep=deep)", "= type_str(object_type) ref_type = get_ref_type(node) ref_type_str = type_str(ref_type) msg =", "else: return origin is tuple # pragma: no cover def", "bool: type_ = get_type_of(obj) if is_dataclass(type_): return is_dataclass_frozen(type_) if is_attr_class(type_):", "if attr is None or isinstance(obj, Node): return False return", "Optional, Tuple, Type, Union, get_type_hints, ) import yaml from .errors", "REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, KEY=key, FULL_KEY=full_key, VALUE=value, VALUE_TYPE=type_str(type(value), include_module_name=True), KEY_TYPE=f\"{type(key).__name__}\", ) if", "Any, resolve: bool = False, throw_on_resolution_failure: bool = True )", "Node): return value is None if resolve: value = value._maybe_dereference_node(", "Optional[str] child_node: Optional[Node] = None if node is None: full_key", "t in t.__args__] ) ret = f\"{name}[{args}]\" else: ret =", "`[` followed by anything then `]` (ex: [b], [c]) KEY_PATH_OTHER", "Optional[Type[Any]]) -> Any: args = getattr(ref_type, \"__args__\", None) if ref_type", "if isinstance(obj, Node): return obj._is_optional() else: # In case `obj`", "KEY_PATH_OTHER = re.compile(r\"\\.([^.[]*)|\\[(.*?)\\]\") # source: https://yaml.org/type/bool.html YAML_BOOL_TYPES = [ \"y\",", "duplicate key {key_node.value}\", key_node.start_mark, ) keys.add(key_node.value) return super().construct_mapping(node, deep=deep) loader", "= path.rpartition(\".\") mod = import_module(module_path) try: klass: type = getattr(mod,", "ignore def is_primitive_type(type_: Any) -> bool: type_ = get_type_of(type_) return", "Optional[Type[Any]]: from omegaconf import Container, Node if isinstance(obj, Container): if", "omegaconf import Container, Node if isinstance(obj, Container): if key is", "if full_backtrace: ex.__cause__ = cause else: ex.__cause__ = None raise", "with a bracket ([b], [c]). # Only one group can", "if is_dict_annotation(type_): kt, vt = get_dict_key_value_types(type_) if kt is not", "None ) -> Dict[str, Any]: from omegaconf.omegaconf import MISSING, OmegaConf,", "presence of \"${\" in the string. # Note that escaped", "def _valid_dict_key_annotation_type(type_: Any) -> bool: from omegaconf import DictKeyType return", "1 INTERPOLATION = 2 def _is_missing_value(value: Any) -> bool: from", "= getattr(mod, class_name) except AttributeError: raise ImportError(f\"Class {class_name} is not", "return Optional[ref_type] # type: ignore else: return ref_type else: return", "end OC_CAUSE=1 for full backtrace def format_and_raise( node: Any, key:", "Keep in mind that invalid interpolations will only be detected", "object_type_str: Optional[str] = None ref_type: Optional[Type[Any]] ref_type_str: Optional[str] child_node: Optional[Node]", "is Any or is_primitive_type(type_) or is_structured_config(type_) def _valid_dict_key_annotation_type(type_: Any) ->", "return True, Any return False, type_ def _is_optional(obj: Any, key:", "obj is a container\") if isinstance(obj, Node): ref_type = obj._metadata.ref_type", "get_omega_conf_dumper() -> Type[OmegaConfDumper]: if not OmegaConfDumper.str_representer_added: OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer) OmegaConfDumper.str_representer_added =", "In case `obj` is not a Node, treat it as", "-> str: return self.desc # To be used as default", "0: args = getattr(bases[0], \"__args__\", None) key_type: Any element_type: Any", "the given node is optional.\"\"\" from .base import Container, Node", "tuple)) def is_primitive_dict(obj: Any) -> bool: t = get_type_of(obj) return", "= OmegaConfLoader loader.add_implicit_resolver( \"tag:yaml.org,2002:float\", re.compile( \"\"\"^(?: [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]*", "\"FALSE\", \"on\", \"On\", \"ON\", \"off\", \"Off\", \"OFF\", ] class Marker:", "is None or isinstance(obj, Node): return False return dataclasses.is_dataclass(obj) def", "= get_type_of(type_) return issubclass(type_, Enum) or type_ in (int, float,", "OmegaConfLoader(yaml.SafeLoader): # type: ignore def construct_mapping(self, node: yaml.Node, deep: bool", "if _is_union(type_): e = ConfigValueError( f\"Union types are not supported:\\n{name}:", "else type(obj) dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type for", "-> bool: return is_primitive_list(obj) or is_primitive_dict(obj) def get_list_element_type(ref_type: Optional[Type[Any]]) ->", "get_dict_key_value_types(type_) if kt is not None: kt = _resolve_forward(kt, module=module)", "str) -> bool: st = str.lower(st) return st == \"true\"", "else: return ValueKind.VALUE # DEPRECATED: remove in 2.2 def is_bool(st:", "= Any else: if args is not None: key_type =", "node=None, key=name, value=value, cause=ex, msg=str(ex) ) return dict_subclass_data else: return", "an official API in attr that can detect that. #", "Any: args = getattr(ref_type, \"__args__\", None) if ref_type is not", "= None) -> Dict[str, Any]: from omegaconf.omegaconf import OmegaConf, _maybe_wrap", "return get_dataclass_field_names(obj) elif is_attr_class(obj): return get_attr_class_field_names(obj) else: raise ValueError(f\"Unsupported type:", "the kind of a value Examples: VALUE: \"10\", \"20\", True", "be dropped. typed_dict = hasattr(type_, \"__base__\") and type_.__base__ == dict", "= _resolve_forward(type_, obj.__module__) try: dict_subclass_data[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name,", "an option. _DEFAULT_MARKER_: Any = Marker(\"_DEFAULT_MARKER_\") class OmegaConfDumper(yaml.Dumper): # type:", "_is_missing_value(value: Any) -> bool: from omegaconf import Node if isinstance(value,", "with brackets, e.g. # [a] or ..[a]. In that case", "return value is None if resolve: value = value._maybe_dereference_node( throw_on_resolution_failure=throw_on_resolution_failure", "Any, flags: Optional[Dict[str, bool]] = None) -> Any: from omegaconf", ".nodes import ValueNode if isinstance(value, ValueNode): return value._value() elif isinstance(value,", "in module {module_path}\") return klass def _is_union(type_: Any) -> bool:", "= None raise ex.with_traceback(sys.exc_info()[2]) # set end OC_CAUSE=1 for full", "d.update(dict_subclass_data) return d def is_dataclass(obj: Any) -> bool: from omegaconf.base", "forward = typing.ForwardRef if hasattr(typing, \"ForwardRef\") else typing._ForwardRef # type:", "if t is None: return type(t).__name__ if t is Any:", "match key paths like: a.b, a[b], ..a[c].d, etc. # We", "return boxed # return primitives and regular OmegaConf Containers as", "Any]: args = getattr(ref_type, \"__args__\", None) if args is None:", ") if ref_type not in (None, Any): template = dedent(", "getattr(t, \"__args__\", None) if args is not None: args =", "case where the first key starts with brackets, e.g. #", "it as optional by default. # This is used in", "include_module_name: if ( hasattr(t, \"__module__\") and t.__module__ != \"builtins\" and", "import attr except ImportError: # pragma: no cover attr =", "Any element_type = Any return key_type, element_type def valid_value_annotation_type(type_: Any)", "Any element_type = Any else: if args is not None:", "None) -> Optional[Type[Any]]: from omegaconf import Container, Node if isinstance(obj,", "type_override(str(cause)) ex.__dict__ = copy.deepcopy(cause.__dict__) _raise(ex, cause) object_type: Optional[Type[Any]] object_type_str: Optional[str]", "dict, for example: list returns False typing.List returns False typing.List[T]", "raise ex.with_traceback(sys.exc_info()[2]) # set end OC_CAUSE=1 for full backtrace def", "Node if key is not None: assert isinstance(obj, Container) obj", "in value: if strict_interpolation_validation: # First try the cheap regex", "t is ...: return \"...\" if sys.version_info < (3, 7,", "args = getattr(ref_type, \"__args__\", None) if args is None: bases", ") keys.add(key_node.value) return super().construct_mapping(node, deep=deep) loader = OmegaConfLoader loader.add_implicit_resolver( \"tag:yaml.org,2002:float\",", "decode_primitive(s: str) -> Any: if is_bool(s): return str.lower(s) == \"true\"", "for some T.\"\"\" if getattr(type_, \"__origin__\", None) is Union: args", "OmegaConf.structured(target, flags=flags) elif not OmegaConf.is_config(target): raise ValueError( \"Invalid input. Supports", "and will instead be handled in the next regex below", "if is_dataclass(obj): return get_dataclass_field_names(obj) elif is_attr_class(obj): return get_attr_class_field_names(obj) else: raise", "supported:\\n{name}: {type_str(type_)}\" ) format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e)) try: d[name]", "isinstance(type_, type) and issubclass(type_, Dict) def is_dict(obj: Any) -> bool:", "obj.__module__) if not is_type: value = getattr(obj, name) else: value", "Dict: key_type = Any element_type = Any else: if args", "target def is_generic_list(type_: Any) -> bool: \"\"\" Checks if a", "# pragma: no cover def is_dict_subclass(type_: Any) -> bool: return", "# type: ignore str_representer_added = False @staticmethod def str_representer(dumper: yaml.Dumper,", "key_type, element_type def valid_value_annotation_type(type_: Any) -> bool: return type_ is", "Any]: from omegaconf.omegaconf import OmegaConf, _maybe_wrap flags = {\"allow_objects\": allow_objects}", "True MANDATORY_MISSING: \"???\" INTERPOLATION: \"${foo.bar}\", \"${foo.${bar}}\", \"${foo:bar}\", \"[${foo}, ${bar}]\", \"ftp://${host}/path\",", "(list, dict)) target = OmegaConf.create(target, flags=flags) elif is_structured_config(target): target =", "name = type_str(t.__origin__) else: name = str(t) if name.startswith(\"typing.\"): name", "# return primitives and regular OmegaConf Containers as is return", "Node if isinstance(obj, Container): if key is not None: obj", "full_backtrace: ex.__cause__ = cause else: ex.__cause__ = None raise ex.with_traceback(sys.exc_info()[2])", "Any, allow_objects: Optional[bool] = None) -> Dict[str, Any]: from omegaconf.omegaconf", "OmegaConf from omegaconf.base import Node if isinstance(cause, AssertionError): raise if", ") except ValidationError as ex: format_and_raise( node=None, key=name, value=value, cause=ex,", "if _is_missing_value(value): return ValueKind.MANDATORY_MISSING value = _get_value(value) # We identify", "s.substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key ) exception_type = type(cause) if", "if is_type else type(obj) subclasses_dict = is_dict_subclass(obj_type) if subclasses_dict: warnings.warn(", "return _is_missing_literal(value) def _is_missing_literal(value: Any) -> bool: # Uses literal", "key paths like: a.b, a[b], ..a[c].d, etc. # We begin", "KEY_PATH_HEAD = re.compile(r\"(\\.)*[^.[]*\") # Then we match other keys. The", "are done. if first_stop == len(key): return tokens if key[first_stop]", "origin is Tuple or type_ is Tuple # pragma: no", "flags=flags) dummy_parent._metadata.object_type = obj_type resolved_hints = get_type_hints(obj_type) for field in", "OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type resolved_hints = get_type_hints(obj_type) for field", "or _is_missing_literal(boxed) or _is_interpolation(boxed): return boxed # return primitives and", "\", \".join( [type_str(t, include_module_name=include_module_name) for t in t.__args__] ) ret", "== \"1\") if full_backtrace: ex.__cause__ = cause else: ex.__cause__ =", "yaml_is_bool(data) or is_int(data) or is_float(data) return dumper.represent_scalar( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, data, style=(\"'\"", "): module_prefix = t.__module__ + \".\" else: module_prefix = \"\"", "# lgtm [py/import-and-import-from] forward = typing.ForwardRef if hasattr(typing, \"ForwardRef\") else", "Then we match other keys. The following expression matches one", "-> tokens = [\"\"] but we would like [] #", "by anything then `]` (ex: [b], [c]) KEY_PATH_OTHER = re.compile(r\"\\.([^.[]*)|\\[(.*?)\\]\")", "< (3, 7, 0): return origin is Dict or type_", "ex.with_traceback(sys.exc_info()[2]) # set end OC_CAUSE=1 for full backtrace def format_and_raise(", "elif exception_type == IndexError: exception_type = ConfigIndexError ex = exception_type(f\"{message}\")", "is forward: return _get_class(f\"{module}.{type_.__forward_arg__}\") else: if is_dict_annotation(type_): kt, vt =", "getattr(type_, \"__origin__\", None) is Union: args = type_.__args__ if len(args)", "`.` or `[` (ex: .b, .d) # - `[` followed", "list(attr.fields_dict(obj_type)) def get_attr_data(obj: Any, allow_objects: Optional[bool] = None) -> Dict[str,", "return element_type def get_dict_key_value_types(ref_type: Any) -> Tuple[Any, Any]: args =", "= re.compile(r\"\\.([^.[]*)|\\[(.*?)\\]\") # source: https://yaml.org/type/bool.html YAML_BOOL_TYPES = [ \"y\", \"Y\",", "Type[Any], module: str) -> Type[Any]: import typing # lgtm [py/import-and-import-from]", "== \"false\" def is_float(st: str) -> bool: try: float(st) return", "a, ..a). # This can be read as \"dots followed", "type: ignore if type(type_) is forward: return _get_class(f\"{module}.{type_.__forward_arg__}\") else: if", "\"esc: \\${bar}\") are identified as # interpolations: this is intended,", "# Identify other key elements (in docstring examples: b, b,", "list, for example: list returns False typing.List returns False typing.List[T]", "_resolve_forward(type_, obj.__module__) try: dict_subclass_data[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value,", "not env_var == \"0\") or (env_var == \"1\") if full_backtrace:", "Any) -> bool: type_ = get_type_of(type_) return issubclass(type_, Enum) or", "return OmegaConfDumper def yaml_is_bool(b: str) -> bool: return b in", "dataclasses.fields(obj)] def get_dataclass_data( obj: Any, allow_objects: Optional[bool] = None )", "_raise(ex: Exception, cause: Exception) -> None: # Set the environment", "from textwrap import dedent from typing import ( Any, Dict,", "None) is Union def _resolve_optional(type_: Any) -> Tuple[bool, Any]: \"\"\"Check", "else None), ) def get_omega_conf_dumper() -> Type[OmegaConfDumper]: if not OmegaConfDumper.str_representer_added:", "origin = getattr(type_, \"__origin__\", None) if sys.version_info < (3, 7,", "\"\"\" Determine the kind of a value Examples: VALUE: \"10\",", "None or isinstance(obj, Node): return False return attr.has(obj) def is_structured_config(obj:", "is_structured_config(obj: Any) -> bool: return is_attr_class(obj) or is_dataclass(obj) def is_dataclass_frozen(type_:", "def type_str(t: Any, include_module_name: bool = False) -> str: is_optional,", "True return OmegaConfDumper def yaml_is_bool(b: str) -> bool: return b", "for dot_key, bracket_key in others] return tokens # Similar to", "`None` is not an option. _DEFAULT_MARKER_: Any = Marker(\"_DEFAULT_MARKER_\") class", "= get_dict_key_value_types(type_) if kt is not None: kt = _resolve_forward(kt,", "from omegaconf.base import Node if dataclasses is None or isinstance(obj,", "# pragma: no cover # type_dict is a bit hard", "is not a Node, treat it as optional by default.", "kt = _resolve_forward(kt, module=module) if vt is not None: vt", "return dumper.represent_scalar( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, data, style=(\"'\" if with_quotes else None), )", "ConfigValueError( f\"Union types are not supported:\\n{name}: {type_str(type_)}\" ) format_and_raise(node=None, key=None,", "one here would # be misleading. Instead, we display it", ".b, .d) # - `[` followed by anything then `]`", "None def get_attr_class_field_names(obj: Any) -> List[str]: is_type = isinstance(obj, type)", "tokens.pop() # Identify other key elements (in docstring examples: b,", "variable type :return: bool \"\"\" return is_list_annotation(type_) and get_list_element_type(type_) is", "-> [\"a\", \"b\"] \"\"\" # Obtain the first part of", "parent=parent, ) except ValidationError as ex: format_and_raise( node=None, key=name, value=value,", ") import yaml from .errors import ( ConfigIndexError, ConfigTypeError, ConfigValueError,", "be properly un-escaped. # Keep in mind that invalid interpolations", "Any, include_module_name: bool = False) -> str: is_optional, t =", "def get_value_kind( value: Any, strict_interpolation_validation: bool = False ) ->", "simple). KEY_PATH_HEAD = re.compile(r\"(\\.)*[^.[]*\") # Then we match other keys.", "returns True :param type_: variable type :return: bool \"\"\" return", "if is_bool(s): return str.lower(s) == \"true\" if is_int(s): return int(s)", "that includes the # causing exception. env_var = os.environ[\"OC_CAUSE\"] if", "is to keep this regex simple). KEY_PATH_HEAD = re.compile(r\"(\\.)*[^.[]*\") #", "deep: bool = False) -> Any: keys = set() for", "matching the head (in these examples: a, a, ..a). #", "stacktrace that includes the # causing exception. env_var = os.environ[\"OC_CAUSE\"]", "`Dict` in Structured Config classes is deprecated,\" + \" see", "msg: str, cause: Exception, type_override: Any = None, ) ->", "type: from importlib import import_module module_path, _, class_name = path.rpartition(\".\")", "get_type_of(obj) if is_dataclass(type_): return is_dataclass_frozen(type_) if is_attr_class(type_): return is_attr_frozen(type_) return", "origin is tuple # pragma: no cover def is_dict_subclass(type_: Any)", "None def is_generic_dict(type_: Any) -> bool: \"\"\" Checks if a", "else: return None def get_attr_class_field_names(obj: Any) -> List[str]: is_type =", "None: # Resolution failure: consider that it is *not* None.", "re.compile(r\"\\.([^.[]*)|\\[(.*?)\\]\") # source: https://yaml.org/type/bool.html YAML_BOOL_TYPES = [ \"y\", \"Y\", \"yes\",", "{type(obj).__name__}\") def get_structured_config_data( obj: Any, allow_objects: Optional[bool] = None )", "bases = getattr(ref_type, \"__orig_bases__\", None) if bases is not None", "in resolvers if tag != \"tag:yaml.org,2002:timestamp\" ] for key, resolvers", "not detect errors. \"\"\" if _is_missing_value(value): return ValueKind.MANDATORY_MISSING value =", "dataclasses.fields(obj): name = field.name is_optional, type_ = _resolve_optional(resolved_hints[field.name]) type_ =", "None: # If no match, do the more expensive grammar", "Tuple[Any, Any]: args = getattr(ref_type, \"__args__\", None) if args is", "= string.Template(template=template) message = s.substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key )", "is None: bases = getattr(ref_type, \"__orig_bases__\", None) if bases is", "len(args) == 2 and args[1] == type(None): # noqa E721", "ignore # pragma: no cover # Regexprs to match key", "0 def is_container_annotation(type_: Any) -> bool: return is_list_annotation(type_) or is_dict_annotation(type_)", "# type: ignore def get_type_of(class_or_object: Any) -> Type[Any]: type_ =", "= key[0:first_stop].split(\".\") # Optimization in case `key` has no other", "( ConfigIndexError, ConfigTypeError, ConfigValueError, GrammarParseError, OmegaConfBaseException, ValidationError, ) from .grammar_parser", "\"__args__\", None) if ref_type is not List and args is", "elements composing the key. tokens = key[0:first_stop].split(\".\") # Optimization in", "allow_objects is not None else {} from omegaconf import MISSING", "import copy import os import re import string import sys", "type_.__dataclass_params__.frozen # type: ignore def is_attr_frozen(type_: type) -> bool: #", "= t.__module__ + \".\" else: module_prefix = \"\" ret =", "the MISSING const for performance reasons. return isinstance(value, str) and", "t.__origin__ is not None: name = type_str(t.__origin__) else: name =", "assert isinstance(value, Node) return value._is_none() def get_value_kind( value: Any, strict_interpolation_validation:", "by anything except `.` or `[` (ex: .b, .d) #", "\"__origin__\", None) if sys.version_info < (3, 7, 0): return origin", "is_optional, type_ = _resolve_optional(element_type) type_ = _resolve_forward(type_, obj.__module__) try: dict_subclass_data[name]", "Resolution failure: consider that it is *not* None. return False", "remove in 2.2 def decode_primitive(s: str) -> Any: if is_bool(s):", "are not supported:\\n{name}: {type_str(type_)}\" ) format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e))", "cause._initialized: ex = cause if type_override is not None: ex", "name, value in obj.items(): is_optional, type_ = _resolve_optional(element_type) type_ =", "import re import string import sys import warnings from contextlib", "= get_type_of(obj) return t is dict def is_dict_annotation(type_: Any) ->", "value = value._maybe_dereference_node( throw_on_resolution_failure=throw_on_resolution_failure ) if not throw_on_resolution_failure and value", "d[name]._set_parent(None) dict_subclass_data = extract_dict_subclass_data(obj=obj, parent=dummy_parent) if dict_subclass_data is not None:", "type :return: bool \"\"\" return is_list_annotation(type_) and get_list_element_type(type_) is not", "yaml.Dumper, data: str) -> yaml.ScalarNode: with_quotes = yaml_is_bool(data) or is_int(data)", "{\"allow_objects\": allow_objects} if allow_objects is not None else {} d", "None else type_override if exception_type == TypeError: exception_type = ConfigTypeError", "interpolations: this is intended, since they must be processed as", "and can # be read as a choice between two", "GrammarParseError, OmegaConfBaseException, ValidationError, ) from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse try:", "Dict, Iterator, List, Optional, Tuple, Type, Union, get_type_hints, ) import", "set end OC_CAUSE=1 for full backtrace def format_and_raise( node: Any,", "template = dedent( \"\"\"\\ $MSG full_key: $FULL_KEY reference_type=$REF_TYPE object_type=$OBJECT_TYPE\"\"\" )", "grammar parsing to detect errors. parse(value) return ValueKind.INTERPOLATION else: return", "key. full_key = f\"<unresolvable due to {type(exc).__name__}: {exc}>\" object_type =", "value._value() return _is_missing_literal(value) def _is_missing_literal(value: Any) -> bool: # Uses", "if isinstance(obj, Container): if key is not None: obj =", "args is not None: args = \", \".join( [type_str(t, include_module_name=include_module_name)", "typing.List returns False typing.List[T] returns True :param type_: variable type", "object_type=$OBJECT_TYPE\"\"\" ) else: template = dedent( \"\"\"\\ $MSG full_key: $FULL_KEY", "not None and not node._is_none(): child_node = node._get_node(key, validate_access=False) try:", "return issubclass(type_, Enum) or type_ in (int, float, bool, str,", "due to {type(exc).__name__}: {exc}>\" object_type = OmegaConf.get_type(node) object_type_str = type_str(object_type)", "Node) return value._is_none() def get_value_kind( value: Any, strict_interpolation_validation: bool =", "= sys.gettrace() is not None full_backtrace = (debugging and not", "return is_primitive_dict(obj) or is_dict_annotation(obj) or is_dict_subclass(obj) def is_primitive_container(obj: Any) ->", "= str(t.__name__) else: if t._name is None: if t.__origin__ is", "= getattr(ref_type, \"__args__\", None) if ref_type is not List and", "[dot_key if dot_key else bracket_key for dot_key, bracket_key in others]", "must be processed as interpolations # for the string to", "flags=flags) elif not OmegaConf.is_config(target): raise ValueError( \"Invalid input. Supports one", "!= yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG: continue if key_node.value in keys: raise yaml.constructor.ConstructorError( \"while", "class_name) except AttributeError: raise ImportError(f\"Class {class_name} is not in module", "`obj` is not a Node, treat it as optional by", "= module_prefix + ret if is_optional: return f\"Optional[{ret}]\" else: return", "value=value, parent=dummy_parent, ) except (ValidationError, GrammarParseError) as ex: format_and_raise( node=dummy_parent,", "ImportError: # pragma: no cover attr = None # type:", "key if key is not None else \"\" object_type =", "is not None and not node._is_none(): child_node = node._get_node(key, validate_access=False)", "instance]\" ) return target def is_generic_list(type_: Any) -> bool: \"\"\"", "is not None def is_generic_dict(type_: Any) -> bool: \"\"\" Checks", "type_ is Dict # pragma: no cover else: # pragma:", "OmegaConfBaseException, ValidationError, ) from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse try: import", "Any, key: Any, value: Any, msg: str, cause: Exception, type_override:", "name = field.name is_optional, type_ = _resolve_optional(resolved_hints[field.name]) type_ = _resolve_forward(type_,", "Any: return Optional[ref_type] # type: ignore else: return ref_type else:", "element_type = args[1] else: key_type = Any element_type = Any", "str: return self.desc # To be used as default value", "Any, strict_interpolation_validation: bool = False ) -> ValueKind: \"\"\" Determine", "type_ def extract_dict_subclass_data(obj: Any, parent: Any) -> Optional[Dict[str, Any]]: \"\"\"Check", "from omegaconf import Node if isinstance(value, Node): value = value._value()", "= Any element_type = Any return key_type, element_type def valid_value_annotation_type(type_:", "allow_objects: Optional[bool] = None ) -> Dict[str, Any]: from omegaconf.omegaconf", "regexp) for tag, regexp in resolvers if tag != \"tag:yaml.org,2002:timestamp\"", "# DEPRECATED: remove in 2.2 def decode_primitive(s: str) -> Any:", "isinstance(v, str): ret = ( get_value_kind(v, strict_interpolation_validation) == ValueKind.INTERPOLATION )", "for key_node, value_node in node.value: if key_node.tag != yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG: continue", "child_node ex.key = key ex.full_key = full_key ex.value = value", "None: # Set the environment variable OC_CAUSE=1 to get a", "str_representer_added = False @staticmethod def str_representer(dumper: yaml.Dumper, data: str) ->", "key_type, element_type = get_dict_key_value_types(obj_type) for name, value in obj.items(): is_optional,", "mod = import_module(module_path) try: klass: type = getattr(mod, class_name) except", "but we would like [\"\", \"\"] tokens.pop() # Identify other", "assert first is not None first_stop = first.span()[1] # `tokens`", "is_dict_annotation(type_: Any) -> bool: origin = getattr(type_, \"__origin__\", None) if", "hasattr(type_, \"__base__\") and type_.__base__ == dict return origin is dict", "= type(cause) if type_override is None else type_override if exception_type", "for name, value in obj.items(): is_optional, type_ = _resolve_optional(element_type) type_", "List[str]: if is_dataclass(obj): return get_dataclass_field_names(obj) elif is_attr_class(obj): return get_attr_class_field_names(obj) else:", "None ref_type: Optional[Type[Any]] ref_type_str: Optional[str] child_node: Optional[Node] = None if", ".a, '') first = KEY_PATH_HEAD.match(key) assert first is not None", "extract the Dict keys/values.\"\"\" from omegaconf.omegaconf import _maybe_wrap is_type =", "of a value Examples: VALUE: \"10\", \"20\", True MANDATORY_MISSING: \"???\"", "is List # pragma: no cover else: return origin is", "value == attr.NOTHING: value = MISSING if _is_union(type_): e =", "return s def is_primitive_list(obj: Any) -> bool: from .base import", "(3, 7, 0): return origin is List or type_ is", "reasons. return isinstance(value, str) and value == \"???\" def _is_none(", "float, bool, str, type(None)) def _is_interpolation(v: Any, strict_interpolation_validation: bool =", "= value._value() return _is_missing_literal(value) def _is_missing_literal(value: Any) -> bool: #", "value._value() elif isinstance(value, Container): boxed = value._value() if boxed is", "bool: from omegaconf import Node if isinstance(value, Node): value =", "return False return attr.has(obj) def is_structured_config(obj: Any) -> bool: return", "else {} from omegaconf import MISSING d = {} is_type", "def is_attr_class(obj: Any) -> bool: from omegaconf.base import Node if", "0): # pragma: no cover # Python 3.6 if hasattr(t,", "If `False`, this parsing step is skipped: this is more", "yaml.ScalarNode: with_quotes = yaml_is_bool(data) or is_int(data) or is_float(data) return dumper.represent_scalar(", "d def is_dataclass(obj: Any) -> bool: from omegaconf.base import Node", "# - `[` followed by anything then `]` (ex: [b],", "get_structured_config_data( obj: Any, allow_objects: Optional[bool] = None ) -> Dict[str,", "value._is_none() def get_value_kind( value: Any, strict_interpolation_validation: bool = False )", "if kt is not None: kt = _resolve_forward(kt, module=module) if", "bool: from omegaconf import DictKeyType return type_ is None or", "if dict_subclass_data is not None: d.update(dict_subclass_data) return d def get_dataclass_field_names(obj:", "d def get_dataclass_field_names(obj: Any) -> List[str]: return [field.name for field", ".d) # - `[` followed by anything then `]` (ex:", "KEY=key, FULL_KEY=full_key, VALUE=value, VALUE_TYPE=type_str(type(value), include_module_name=True), KEY_TYPE=f\"{type(key).__name__}\", ) if ref_type not", "\"yes\", \"Yes\", \"YES\", \"n\", \"N\", \"no\", \"No\", \"NO\", \"true\", \"True\",", "elif subclasses_dict: dict_subclass_data = {} key_type, element_type = get_dict_key_value_types(obj_type) for", "is Tuple # pragma: no cover else: return origin is", "bool \"\"\" return is_dict_annotation(type_) and len(get_dict_key_value_types(type_)) > 0 def is_container_annotation(type_:", "mapping\", node.start_mark, f\"found duplicate key {key_node.value}\", key_node.start_mark, ) keys.add(key_node.value) return", "starting with a bracket ([b], [c]). # Only one group", "is not None: assert isinstance(obj, Container) obj = obj._get_node(key) if", "type is a generic list, for example: list returns False", "strict_interpolation_validation: bool = False ) -> ValueKind: \"\"\" Determine the", "if t is ...: return \"...\" if sys.version_info < (3,", "False, throw_on_resolution_failure: bool = True ) -> bool: from omegaconf", "Any) -> bool: return is_list_annotation(type_) or is_dict_annotation(type_) def split_key(key: str)", "re.compile( \"\"\"^(?: [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]* |[-+]?\\\\.(?:inf|Inf|INF) |\\\\.(?:nan|NaN|NAN))$\"\"\", re.X, ),", "flags=flags) dummy_parent._metadata.object_type = obj_type for name, attrib in attr.fields_dict(obj_type).items(): is_optional,", "[ \"y\", \"Y\", \"yes\", \"Yes\", \"YES\", \"n\", \"N\", \"no\", \"No\",", "type: ignore value = MISSING else: value = field.default_factory() #", "works with the getitem syntax: \"a.b\" -> [\"a\", \"b\"] \"a[b]\"", "ImportError: # pragma: no cover dataclasses = None # type:", "be used instead, # once support for Python 3.6 is", "== \"0\") or (env_var == \"1\") if full_backtrace: ex.__cause__ =", "OmegaConf.is_config(target): raise ValueError( \"Invalid input. Supports one of \" +", "return origin is Tuple or type_ is Tuple # pragma:", "not None and args[0]: element_type = args[0] else: element_type =", "and t.__module__ != \"typing\" and not t.__module__.startswith(\"omegaconf.\") ): module_prefix =", "and \"${\" in value: if strict_interpolation_validation: # First try the", "\"20\", True MANDATORY_MISSING: \"???\" INTERPOLATION: \"${foo.bar}\", \"${foo.${bar}}\", \"${foo:bar}\", \"[${foo}, ${bar}]\",", "..[a] -> tokens = [\"\", \"\", \"\"] but we would", "[a] or ..[a]. In that case there is an extra", "of: # [a] -> tokens = [\"\"] but we would", "0): return origin is List or type_ is List #", "below (this # is to keep this regex simple). KEY_PATH_HEAD", "Any return False, type_ def _is_optional(obj: Any, key: Optional[Union[int, str]]", "t.__origin__, include_module_name=include_module_name ) else: name = str(t._name) args = getattr(t,", "def str_representer(dumper: yaml.Dumper, data: str) -> yaml.ScalarNode: with_quotes = yaml_is_bool(data)", "consider that it is *not* None. return False assert isinstance(value,", "examples: a, a, ..a). # This can be read as", "that it is *not* None. return False assert isinstance(value, Node)", "return is_list_annotation(type_) and get_list_element_type(type_) is not None def is_generic_dict(type_: Any)", "but we would like [] # ..[a] -> tokens =", "7, 0): # pragma: no cover # Python 3.6 if", "target = OmegaConf.structured(target, flags=flags) elif not OmegaConf.is_config(target): raise ValueError( \"Invalid", "7, 0): return origin is Tuple or type_ is Tuple", "origin is list # pragma: no cover def is_tuple_annotation(type_: Any)", "bool: type_ = get_type_of(type_) return issubclass(type_, Enum) or type_ in", "from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap flags = {\"allow_objects\": allow_objects}", "`{obj_type.__name__}` subclasses `Dict`.\" + \" Subclassing `Dict` in Structured Config", "type_str(t.__origin__) else: name = str(t) if name.startswith(\"typing.\"): name = name[len(\"typing.\")", "omegaconf import OmegaConf if is_primitive_container(target): assert isinstance(target, (list, dict)) target", "strict_interpolation_validation: If `True`, then when `value` is a string containing", "if exception_type == TypeError: exception_type = ConfigTypeError elif exception_type ==", "in `tokens` that we # need to get rid of:", "extract_dict_subclass_data(obj: Any, parent: Any) -> Optional[Dict[str, Any]]: \"\"\"Check if obj", "type_ def _is_optional(obj: Any, key: Optional[Union[int, str]] = None) ->", "Optional[Union[int, str]] = None) -> bool: \"\"\"Check `obj` metadata to", "Type, Union, get_type_hints, ) import yaml from .errors import (", ") return target def is_generic_list(type_: Any) -> bool: \"\"\" Checks", "failure: consider that it is *not* None. return False assert", "keys: raise yaml.constructor.ConstructorError( \"while constructing a mapping\", node.start_mark, f\"found duplicate", "_get_value(value) # We identify potential interpolations by the presence of", "return ValueKind.INTERPOLATION else: return ValueKind.VALUE # DEPRECATED: remove in 2.2", "-> bool: from omegaconf import Node if not isinstance(value, Node):", "`Dict`.\" + \" Subclassing `Dict` in Structured Config classes is", "in others] return tokens # Similar to Python 3.7+'s `contextlib.nullcontext`", "extract_dict_subclass_data(obj=obj, parent=dummy_parent) if dict_subclass_data is not None: d.update(dict_subclass_data) return d", "that invalid interpolations will only be detected when # `strict_interpolation_validation`", "= MISSING if _is_union(type_): e = ConfigValueError( f\"Union types are", "_resolve_optional(t) if t is None: return type(t).__name__ if t is", "Any]]: \"\"\"Check if obj is an instance of a subclass", "def format_and_raise( node: Any, key: Any, value: Any, msg: str,", "ex: format_and_raise( node=dummy_parent, key=name, value=value, cause=ex, msg=str(ex) ) d[name]._set_parent(None) dict_subclass_data", "import_module(module_path) try: klass: type = getattr(mod, class_name) except AttributeError: raise", "False # DEPRECATED: remove in 2.2 def decode_primitive(s: str) ->", "ex = exception_type(f\"{message}\") if issubclass(exception_type, OmegaConfBaseException): ex._initialized = True ex.msg", "t._name is None: if t.__origin__ is not None: name =", "is *not* None. return False assert isinstance(value, Node) return value._is_none()", "\"true\" if is_int(s): return int(s) if is_float(s): return float(s) return", "name.startswith(\"typing.\"): name = name[len(\"typing.\") :] else: # pragma: no cover", "given node is optional.\"\"\" from .base import Container, Node if", "node._is_none(): child_node = node._get_node(key, validate_access=False) try: full_key = node._get_full_key(key=key) except", "_is_missing_literal(value) def _is_missing_literal(value: Any) -> bool: # Uses literal '???'", "ex.__cause__ = cause else: ex.__cause__ = None raise ex.with_traceback(sys.exc_info()[2]) #", "with_quotes else None), ) def get_omega_conf_dumper() -> Type[OmegaConfDumper]: if not", "dataclasses is None or isinstance(obj, Node): return False return dataclasses.is_dataclass(obj)", "= get_ref_type(node) ref_type_str = type_str(ref_type) msg = string.Template(msg).safe_substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str,", "type = getattr(mod, class_name) except AttributeError: raise ImportError(f\"Class {class_name} is", "is equivalent to `typing.Optional[T]` for some T.\"\"\" if getattr(type_, \"__origin__\",", "key_node.start_mark, ) keys.add(key_node.value) return super().construct_mapping(node, deep=deep) loader = OmegaConfLoader loader.add_implicit_resolver(", "bool: \"\"\"Check `obj` metadata to see if the given node", "is not None else {} from omegaconf import MISSING d", "be detected when # `strict_interpolation_validation` is True. if isinstance(value, str)", "sys.version_info < (3, 7, 0): return origin is Dict or", "literal '???' instead of the MISSING const for performance reasons.", "causes issues in other areas it may be dropped. typed_dict", "get a stacktrace that includes the # causing exception. env_var", "(env_var == \"1\") if full_backtrace: ex.__cause__ = cause else: ex.__cause__", "type(class_or_object) assert isinstance(type_, type) return type_ def is_structured_config_frozen(obj: Any) ->", "3.6 if hasattr(t, \"__name__\"): name = str(t.__name__) else: if t.__origin__", "args[1] else: key_type = Any element_type = Any return key_type,", "obj_type = obj if is_type else type(obj) subclasses_dict = is_dict_subclass(obj_type)", "is a generic dict, for example: list returns False typing.List", "Enum from textwrap import dedent from typing import ( Any,", "= ConfigTypeError elif exception_type == IndexError: exception_type = ConfigIndexError ex", "# where the appended/inserted value might or might not be", "is a generic list, for example: list returns False typing.List", "parsing to detect errors. parse(value) return ValueKind.INTERPOLATION else: return ValueKind.VALUE", "\"OFF\", ] class Marker: def __init__(self, desc: str): self.desc =", "list(\"-+0123456789.\"), ) loader.yaml_implicit_resolvers = { key: [ (tag, regexp) for", "backtrace def format_and_raise( node: Any, key: Any, value: Any, msg:", "Node): ref_type = obj._metadata.ref_type if obj._is_optional() and ref_type is not", "once support for Python 3.6 is dropped). @contextmanager def nullcontext(enter_result:", "regex matching that detects common interpolations. if SIMPLE_INTERPOLATION_PATTERN.match(value) is None:", "type_override is None else type_override if exception_type == TypeError: exception_type", "yaml.constructor.ConstructorError( \"while constructing a mapping\", node.start_mark, f\"found duplicate key {key_node.value}\",", "node.value: if key_node.tag != yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG: continue if key_node.value in keys:", "\"false\", \"False\", \"FALSE\", \"on\", \"On\", \"ON\", \"off\", \"Off\", \"OFF\", ]", "Any) -> bool: t = get_type_of(obj) return t is dict", "self.desc = desc def __repr__(self) -> str: return self.desc #", "# type: ignore else: return ref_type else: return Any #", "only be provided when obj is a container\") if isinstance(obj,", "and len(get_dict_key_value_types(type_)) > 0 def is_container_annotation(type_: Any) -> bool: return", "{type(obj).__name__}\") class ValueKind(Enum): VALUE = 0 MANDATORY_MISSING = 1 INTERPOLATION", "return is_attr_class(obj) or is_dataclass(obj) def is_dataclass_frozen(type_: Any) -> bool: return", "full_key ex.value = value ex.object_type = object_type ex.object_type_str = object_type_str", "type_override if exception_type == TypeError: exception_type = ConfigTypeError elif exception_type", "in node.value: if key_node.tag != yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG: continue if key_node.value in", "List or type_ is List # pragma: no cover else:", "dict)) target = OmegaConf.create(target, flags=flags) elif is_structured_config(target): target = OmegaConf.structured(target,", "import Enum from textwrap import dedent from typing import (", "Exception) -> None: # Set the environment variable OC_CAUSE=1 to", "if isinstance(cause, AssertionError): raise if isinstance(cause, OmegaConfBaseException) and cause._initialized: ex", "get_list_element_type(type_) is not None def is_generic_dict(type_: Any) -> bool: \"\"\"", "is_dataclass(obj): return get_dataclass_data(obj, allow_objects=allow_objects) elif is_attr_class(obj): return get_attr_data(obj, allow_objects=allow_objects) else:", "\"n\", \"N\", \"no\", \"No\", \"NO\", \"true\", \"True\", \"TRUE\", \"false\", \"False\",", "\"Y\", \"yes\", \"Yes\", \"YES\", \"n\", \"N\", \"no\", \"No\", \"NO\", \"true\",", "cover else: return origin is tuple # pragma: no cover", "handling an exception, raising a different one here would #", "def _get_class(path: str) -> type: from importlib import import_module module_path,", "f\"Optional[{ret}]\" else: return ret def _ensure_container(target: Any, flags: Optional[Dict[str, bool]]", "key ex.full_key = full_key ex.value = value ex.object_type = object_type", "appended/inserted value might or might not be a Node. return", ") def get_omega_conf_dumper() -> Type[OmegaConfDumper]: if not OmegaConfDumper.str_representer_added: OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer)", "key: Any, value: Any, msg: str, cause: Exception, type_override: Any", "is similar to `key.split(\".\")` but also works with the getitem", "= obj_type resolved_hints = get_type_hints(obj_type) for field in dataclasses.fields(obj): name", "in t.__args__] ) ret = f\"{name}[{args}]\" else: ret = name", "omegaconf import Node if isinstance(value, Node): value = value._value() return", "parse try: import dataclasses except ImportError: # pragma: no cover", "used as default value when `None` is not an option.", "here and will instead be handled in the next regex", "class ValueKind(Enum): VALUE = 0 MANDATORY_MISSING = 1 INTERPOLATION =", "issues in other areas it may be dropped. typed_dict =", "Any = None, ) -> None: from omegaconf import OmegaConf", "obj = obj._get_node(key) if isinstance(obj, Node): return obj._is_optional() else: #", "Container return not isinstance(obj, Container) and isinstance(obj, (list, tuple)) def", "that detects common interpolations. if SIMPLE_INTERPOLATION_PATTERN.match(value) is None: # If", "like [a], is purposedly *not* # matched here and will", "\"typing\" and not t.__module__.startswith(\"omegaconf.\") ): module_prefix = t.__module__ + \".\"", "value = getattr(obj, name) else: value = attrib.default if value", "= False ) -> ValueKind: \"\"\" Determine the kind of", "different one here would # be misleading. Instead, we display", "def _is_missing_value(value: Any) -> bool: from omegaconf import Node if", "Node. return True def _resolve_forward(type_: Type[Any], module: str) -> Type[Any]:", "else type_override if exception_type == TypeError: exception_type = ConfigTypeError elif", "ref_type else: return Any # type: ignore def _raise(ex: Exception,", "cover try: import attr except ImportError: # pragma: no cover", "from .nodes import ValueNode if isinstance(value, ValueNode): return value._value() elif", "else type(obj) return list(attr.fields_dict(obj_type)) def get_attr_data(obj: Any, allow_objects: Optional[bool] =", "typing.ForwardRef if hasattr(typing, \"ForwardRef\") else typing._ForwardRef # type: ignore if", "obj if is_type else type(obj) subclasses_dict = is_dict_subclass(obj_type) if subclasses_dict:", "environment variable OC_CAUSE=1 to get a stacktrace that includes the", "This can be read as \"dots followed by any character", "is an instance of a subclass of Dict. If so,", "Optional[Dict[str, Any]]: \"\"\"Check if obj is an instance of a", "'???' instead of the MISSING const for performance reasons. return", "if \"OC_CAUSE\" in os.environ else None debugging = sys.gettrace() is", "dumper.represent_scalar( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, data, style=(\"'\" if with_quotes else None), ) def", "bool: return is_attr_class(obj) or is_dataclass(obj) def is_dataclass_frozen(type_: Any) -> bool:", "to keep this regex simple). KEY_PATH_HEAD = re.compile(r\"(\\.)*[^.[]*\") # Then", "lgtm [py/import-and-import-from] forward = typing.ForwardRef if hasattr(typing, \"ForwardRef\") else typing._ForwardRef", "or is_primitive_type(type_) or is_structured_config(type_) def _valid_dict_key_annotation_type(type_: Any) -> bool: from", "a different one here would # be misleading. Instead, we", "or st == \"false\" def is_float(st: str) -> bool: try:", "ImportError(f\"Class {class_name} is not in module {module_path}\") return klass def", "OmegaConf.create(target, flags=flags) elif is_structured_config(target): target = OmegaConf.structured(target, flags=flags) elif not", "Regexprs to match key paths like: a.b, a[b], ..a[c].d, etc.", "= args[0] element_type = args[1] else: key_type = Any element_type", "as interpolations # for the string to be properly un-escaped.", "_maybe_wrap is_type = isinstance(obj, type) obj_type = obj if is_type", "try: full_key = node._get_full_key(key=key) except Exception as exc: # Since", "type) obj_type = obj if is_type else type(obj) subclasses_dict =", "is_dict_annotation(type_) and len(get_dict_key_value_types(type_)) > 0 def is_container_annotation(type_: Any) -> bool:", "${bar}]\", \"ftp://${host}/path\", \"${foo:${bar}, [true], {'baz': ${baz}}}\" :param value: Input to", "isinstance(obj, Node): return obj._is_optional() else: # In case `obj` is", "return True def _resolve_forward(type_: Type[Any], module: str) -> Type[Any]: import", "exception_type = type(cause) if type_override is None else type_override if", "Any) -> Any: from .base import Container from .nodes import", "-> bool: return is_attr_class(obj) or is_dataclass(obj) def is_dataclass_frozen(type_: Any) ->", "args = getattr(bases[0], \"__args__\", None) key_type: Any element_type: Any if", "the key (in docstring examples: a, a, .a, '') first", "Exception, type_override: Any = None, ) -> None: from omegaconf", "as # interpolations: this is intended, since they must be", "= obj if is_type else type(obj) dummy_parent = OmegaConf.create({}, flags=flags)", "if resolve: value = value._maybe_dereference_node( throw_on_resolution_failure=throw_on_resolution_failure ) if not throw_on_resolution_failure", "\"while constructing a mapping\", node.start_mark, f\"found duplicate key {key_node.value}\", key_node.start_mark,", "get_list_element_type(ref_type: Optional[Type[Any]]) -> Any: args = getattr(ref_type, \"__args__\", None) if", "SIMPLE_INTERPOLATION_PATTERN, parse try: import dataclasses except ImportError: # pragma: no", "pragma: no cover else: # pragma: no cover # type_dict", "\"\"\" Checks if a type is a generic list, for", "or type_ is Tuple # pragma: no cover else: return", "= cause if type_override is not None: ex = type_override(str(cause))", "# pragma: no cover try: import attr except ImportError: #", "# Unfortunately currently there isn't an official API in attr", "dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type resolved_hints = get_type_hints(obj_type)", "name): value = getattr(obj, name) if value == dataclasses.MISSING: value", "type_.__setattr__ == attr._make._frozen_setattrs # type: ignore def get_type_of(class_or_object: Any) ->", "since they must be processed as interpolations # for the", "get_type_of(obj) dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type resolved_hints =", "Any) -> List[str]: return [field.name for field in dataclasses.fields(obj)] def", "and args[0]: element_type = args[0] else: element_type = Any return", "None: name = type_str(t.__origin__) else: name = str(t) if name.startswith(\"typing.\"):", "classify. :param strict_interpolation_validation: If `True`, then when `value` is a", "import ( Any, Dict, Iterator, List, Optional, Tuple, Type, Union,", "an instance of a subclass of Dict. If so, extract", "-> Dict[str, Any]: from omegaconf.omegaconf import OmegaConf, _maybe_wrap flags =", "type(t).__name__ if t is Any: return \"Any\" if t is", "= type_str(t.__origin__) else: name = str(t) if name.startswith(\"typing.\"): name =", "def is_dataclass_frozen(type_: Any) -> bool: return type_.__dataclass_params__.frozen # type: ignore", "if type_override is not None: ex = type_override(str(cause)) ex.__dict__ =", "Any return element_type def get_dict_key_value_types(ref_type: Any) -> Tuple[Any, Any]: args", "if args is not None: key_type = args[0] element_type =", "key is not None: assert isinstance(obj, Container) obj = obj._get_node(key)", "Any: if is_bool(s): return str.lower(s) == \"true\" if is_int(s): return", "is Union def _resolve_optional(type_: Any) -> Tuple[bool, Any]: \"\"\"Check whether", "the next regex below (this # is to keep this", "API in attr that can detect that. # noinspection PyProtectedMember", "_resolve_forward(type_, obj.__module__) if hasattr(obj, name): value = getattr(obj, name) if", "False) -> str: is_optional, t = _resolve_optional(t) if t is", "\"ftp://${host}/path\", \"${foo:${bar}, [true], {'baz': ${baz}}}\" :param value: Input to classify.", "Type[Any]: import typing # lgtm [py/import-and-import-from] forward = typing.ForwardRef if", "FULL_KEY=full_key, VALUE=value, VALUE_TYPE=type_str(type(value), include_module_name=True), KEY_TYPE=f\"{type(key).__name__}\", ) if ref_type not in", "there is an extra \"\" in `tokens` that we #", "module=module) return List[et] # type: ignore return type_ def extract_dict_subclass_data(obj:", "\".a.b[c].d\" -> [\"\", \"a\", \"b\", \"c\", \"d\"] \"[a].b\" -> [\"a\",", "return st == \"true\" or st == \"false\" def is_float(st:", "to detect errors. parse(value) return ValueKind.INTERPOLATION else: return ValueKind.VALUE #", "\"ForwardRef\") else typing._ForwardRef # type: ignore if type(type_) is forward:", "# type: ignore return type_ def extract_dict_subclass_data(obj: Any, parent: Any)", "# pragma: no cover def is_tuple_annotation(type_: Any) -> bool: origin", "is_optional, type_ = _resolve_optional(resolved_hints[field.name]) type_ = _resolve_forward(type_, obj.__module__) if hasattr(obj,", "...: return \"...\" if sys.version_info < (3, 7, 0): #", "first_stop = first.span()[1] # `tokens` will contain all elements composing", "well. # Unfortunately currently there isn't an official API in", "one of \" + \"[dict,list,DictConfig,ListConfig,dataclass,dataclass instance,attr class,attr class instance]\" )", "tag, regexp in resolvers if tag != \"tag:yaml.org,2002:timestamp\" ] for", "True :param type_: variable type :return: bool \"\"\" return is_list_annotation(type_)", "!= \"typing\" and not t.__module__.startswith(\"omegaconf.\") ): module_prefix = t.__module__ +", "is_generic_list(type_: Any) -> bool: \"\"\" Checks if a type is", "or is_dict_annotation(type_) def split_key(key: str) -> List[str]: \"\"\" Split a", "components. This is similar to `key.split(\".\")` but also works with", "if SIMPLE_INTERPOLATION_PATTERN.match(value) is None: # If no match, do the", "only be detected when # `strict_interpolation_validation` is True. if isinstance(value,", "_raise(ex, cause) def type_str(t: Any, include_module_name: bool = False) ->", "is not None: raise ValueError(\"Key must only be provided when", "hasattr(typing, \"ForwardRef\") else typing._ForwardRef # type: ignore if type(type_) is", "parse(value) return ValueKind.INTERPOLATION else: return ValueKind.VALUE # DEPRECATED: remove in", "bit hard to detect. # this support is tentative, if", "args is not None: key_type = args[0] element_type = args[1]", "type_str(object_type) ref_type = get_ref_type(node) ref_type_str = type_str(ref_type) msg = string.Template(msg).safe_substitute(", "we would like [\"\", \"\"] tokens.pop() # Identify other key", "b/c/d, b) others = KEY_PATH_OTHER.findall(key[first_stop:]) # There are two groups", "metadata to see if the given node is optional.\"\"\" from", "-> Type[Any]: type_ = class_or_object if not isinstance(type_, type): type_", "= None ) -> Dict[str, Any]: from omegaconf.omegaconf import MISSING,", "dataclasses.MISSING: value = MISSING else: if field.default_factory == dataclasses.MISSING: #", "key=None, value=value, cause=e, msg=str(e)) try: d[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional,", "typing import ( Any, Dict, Iterator, List, Optional, Tuple, Type,", "by the presence of \"${\" in the string. # Note", "str) -> yaml.ScalarNode: with_quotes = yaml_is_bool(data) or is_int(data) or is_float(data)", "= None # type: ignore # pragma: no cover #", "_is_union(type_): e = ConfigValueError( f\"Union types are not supported:\\n{name}: {type_str(type_)}\"", "\"off\", \"Off\", \"OFF\", ] class Marker: def __init__(self, desc: str):", "Container, Node if isinstance(obj, Container): if key is not None:", "key and can # be read as a choice between", "\"tag:yaml.org,2002:timestamp\" ] for key, resolvers in loader.yaml_implicit_resolvers.items() } return loader", "\"\" object_type = None ref_type = None ref_type_str = None", "ValueKind: \"\"\" Determine the kind of a value Examples: VALUE:", "is Union: args = type_.__args__ if len(args) == 2 and", "name, attrib in attr.fields_dict(obj_type).items(): is_optional, type_ = _resolve_optional(attrib.type) type_ =", "return getattr(type_, \"__origin__\", None) is Union def _resolve_optional(type_: Any) ->", "\"${\", it is parsed to validate the interpolation syntax. If", "= MISSING else: value = field.default_factory() # type: ignore if", "DEPRECATED: remove in 2.2 def decode_primitive(s: str) -> Any: if", "optional.\"\"\" from .base import Container, Node if key is not", "_is_interpolation(boxed): return boxed # return primitives and regular OmegaConf Containers", "here would # be misleading. Instead, we display it in", "regex simple). KEY_PATH_HEAD = re.compile(r\"(\\.)*[^.[]*\") # Then we match other", "parsing step is skipped: this is more efficient, but will", "args[0] else: element_type = Any return element_type def get_dict_key_value_types(ref_type: Any)", "path into its individual components. This is similar to `key.split(\".\")`", "not OmegaConf.is_config(target): raise ValueError( \"Invalid input. Supports one of \"", "= {} key_type, element_type = get_dict_key_value_types(obj_type) for name, value in", "= _resolve_forward(et, module=module) return List[et] # type: ignore return type_", "value in obj.items(): is_optional, type_ = _resolve_optional(element_type) type_ = _resolve_forward(type_,", "if is_int(s): return int(s) if is_float(s): return float(s) return s", "# This can be read as \"dots followed by any", "None, ) -> None: from omegaconf import OmegaConf from omegaconf.base", "True, args[0] if type_ is Any: return True, Any return", "in attr that can detect that. # noinspection PyProtectedMember return", "omegaconf import Node if not isinstance(value, Node): return value is", "- `.` followed by anything except `.` or `[` (ex:", "Any) -> bool: return is_primitive_list(obj) or is_primitive_dict(obj) def get_list_element_type(ref_type: Optional[Type[Any]])", "instead, # once support for Python 3.6 is dropped). @contextmanager", "from omegaconf import Node if not isinstance(value, Node): return value", "if strict_interpolation_validation: # First try the cheap regex matching that", "Optional[str] = None ref_type: Optional[Type[Any]] ref_type_str: Optional[str] child_node: Optional[Node] =", "bool: t = get_type_of(obj) return t is dict def is_dict_annotation(type_:", "ignore value = MISSING else: value = field.default_factory() # type:", "intended, since they must be processed as interpolations # for", "cause=ex, msg=str(ex) ) return dict_subclass_data else: return None def get_attr_class_field_names(obj:", "-> bool: type_ = get_type_of(type_) return issubclass(type_, Enum) or type_", "super().construct_mapping(node, deep=deep) loader = OmegaConfLoader loader.add_implicit_resolver( \"tag:yaml.org,2002:float\", re.compile( \"\"\"^(?: [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)?", "`KEY_PATH_OTHER` regex: one for keys starting # with a dot", "\"${foo:${bar}, [true], {'baz': ${baz}}}\" :param value: Input to classify. :param", "we are done. if first_stop == len(key): return tokens if", "type: ignore if _is_union(type_): e = ConfigValueError( f\"Union types are", "= attrib.default if value == attr.NOTHING: value = MISSING if", "validate_access=False) try: full_key = node._get_full_key(key=key) except Exception as exc: #", "first_stop == len(key): return tokens if key[first_stop] == \"[\" and", "None or isinstance(obj, Node): return False return dataclasses.is_dataclass(obj) def is_attr_class(obj:", "rid of: # [a] -> tokens = [\"\"] but we", "type_ is None or type_ is Any or issubclass(type_, DictKeyType.__args__)", "ignore return type_ def extract_dict_subclass_data(obj: Any, parent: Any) -> Optional[Dict[str,", "is very hacky and probably fragile as well. # Unfortunately", "element_type def get_dict_key_value_types(ref_type: Any) -> Tuple[Any, Any]: args = getattr(ref_type,", "bool: return is_primitive_list(obj) or is_primitive_dict(obj) def get_list_element_type(ref_type: Optional[Type[Any]]) -> Any:", "no cover def is_tuple_annotation(type_: Any) -> bool: origin = getattr(type_,", "ref_type is not List and args is not None and", "None) -> Dict[str, Any]: from omegaconf.omegaconf import OmegaConf, _maybe_wrap flags", "exception_type = ConfigTypeError elif exception_type == IndexError: exception_type = ConfigIndexError", "+= [dot_key if dot_key else bracket_key for dot_key, bracket_key in", "def _is_interpolation(v: Any, strict_interpolation_validation: bool = False) -> bool: if", "= copy.deepcopy(cause.__dict__) _raise(ex, cause) object_type: Optional[Type[Any]] object_type_str: Optional[str] = None", "(in docstring examples: a, a, .a, '') first = KEY_PATH_HEAD.match(key)", "3.7+'s `contextlib.nullcontext` (which should be used instead, # once support", "isinstance(ret, bool) return ret return False def _get_value(value: Any) ->", "# [a] -> tokens = [\"\"] but we would like", "`tokens` will contain all elements composing the key. tokens =", "for Python 3.6 is dropped). @contextmanager def nullcontext(enter_result: Any =", "textwrap import dedent from typing import ( Any, Dict, Iterator,", "resolvers if tag != \"tag:yaml.org,2002:timestamp\" ] for key, resolvers in", "these examples: a, a, ..a). # This can be read", "if a type is a generic list, for example: list", "value: Any, resolve: bool = False, throw_on_resolution_failure: bool = True", "e.g. # [a] or ..[a]. In that case there is", "\" Subclassing `Dict` in Structured Config classes is deprecated,\" +", "of a subclass of Dict. If so, extract the Dict", "Any) -> bool: return type_ is Any or is_primitive_type(type_) or", "typing.List[T] returns True :param type_: variable type :return: bool \"\"\"", "def is_primitive_dict(obj: Any) -> bool: t = get_type_of(obj) return t", "value might or might not be a Node. return True", "msg=str(ex) ) d[name]._set_parent(None) dict_subclass_data = extract_dict_subclass_data(obj=obj, parent=dummy_parent) if dict_subclass_data is", "import_module module_path, _, class_name = path.rpartition(\".\") mod = import_module(module_path) try:", "like: a.b, a[b], ..a[c].d, etc. # We begin by matching", "\"\"\" Checks if a type is a generic dict, for", "not None: assert isinstance(obj, Container) obj = obj._get_node(key) if isinstance(obj,", "get_value_kind( value: Any, strict_interpolation_validation: bool = False ) -> ValueKind:", "that escaped interpolations (ex: \"esc: \\${bar}\") are identified as #", "try the cheap regex matching that detects common interpolations. if", "module_prefix + ret if is_optional: return f\"Optional[{ret}]\" else: return ret", "args is None: bases = getattr(ref_type, \"__orig_bases__\", None) if bases", "DictKeyType return type_ is None or type_ is Any or", "ex.key = key ex.full_key = full_key ex.value = value ex.object_type", "yaml_is_bool(b: str) -> bool: return b in YAML_BOOL_TYPES def get_yaml_loader()", "-> bool: try: float(st) return True except ValueError: return False", "exc: # Since we are handling an exception, raising a", "{ key: [ (tag, regexp) for tag, regexp in resolvers", "value: Any, strict_interpolation_validation: bool = False ) -> ValueKind: \"\"\"", "False def get_structured_config_field_names(obj: Any) -> List[str]: if is_dataclass(obj): return get_dataclass_field_names(obj)", "no cover # Regexprs to match key paths like: a.b,", "\"\" in `tokens` that we # need to get rid", "(which should be used instead, # once support for Python", "origin is Dict or type_ is Dict # pragma: no", "no cover else: return origin is list # pragma: no", "is more efficient, but will not detect errors. \"\"\" if", "is_optional=is_optional, key=name, value=value, parent=parent, ) except ValidationError as ex: format_and_raise(", "type_ = type(class_or_object) assert isinstance(type_, type) return type_ def is_structured_config_frozen(obj:", "List and args is not None and args[0]: element_type =", "raise ValueError(f\"Unsupported type: {type(obj).__name__}\") def get_structured_config_data( obj: Any, allow_objects: Optional[bool]", "loader = OmegaConfLoader loader.add_implicit_resolver( \"tag:yaml.org,2002:float\", re.compile( \"\"\"^(?: [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\\\.[0-9_]+(?:[eE][-+][0-9]+)?", "key: Any = None) -> Optional[Type[Any]]: from omegaconf import Container,", "when # `strict_interpolation_validation` is True. if isinstance(value, str) and \"${\"", "\"\"\" if _is_missing_value(value): return ValueKind.MANDATORY_MISSING value = _get_value(value) # We", "obj._metadata.ref_type if obj._is_optional() and ref_type is not Any: return Optional[ref_type]", "if isinstance(value, Node): value = value._value() return _is_missing_literal(value) def _is_missing_literal(value:", "kt, vt = get_dict_key_value_types(type_) if kt is not None: kt", "getattr(ref_type, \"__args__\", None) if args is None: bases = getattr(ref_type,", "\"OC_CAUSE\" in os.environ else None debugging = sys.gettrace() is not", "# noqa E721 return True, args[0] if type_ is Any:", "field.default_factory() # type: ignore if _is_union(type_): e = ConfigValueError( f\"Union", "list returns False typing.List returns False typing.List[T] returns True :param", "return List[et] # type: ignore return type_ def extract_dict_subclass_data(obj: Any,", "cheap regex matching that detects common interpolations. if SIMPLE_INTERPOLATION_PATTERN.match(value) is", "(None, Any): template = dedent( \"\"\"\\ $MSG full_key: $FULL_KEY reference_type=$REF_TYPE", ".base import Container, Node if key is not None: assert", ".base import Container return not isinstance(obj, Container) and isinstance(obj, (list,", "is not None else \"\" object_type = None ref_type =", "they must be processed as interpolations # for the string", "get_type_of(obj) return t is dict def is_dict_annotation(type_: Any) -> bool:", "else: name = str(t._name) args = getattr(t, \"__args__\", None) if", "value = _get_value(value) # We identify potential interpolations by the", "enum import Enum from textwrap import dedent from typing import", "ValueNode): return value._value() elif isinstance(value, Container): boxed = value._value() if", "if node is None: full_key = key if key is", "OmegaConfDumper.str_representer_added = True return OmegaConfDumper def yaml_is_bool(b: str) -> bool:", "from contextlib import contextmanager from enum import Enum from textwrap", "Union def _resolve_optional(type_: Any) -> Tuple[bool, Any]: \"\"\"Check whether `type_`", "dummy_parent._metadata.object_type = obj_type for name, attrib in attr.fields_dict(obj_type).items(): is_optional, type_", "else: raise ValueError(f\"Unsupported type: {type(obj).__name__}\") def get_structured_config_data( obj: Any, allow_objects:", "return False def _get_value(value: Any) -> Any: from .base import", "from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse try: import dataclasses except ImportError:", "else None debugging = sys.gettrace() is not None full_backtrace =", "resolvers in loader.yaml_implicit_resolvers.items() } return loader def _get_class(path: str) ->", "!= \"tag:yaml.org,2002:timestamp\" ] for key, resolvers in loader.yaml_implicit_resolvers.items() } return", "Any, msg: str, cause: Exception, type_override: Any = None, )", ".d) and one for keys starting with a bracket ([b],", "`contextlib.nullcontext` (which should be used instead, # once support for", "bases is not None and len(bases) > 0: args =", "type: {type(obj).__name__}\") def get_structured_config_data( obj: Any, allow_objects: Optional[bool] = None", "or is_dataclass(obj) def is_dataclass_frozen(type_: Any) -> bool: return type_.__dataclass_params__.frozen #", "value is None: # Resolution failure: consider that it is", "def is_dict_subclass(type_: Any) -> bool: return type_ is not None", "for tag, regexp in resolvers if tag != \"tag:yaml.org,2002:timestamp\" ]", "[a] -> tokens = [\"\"] but we would like []", "# If no match, do the more expensive grammar parsing", "if args is None: bases = getattr(ref_type, \"__orig_bases__\", None) if", "is None: full_key = key if key is not None", "a Node, treat it as optional by default. # This", ") exception_type = type(cause) if type_override is None else type_override", "_, class_name = path.rpartition(\".\") mod = import_module(module_path) try: klass: type", "klass: type = getattr(mod, class_name) except AttributeError: raise ImportError(f\"Class {class_name}", "from omegaconf.omegaconf import _maybe_wrap is_type = isinstance(obj, type) obj_type =", "True, Any return False, type_ def _is_optional(obj: Any, key: Optional[Union[int,", "-> bool: try: int(st) return True except ValueError: return False", "= _resolve_optional(t) if t is None: return type(t).__name__ if t", "-> List[str]: return [field.name for field in dataclasses.fields(obj)] def get_dataclass_data(", "\"[\" and not tokens[-1]: # This is a special case", "from omegaconf import OmegaConf from omegaconf.base import Node if isinstance(cause,", "as a choice between two syntaxes: # - `.` followed", "ref_type = None ref_type_str = None else: if key is", "`obj` metadata to see if the given node is optional.\"\"\"", "return type_ is Any or is_primitive_type(type_) or is_structured_config(type_) def _valid_dict_key_annotation_type(type_:", "ref_type=type_, is_optional=is_optional, key=name, value=value, parent=dummy_parent, ) except (ValidationError, GrammarParseError) as", "type_ is Any or issubclass(type_, DictKeyType.__args__) # type: ignore def", "3.6 is dropped). @contextmanager def nullcontext(enter_result: Any = None) ->", "return True except ValueError: return False # DEPRECATED: remove in", "+ \" Subclassing `Dict` in Structured Config classes is deprecated,\"", "dedent from typing import ( Any, Dict, Iterator, List, Optional,", "key {key_node.value}\", key_node.start_mark, ) keys.add(key_node.value) return super().construct_mapping(node, deep=deep) loader =", "issubclass(type_, Enum) or type_ in (int, float, bool, str, type(None))", "[\"\"] but we would like [] # ..[a] -> tokens", "Any) -> Type[Any]: type_ = class_or_object if not isinstance(type_, type):", "dict_subclass_data is not None: d.update(dict_subclass_data) return d def get_dataclass_field_names(obj: Any)", "identified as # interpolations: this is intended, since they must", "\"YES\", \"n\", \"N\", \"no\", \"No\", \"NO\", \"true\", \"True\", \"TRUE\", \"false\",", "= None ref_type_str = None else: if key is not", "is_bool(s): return str.lower(s) == \"true\" if is_int(s): return int(s) if", "hasattr(obj, name): value = getattr(obj, name) if value == dataclasses.MISSING:", "omegaconf.base import Node if isinstance(cause, AssertionError): raise if isinstance(cause, OmegaConfBaseException)", "eventually causes issues in other areas it may be dropped.", "\"__origin__\", None) is Union def _resolve_optional(type_: Any) -> Tuple[bool, Any]:", "[type_str(t, include_module_name=include_module_name) for t in t.__args__] ) ret = f\"{name}[{args}]\"", "regular OmegaConf Containers as is return value def get_ref_type(obj: Any,", "omegaconf.omegaconf import OmegaConf, _maybe_wrap flags = {\"allow_objects\": allow_objects} if allow_objects", "def _raise(ex: Exception, cause: Exception) -> None: # Set the", "= ConfigIndexError ex = exception_type(f\"{message}\") if issubclass(exception_type, OmegaConfBaseException): ex._initialized =", "return is_list_annotation(type_) or is_dict_annotation(type_) def split_key(key: str) -> List[str]: \"\"\"", "ignore # pragma: no cover try: import attr except ImportError:", "if args is not None: args = \", \".join( [type_str(t,", "return type_ def extract_dict_subclass_data(obj: Any, parent: Any) -> Optional[Dict[str, Any]]:", "ref_type = obj._metadata.ref_type if obj._is_optional() and ref_type is not Any:", "# Obtain the first part of the key (in docstring", "elements (in docstring examples: b, b, b/c/d, b) others =", "variable OC_CAUSE=1 to get a stacktrace that includes the #", "None: raise ValueError(\"Key must only be provided when obj is", "as ex: format_and_raise( node=dummy_parent, key=name, value=value, cause=ex, msg=str(ex) ) d[name]._set_parent(None)", "hasattr(t, \"__module__\") and t.__module__ != \"builtins\" and t.__module__ != \"typing\"", "if sys.version_info < (3, 7, 0): # pragma: no cover", "return b in YAML_BOOL_TYPES def get_yaml_loader() -> Any: class OmegaConfLoader(yaml.SafeLoader):", "ex.__cause__ = None raise ex.with_traceback(sys.exc_info()[2]) # set end OC_CAUSE=1 for", "type_str(ref_type) msg = string.Template(msg).safe_substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, KEY=key, FULL_KEY=full_key, VALUE=value, VALUE_TYPE=type_str(type(value),", "if t is Any: return \"Any\" if t is ...:", "is_list_annotation(type_: Any) -> bool: origin = getattr(type_, \"__origin__\", None) if", "= None # type: ignore # pragma: no cover try:", "the `KEY_PATH_OTHER` regex: one for keys starting # with a", "is_dict(obj: Any) -> bool: return is_primitive_dict(obj) or is_dict_annotation(obj) or is_dict_subclass(obj)", "_resolve_forward(kt, module=module) if vt is not None: vt = _resolve_forward(vt,", "def _resolve_optional(type_: Any) -> Tuple[bool, Any]: \"\"\"Check whether `type_` is", "Exception, cause: Exception) -> None: # Set the environment variable", "of \" + \"[dict,list,DictConfig,ListConfig,dataclass,dataclass instance,attr class,attr class instance]\" ) return", "t.__module__.startswith(\"omegaconf.\") ): module_prefix = t.__module__ + \".\" else: module_prefix =", "begin by matching the head (in these examples: a, a,", "no cover attr = None # type: ignore # pragma:", "def is_container_annotation(type_: Any) -> bool: return is_list_annotation(type_) or is_dict_annotation(type_) def", "cover dataclasses = None # type: ignore # pragma: no", "..a[c].d, etc. # We begin by matching the head (in", "0): return origin is Tuple or type_ is Tuple #", "Input to classify. :param strict_interpolation_validation: If `True`, then when `value`", "is not an option. _DEFAULT_MARKER_: Any = Marker(\"_DEFAULT_MARKER_\") class OmegaConfDumper(yaml.Dumper):", "attr is None or isinstance(obj, Node): return False return attr.has(obj)", "subclasses `Dict`.\" + \" Subclassing `Dict` in Structured Config classes", "= getattr(obj, name) if value == dataclasses.MISSING: value = MISSING", "def is_primitive_type(type_: Any) -> bool: type_ = get_type_of(type_) return issubclass(type_,", "tokens += [dot_key if dot_key else bracket_key for dot_key, bracket_key", "return target def is_generic_list(type_: Any) -> bool: \"\"\" Checks if", "msg=str(ex) ) return dict_subclass_data else: return None def get_attr_class_field_names(obj: Any)", "and value == \"???\" def _is_none( value: Any, resolve: bool", "type_.__args__ if len(args) == 2 and args[1] == type(None): #", "f\"Class `{obj_type.__name__}` subclasses `Dict`.\" + \" Subclassing `Dict` in Structured", "is not None else {} d = {} obj_type =", "is tuple # pragma: no cover def is_dict_subclass(type_: Any) ->", "is used in `ListConfig.append` and `ListConfig.insert` # where the appended/inserted", "None else {} from omegaconf import MISSING d = {}", "e = ConfigValueError( f\"Union types are not supported:\\n{name}: {type_str(type_)}\" )", "not tokens[-1]: # This is a special case where the", "# is to keep this regex simple). KEY_PATH_HEAD = re.compile(r\"(\\.)*[^.[]*\")", "value_node in node.value: if key_node.tag != yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG: continue if key_node.value", "return is_dataclass_frozen(type_) if is_attr_class(type_): return is_attr_frozen(type_) return False def get_structured_config_field_names(obj:", "is None: # If no match, do the more expensive", "is_primitive_container(target): assert isinstance(target, (list, dict)) target = OmegaConf.create(target, flags=flags) elif", "is_int(st: str) -> bool: try: int(st) return True except ValueError:", "REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key ) exception_type = type(cause) if type_override", "_resolve_optional(attrib.type) type_ = _resolve_forward(type_, obj.__module__) if not is_type: value =", "path.rpartition(\".\") mod = import_module(module_path) try: klass: type = getattr(mod, class_name)", "Any) -> bool: type_ = get_type_of(obj) if is_dataclass(type_): return is_dataclass_frozen(type_)", "contextlib import contextmanager from enum import Enum from textwrap import", "pragma: no cover # type_dict is a bit hard to", "False) -> Any: keys = set() for key_node, value_node in", "class OmegaConfDumper(yaml.Dumper): # type: ignore str_representer_added = False @staticmethod def", "Any: from omegaconf import OmegaConf if is_primitive_container(target): assert isinstance(target, (list,", "type_ = _resolve_forward(type_, obj.__module__) try: dict_subclass_data[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional,", "Examples: VALUE: \"10\", \"20\", True MANDATORY_MISSING: \"???\" INTERPOLATION: \"${foo.bar}\", \"${foo.${bar}}\",", "or is_dict_subclass(obj) def is_primitive_container(obj: Any) -> bool: return is_primitive_list(obj) or", "else: element_type = Any return element_type def get_dict_key_value_types(ref_type: Any) ->", "examples: b, b, b/c/d, b) others = KEY_PATH_OTHER.findall(key[first_stop:]) # There", "is None else type_override if exception_type == TypeError: exception_type =", "str) -> bool: return b in YAML_BOOL_TYPES def get_yaml_loader() ->", "get_ref_type(obj: Any, key: Any = None) -> Optional[Type[Any]]: from omegaconf", "groups in the `KEY_PATH_OTHER` regex: one for keys starting #", "return False, type_ def _is_optional(obj: Any, key: Optional[Union[int, str]] =", "ValueKind.VALUE # DEPRECATED: remove in 2.2 def is_bool(st: str) ->", "bool, str, type(None)) def _is_interpolation(v: Any, strict_interpolation_validation: bool = False)", "None first_stop = first.span()[1] # `tokens` will contain all elements", "from importlib import import_module module_path, _, class_name = path.rpartition(\".\") mod", "ignore if type(type_) is forward: return _get_class(f\"{module}.{type_.__forward_arg__}\") else: if is_dict_annotation(type_):", "exception_type(f\"{message}\") if issubclass(exception_type, OmegaConfBaseException): ex._initialized = True ex.msg = message", "be used as default value when `None` is not an", "\"???\" INTERPOLATION: \"${foo.bar}\", \"${foo.${bar}}\", \"${foo:bar}\", \"[${foo}, ${bar}]\", \"ftp://${host}/path\", \"${foo:${bar}, [true],", ") return dict_subclass_data else: return None def get_attr_class_field_names(obj: Any) ->", "name = str(t.__name__) else: if t.__origin__ is not None: name", "cover # Regexprs to match key paths like: a.b, a[b],", "(.b, .d) and one for keys starting with a bracket", "\"on\", \"On\", \"ON\", \"off\", \"Off\", \"OFF\", ] class Marker: def", "$FULL_KEY reference_type=$REF_TYPE object_type=$OBJECT_TYPE\"\"\" ) else: template = dedent( \"\"\"\\ $MSG", "-> bool: return getattr(type_, \"__origin__\", None) is Union def _resolve_optional(type_:", "is_type: return None elif subclasses_dict: dict_subclass_data = {} key_type, element_type", "-> bool: return type_.__dataclass_params__.frozen # type: ignore def is_attr_frozen(type_: type)", "get_type_of(type_) return issubclass(type_, Enum) or type_ in (int, float, bool,", "= None) -> bool: \"\"\"Check `obj` metadata to see if", "Instead, we display it in the key. full_key = f\"<unresolvable", "< (3, 7, 0): # pragma: no cover # Python", "keys. The following expression matches one key and can #", "noqa E721 return True, args[0] if type_ is Any: return", "element_type = Any return key_type, element_type def valid_value_annotation_type(type_: Any) ->", "return attr.has(obj) def is_structured_config(obj: Any) -> bool: return is_attr_class(obj) or", "return _get_class(f\"{module}.{type_.__forward_arg__}\") else: if is_dict_annotation(type_): kt, vt = get_dict_key_value_types(type_) if", "for example: list returns False typing.List returns False typing.List[T] returns", "is Dict or type_ is Dict # pragma: no cover", "pragma: no cover # Regexprs to match key paths like:", "element_type = get_dict_key_value_types(obj_type) for name, value in obj.items(): is_optional, type_", "return key_type, element_type def valid_value_annotation_type(type_: Any) -> bool: return type_", "), list(\"-+0123456789.\"), ) loader.yaml_implicit_resolvers = { key: [ (tag, regexp)", "value = getattr(obj, name) if value == dataclasses.MISSING: value =", "MISSING else: if field.default_factory == dataclasses.MISSING: # type: ignore value", "-> bool: return type_ is Any or is_primitive_type(type_) or is_structured_config(type_)", "`typing.Optional[T]` for some T.\"\"\" if getattr(type_, \"__origin__\", None) is Union:", "= get_type_of(obj) if is_dataclass(type_): return is_dataclass_frozen(type_) if is_attr_class(type_): return is_attr_frozen(type_)", "type: ignore def _raise(ex: Exception, cause: Exception) -> None: #", "except (ValidationError, GrammarParseError) as ex: format_and_raise( node=dummy_parent, key=name, value=value, cause=ex,", ") ret = f\"{name}[{args}]\" else: ret = name if include_module_name:", "type_str( t.__origin__, include_module_name=include_module_name ) else: name = str(t._name) args =", "allow_objects is not None else {} d = {} obj_type", "class Marker: def __init__(self, desc: str): self.desc = desc def", "if the given node is optional.\"\"\" from .base import Container,", ") else: name = str(t._name) args = getattr(t, \"__args__\", None)", "= yaml_is_bool(data) or is_int(data) or is_float(data) return dumper.represent_scalar( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, data,", "as \"dots followed by any character but `.` or `[`\"", "_get_class(path: str) -> type: from importlib import import_module module_path, _,", "value = MISSING if _is_union(type_): e = ConfigValueError( f\"Union types", "a mapping\", node.start_mark, f\"found duplicate key {key_node.value}\", key_node.start_mark, ) keys.add(key_node.value)", "errors. parse(value) return ValueKind.INTERPOLATION else: return ValueKind.VALUE # DEPRECATED: remove", ".errors import ( ConfigIndexError, ConfigTypeError, ConfigValueError, GrammarParseError, OmegaConfBaseException, ValidationError, )", "for keys starting with a bracket ([b], [c]). # Only", "else: if t.__origin__ is not None: name = type_str(t.__origin__) else:", "followed by anything except `.` or `[` (ex: .b, .d)", "str) and \"${\" in value: if strict_interpolation_validation: # First try", "ex.object_type = object_type ex.object_type_str = object_type_str ex.ref_type = ref_type ex.ref_type_str", "FULL_KEY=full_key ) exception_type = type(cause) if type_override is None else", "issubclass(type_, Dict) def is_dict(obj: Any) -> bool: return is_primitive_dict(obj) or", "= extract_dict_subclass_data(obj=obj, parent=dummy_parent) if dict_subclass_data is not None: d.update(dict_subclass_data) return", "_is_interpolation(v: Any, strict_interpolation_validation: bool = False) -> bool: if isinstance(v,", "= _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value, parent=parent, ) except ValidationError", "if is_dataclass(type_): return is_dataclass_frozen(type_) if is_attr_class(type_): return is_attr_frozen(type_) return False", "in Structured Config classes is deprecated,\" + \" see github.com/omry/omegaconf/issues/663\",", "key=name, value=value, parent=parent, ) except ValidationError as ex: format_and_raise( node=None,", "module=module) if vt is not None: vt = _resolve_forward(vt, module=module)", "Any, allow_objects: Optional[bool] = None ) -> Dict[str, Any]: from", "if it eventually causes issues in other areas it may", "typing._ForwardRef # type: ignore if type(type_) is forward: return _get_class(f\"{module}.{type_.__forward_arg__}\")", "[py/import-and-import-from] forward = typing.ForwardRef if hasattr(typing, \"ForwardRef\") else typing._ForwardRef #", "type_ = class_or_object if not isinstance(type_, type): type_ = type(class_or_object)", ") if not throw_on_resolution_failure and value is None: # Resolution", "= False, throw_on_resolution_failure: bool = True ) -> bool: from", "step is skipped: this is more efficient, but will not", "Node if isinstance(value, Node): value = value._value() return _is_missing_literal(value) def", "ref_type_str = None else: if key is not None and", "else: if key is not None and not node._is_none(): child_node", "as exc: # Since we are handling an exception, raising", "like [\"\", \"\"] tokens.pop() # Identify other key elements (in", "full_key = f\"<unresolvable due to {type(exc).__name__}: {exc}>\" object_type = OmegaConf.get_type(node)", "KEY_PATH_OTHER.findall(key[first_stop:]) # There are two groups in the `KEY_PATH_OTHER` regex:", "Any, value: Any, msg: str, cause: Exception, type_override: Any =", "if t.__origin__ is not None: name = type_str( t.__origin__, include_module_name=include_module_name", "no cover # type_dict is a bit hard to detect.", "Any) -> bool: return getattr(type_, \"__origin__\", None) is Union def", "if not isinstance(value, Node): return value is None if resolve:", "remove in 2.2 def is_bool(st: str) -> bool: st =", "= is_dict_subclass(obj_type) if subclasses_dict: warnings.warn( f\"Class `{obj_type.__name__}` subclasses `Dict`.\" +", "then `]` (ex: [b], [c]) KEY_PATH_OTHER = re.compile(r\"\\.([^.[]*)|\\[(.*?)\\]\") # source:", "attr.NOTHING: value = MISSING if _is_union(type_): e = ConfigValueError( f\"Union", "origin is List or type_ is List # pragma: no", "OmegaConfLoader loader.add_implicit_resolver( \"tag:yaml.org,2002:float\", re.compile( \"\"\"^(?: [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]* |[-+]?\\\\.(?:inf|Inf|INF)", "type_ is List # pragma: no cover else: return origin", "] for key, resolvers in loader.yaml_implicit_resolvers.items() } return loader def", "bool: from omegaconf import Node if not isinstance(value, Node): return", "= node._get_node(key, validate_access=False) try: full_key = node._get_full_key(key=key) except Exception as", "= type_str( t.__origin__, include_module_name=include_module_name ) else: name = str(t._name) args", "full key path into its individual components. This is similar", "re.X, ), list(\"-+0123456789.\"), ) loader.yaml_implicit_resolvers = { key: [ (tag,", "non-empty. tokens += [dot_key if dot_key else bracket_key for dot_key,", "not None: args = \", \".join( [type_str(t, include_module_name=include_module_name) for t", "(in these examples: a, a, ..a). # This can be", "no cover else: # pragma: no cover # type_dict is", "node: Any, key: Any, value: Any, msg: str, cause: Exception,", "bool: return b in YAML_BOOL_TYPES def get_yaml_loader() -> Any: class", "-> type: from importlib import import_module module_path, _, class_name =", "# type: ignore def is_attr_frozen(type_: type) -> bool: # This", "2 def _is_missing_value(value: Any) -> bool: from omegaconf import Node", "type_dict is a bit hard to detect. # this support", "individual components. This is similar to `key.split(\".\")` but also works", "we # need to get rid of: # [a] ->", "False, type_ def _is_optional(obj: Any, key: Optional[Union[int, str]] = None)", "is optional.\"\"\" from .base import Container, Node if key is", "ignore def _raise(ex: Exception, cause: Exception) -> None: # Set", "this parsing step is skipped: this is more efficient, but", "import _maybe_wrap is_type = isinstance(obj, type) obj_type = obj if", "is Any: return True, Any return False, type_ def _is_optional(obj:", "return type_ is None or type_ is Any or issubclass(type_,", "next regex below (this # is to keep this regex", "INTERPOLATION: \"${foo.bar}\", \"${foo.${bar}}\", \"${foo:bar}\", \"[${foo}, ${bar}]\", \"ftp://${host}/path\", \"${foo:${bar}, [true], {'baz':", "is not None: key_type = args[0] element_type = args[1] else:", "obj._get_node(key) else: if key is not None: raise ValueError(\"Key must", "env_var = os.environ[\"OC_CAUSE\"] if \"OC_CAUSE\" in os.environ else None debugging", "else: # pragma: no cover # type_dict is a bit", "(3, 7, 0): return origin is Tuple or type_ is", "# type: ignore if is_list_annotation(type_): et = get_list_element_type(type_) if et", "key_type = Any element_type = Any return key_type, element_type def", "= name if include_module_name: if ( hasattr(t, \"__module__\") and t.__module__", "{type(exc).__name__}: {exc}>\" object_type = OmegaConf.get_type(node) object_type_str = type_str(object_type) ref_type =", "if a type is a generic dict, for example: list", "key_node.value in keys: raise yaml.constructor.ConstructorError( \"while constructing a mapping\", node.start_mark,", "Any = Marker(\"_DEFAULT_MARKER_\") class OmegaConfDumper(yaml.Dumper): # type: ignore str_representer_added =", "import MISSING d = {} is_type = isinstance(obj, type) obj_type", "= None ref_type: Optional[Type[Any]] ref_type_str: Optional[str] child_node: Optional[Node] = None", "None: name = type_str( t.__origin__, include_module_name=include_module_name ) else: name =", "= OmegaConf.structured(target, flags=flags) elif not OmegaConf.is_config(target): raise ValueError( \"Invalid input.", "more efficient, but will not detect errors. \"\"\" if _is_missing_value(value):", "# be misleading. Instead, we display it in the key.", "OmegaConfDumper.str_representer_added: OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer) OmegaConfDumper.str_representer_added = True return OmegaConfDumper def yaml_is_bool(b:", "b in YAML_BOOL_TYPES def get_yaml_loader() -> Any: class OmegaConfLoader(yaml.SafeLoader): #", "[\"\", \"a\", \"b\", \"c\", \"d\"] \"[a].b\" -> [\"a\", \"b\"] \"\"\"", ") -> ValueKind: \"\"\" Determine the kind of a value", "dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type for name, attrib", "\"10\", \"20\", True MANDATORY_MISSING: \"???\" INTERPOLATION: \"${foo.bar}\", \"${foo.${bar}}\", \"${foo:bar}\", \"[${foo},", "t = get_type_of(obj) return t is dict def is_dict_annotation(type_: Any)", "subclasses_dict = is_dict_subclass(obj_type) if subclasses_dict: warnings.warn( f\"Class `{obj_type.__name__}` subclasses `Dict`.\"", "not None else {} d = {} obj_type = get_type_of(obj)", "-> bool: from omegaconf.base import Node if attr is None", "Any) -> bool: return is_attr_class(obj) or is_dataclass(obj) def is_dataclass_frozen(type_: Any)", "if sys.version_info < (3, 7, 0): return origin is Tuple", "we match other keys. The following expression matches one key", "not supported:\\n{name}: {type_str(type_)}\" ) format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e)) try:", "parent=dummy_parent) if dict_subclass_data is not None: d.update(dict_subclass_data) return d def", "Dict or type_ is Dict # pragma: no cover else:", "$FULL_KEY object_type=$OBJECT_TYPE\"\"\" ) s = string.Template(template=template) message = s.substitute( REF_TYPE=ref_type_str,", "None: et = _resolve_forward(et, module=module) return List[et] # type: ignore", "Tuple or type_ is Tuple # pragma: no cover else:", "= child_node ex.key = key ex.full_key = full_key ex.value =", "name = name[len(\"typing.\") :] else: # pragma: no cover #", "+ ret if is_optional: return f\"Optional[{ret}]\" else: return ret def", "Optional[bool] = None) -> Dict[str, Any]: from omegaconf.omegaconf import OmegaConf,", "= obj._get_node(key) if isinstance(obj, Node): return obj._is_optional() else: # In", "is Tuple or type_ is Tuple # pragma: no cover", "-> None: # Set the environment variable OC_CAUSE=1 to get", "key[0:first_stop].split(\".\") # Optimization in case `key` has no other component:", "Any): template = dedent( \"\"\"\\ $MSG full_key: $FULL_KEY reference_type=$REF_TYPE object_type=$OBJECT_TYPE\"\"\"", "in case `key` has no other component: we are done.", "\"b\", \"c\", \"d\"] \"[a].b\" -> [\"a\", \"b\"] \"\"\" # Obtain", "False assert isinstance(value, Node) return value._is_none() def get_value_kind( value: Any,", "of the key (in docstring examples: a, a, .a, '')", "is_attr_frozen(type_) return False def get_structured_config_field_names(obj: Any) -> List[str]: if is_dataclass(obj):", "st = str.lower(st) return st == \"true\" or st ==", "this support is tentative, if it eventually causes issues in", "obj_type = obj if is_type else type(obj) return list(attr.fields_dict(obj_type)) def", "value Examples: VALUE: \"10\", \"20\", True MANDATORY_MISSING: \"???\" INTERPOLATION: \"${foo.bar}\",", "cause if type_override is not None: ex = type_override(str(cause)) ex.__dict__", "= value ex.object_type = object_type ex.object_type_str = object_type_str ex.ref_type =", "Any # type: ignore def _raise(ex: Exception, cause: Exception) ->", "object_type = OmegaConf.get_type(node) object_type_str = type_str(object_type) ref_type = get_ref_type(node) ref_type_str", "be provided when obj is a container\") if isinstance(obj, Node):", "and get_list_element_type(type_) is not None def is_generic_dict(type_: Any) -> bool:", "import warnings from contextlib import contextmanager from enum import Enum", "[c]) KEY_PATH_OTHER = re.compile(r\"\\.([^.[]*)|\\[(.*?)\\]\") # source: https://yaml.org/type/bool.html YAML_BOOL_TYPES = [", "is_dataclass(type_): return is_dataclass_frozen(type_) if is_attr_class(type_): return is_attr_frozen(type_) return False def", "bool \"\"\" return is_list_annotation(type_) and get_list_element_type(type_) is not None def", "et = _resolve_forward(et, module=module) return List[et] # type: ignore return", "bool: return type_ is Any or is_primitive_type(type_) or is_structured_config(type_) def", "dataclasses.is_dataclass(obj) def is_attr_class(obj: Any) -> bool: from omegaconf.base import Node", "get_type_of(class_or_object: Any) -> Type[Any]: type_ = class_or_object if not isinstance(type_,", "is_bool(st: str) -> bool: st = str.lower(st) return st ==", "input. Supports one of \" + \"[dict,list,DictConfig,ListConfig,dataclass,dataclass instance,attr class,attr class", "is None: return type(t).__name__ if t is Any: return \"Any\"", "node.start_mark, f\"found duplicate key {key_node.value}\", key_node.start_mark, ) keys.add(key_node.value) return super().construct_mapping(node,", "\"${foo.${bar}}\", \"${foo:bar}\", \"[${foo}, ${bar}]\", \"ftp://${host}/path\", \"${foo:${bar}, [true], {'baz': ${baz}}}\" :param", "OmegaConfDumper(yaml.Dumper): # type: ignore str_representer_added = False @staticmethod def str_representer(dumper:", "we display it in the key. full_key = f\"<unresolvable due", "-> bool: from omegaconf import DictKeyType return type_ is None", "`strict_interpolation_validation` is True. if isinstance(value, str) and \"${\" in value:", "syntaxes: # - `.` followed by anything except `.` or", "type_.__base__ == dict return origin is dict or typed_dict def", "else \"\" object_type = None ref_type = None ref_type_str =", "import Container return not isinstance(obj, Container) and isinstance(obj, (list, tuple))", "def __repr__(self) -> str: return self.desc # To be used", "args[1] == type(None): # noqa E721 return True, args[0] if", "\"d\"] \"[a].b\" -> [\"a\", \"b\"] \"\"\" # Obtain the first", "-> [\"a\", \"b\"] \"a[b]\" -> [\"a, \"b\"] \".a.b[c].d\" -> [\"\",", "regex: one for keys starting # with a dot (.b,", "(this # is to keep this regex simple). KEY_PATH_HEAD =", "# ..[a] -> tokens = [\"\", \"\", \"\"] but we", "pragma: no cover # Python >= 3.7 if hasattr(t, \"__name__\"):", "= None ) -> Dict[str, Any]: if is_dataclass(obj): return get_dataclass_data(obj,", "Container): boxed = value._value() if boxed is None or _is_missing_literal(boxed)", "__repr__(self) -> str: return self.desc # To be used as", "_maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value, parent=parent, ) except ValidationError as", "from omegaconf import OmegaConf if is_primitive_container(target): assert isinstance(target, (list, dict))", "return False assert isinstance(value, Node) return value._is_none() def get_value_kind( value:", "\"__name__\"): name = str(t.__name__) else: if t.__origin__ is not None:", "= 1 INTERPOLATION = 2 def _is_missing_value(value: Any) -> bool:", "instead of the MISSING const for performance reasons. return isinstance(value,", "or is_dict_annotation(obj) or is_dict_subclass(obj) def is_primitive_container(obj: Any) -> bool: return", "by any character but `.` or `[`\" # Note that", "ref_type is not Any: return Optional[ref_type] # type: ignore else:", "allow_objects} if allow_objects is not None else {} d =", "type: ignore # pragma: no cover # Regexprs to match", "< (3, 7, 0): return origin is List or type_", "[\"a, \"b\"] \".a.b[c].d\" -> [\"\", \"a\", \"b\", \"c\", \"d\"] \"[a].b\"", "the string. # Note that escaped interpolations (ex: \"esc: \\${bar}\")", "t.__module__ + \".\" else: module_prefix = \"\" ret = module_prefix", "return tokens # Similar to Python 3.7+'s `contextlib.nullcontext` (which should", "exception_type == TypeError: exception_type = ConfigTypeError elif exception_type == IndexError:", "in the next regex below (this # is to keep", "is ...: return \"...\" if sys.version_info < (3, 7, 0):", "= re.compile(r\"(\\.)*[^.[]*\") # Then we match other keys. The following", "get_structured_config_field_names(obj: Any) -> List[str]: if is_dataclass(obj): return get_dataclass_field_names(obj) elif is_attr_class(obj):", "first part of the key (in docstring examples: a, a,", "is a string containing \"${\", it is parsed to validate", "if vt is not None: vt = _resolve_forward(vt, module=module) return", "Any) -> bool: return type_.__dataclass_params__.frozen # type: ignore def is_attr_frozen(type_:", "common interpolations. if SIMPLE_INTERPOLATION_PATTERN.match(value) is None: # If no match,", "must only be provided when obj is a container\") if", "Optional[ref_type] # type: ignore else: return ref_type else: return Any", "is parsed to validate the interpolation syntax. If `False`, this", "_valid_dict_key_annotation_type(type_: Any) -> bool: from omegaconf import DictKeyType return type_", "_get_class(f\"{module}.{type_.__forward_arg__}\") else: if is_dict_annotation(type_): kt, vt = get_dict_key_value_types(type_) if kt", "[a], is purposedly *not* # matched here and will instead", "so, extract the Dict keys/values.\"\"\" from omegaconf.omegaconf import _maybe_wrap is_type", "module=module) return Dict[kt, vt] # type: ignore if is_list_annotation(type_): et", "string import sys import warnings from contextlib import contextmanager from", "Any) -> bool: return is_primitive_dict(obj) or is_dict_annotation(obj) or is_dict_subclass(obj) def", "an exception, raising a different one here would # be", "in os.environ else None debugging = sys.gettrace() is not None", "os.environ else None debugging = sys.gettrace() is not None full_backtrace", "if ref_type not in (None, Any): template = dedent( \"\"\"\\", "string containing \"${\", it is parsed to validate the interpolation", "\"a[b]\" -> [\"a, \"b\"] \".a.b[c].d\" -> [\"\", \"a\", \"b\", \"c\",", "or is_int(data) or is_float(data) return dumper.represent_scalar( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, data, style=(\"'\" if", "= args[0] else: element_type = Any return element_type def get_dict_key_value_types(ref_type:", ".grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse try: import dataclasses except ImportError: #", "_is_none( value: Any, resolve: bool = False, throw_on_resolution_failure: bool =", "return self.desc # To be used as default value when", "type) obj_type = obj if is_type else type(obj) return list(attr.fields_dict(obj_type))", "is Dict # pragma: no cover else: # pragma: no", "in the string. # Note that escaped interpolations (ex: \"esc:", "type_: variable type :return: bool \"\"\" return is_list_annotation(type_) and get_list_element_type(type_)", "if key[first_stop] == \"[\" and not tokens[-1]: # This is", "case there is an extra \"\" in `tokens` that we", "[b], [c]) KEY_PATH_OTHER = re.compile(r\"\\.([^.[]*)|\\[(.*?)\\]\") # source: https://yaml.org/type/bool.html YAML_BOOL_TYPES =", "return d def is_dataclass(obj: Any) -> bool: from omegaconf.base import", "as well. # Unfortunately currently there isn't an official API", "Exception as exc: # Since we are handling an exception,", "key_node.tag != yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG: continue if key_node.value in keys: raise yaml.constructor.ConstructorError(", "get_dataclass_data(obj, allow_objects=allow_objects) elif is_attr_class(obj): return get_attr_data(obj, allow_objects=allow_objects) else: raise ValueError(f\"Unsupported", "choice between two syntaxes: # - `.` followed by anything", "others] return tokens # Similar to Python 3.7+'s `contextlib.nullcontext` (which", "not a Node, treat it as optional by default. #", "Node, treat it as optional by default. # This is", "None debugging = sys.gettrace() is not None full_backtrace = (debugging", "message = s.substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key ) exception_type =", "of \"${\" in the string. # Note that escaped interpolations", "exception_type == IndexError: exception_type = ConfigIndexError ex = exception_type(f\"{message}\") if", "value: Any, msg: str, cause: Exception, type_override: Any = None,", "typing # lgtm [py/import-and-import-from] forward = typing.ForwardRef if hasattr(typing, \"ForwardRef\")", "= exception_type(f\"{message}\") if issubclass(exception_type, OmegaConfBaseException): ex._initialized = True ex.msg =", "be misleading. Instead, we display it in the key. full_key", "if ref_type is not List and args is not None", "str: is_optional, t = _resolve_optional(t) if t is None: return", "from typing import ( Any, Dict, Iterator, List, Optional, Tuple,", "is_attr_class(type_): return is_attr_frozen(type_) return False def get_structured_config_field_names(obj: Any) -> List[str]:", "# - `.` followed by anything except `.` or `[`", "try: klass: type = getattr(mod, class_name) except AttributeError: raise ImportError(f\"Class", "for name, attrib in attr.fields_dict(obj_type).items(): is_optional, type_ = _resolve_optional(attrib.type) type_", "= { key: [ (tag, regexp) for tag, regexp in", "return t is dict def is_dict_annotation(type_: Any) -> bool: origin", "a generic list, for example: list returns False typing.List returns", "read as a choice between two syntaxes: # - `.`", "Any: from .base import Container from .nodes import ValueNode if", "bool: from omegaconf.base import Node if dataclasses is None or", "object_type: Optional[Type[Any]] object_type_str: Optional[str] = None ref_type: Optional[Type[Any]] ref_type_str: Optional[str]", "dropped). @contextmanager def nullcontext(enter_result: Any = None) -> Iterator[Any]: yield", "Any, parent: Any) -> Optional[Dict[str, Any]]: \"\"\"Check if obj is", "{} obj_type = get_type_of(obj) dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type =", "= getattr(ref_type, \"__args__\", None) if args is None: bases =", "if key is not None: raise ValueError(\"Key must only be", "is_type else type(obj) return list(attr.fields_dict(obj_type)) def get_attr_data(obj: Any, allow_objects: Optional[bool]", "None elif subclasses_dict: dict_subclass_data = {} key_type, element_type = get_dict_key_value_types(obj_type)", "re.compile(r\"(\\.)*[^.[]*\") # Then we match other keys. The following expression", "return origin is list # pragma: no cover def is_tuple_annotation(type_:", "in the `KEY_PATH_OTHER` regex: one for keys starting # with", "any character but `.` or `[`\" # Note that a", "is_dataclass_frozen(type_) if is_attr_class(type_): return is_attr_frozen(type_) return False def get_structured_config_field_names(obj: Any)", "equivalent to `typing.Optional[T]` for some T.\"\"\" if getattr(type_, \"__origin__\", None)", "if isinstance(v, str): ret = ( get_value_kind(v, strict_interpolation_validation) == ValueKind.INTERPOLATION", "key=name, value=value, cause=ex, msg=str(ex) ) return dict_subclass_data else: return None", "# We identify potential interpolations by the presence of \"${\"", "= import_module(module_path) try: klass: type = getattr(mod, class_name) except AttributeError:", "getattr(ref_type, \"__orig_bases__\", None) if bases is not None and len(bases)", "ex.child_node = child_node ex.key = key ex.full_key = full_key ex.value", "first is not None first_stop = first.span()[1] # `tokens` will", "UserWarning, stacklevel=9, ) if is_type: return None elif subclasses_dict: dict_subclass_data", "ignore if _is_union(type_): e = ConfigValueError( f\"Union types are not", "other keys. The following expression matches one key and can", "\"On\", \"ON\", \"off\", \"Off\", \"OFF\", ] class Marker: def __init__(self,", "int(st) return True except ValueError: return False # DEPRECATED: remove", "is_primitive_type(type_) or is_structured_config(type_) def _valid_dict_key_annotation_type(type_: Any) -> bool: from omegaconf", "os.environ[\"OC_CAUSE\"] if \"OC_CAUSE\" in os.environ else None debugging = sys.gettrace()", "not None: d.update(dict_subclass_data) return d def is_dataclass(obj: Any) -> bool:", "False return dataclasses.is_dataclass(obj) def is_attr_class(obj: Any) -> bool: from omegaconf.base", "where the appended/inserted value might or might not be a", "The following expression matches one key and can # be", ":param strict_interpolation_validation: If `True`, then when `value` is a string", "'') first = KEY_PATH_HEAD.match(key) assert first is not None first_stop", "None) -> bool: \"\"\"Check `obj` metadata to see if the", "None ref_type_str = None else: if key is not None", "Similar to Python 3.7+'s `contextlib.nullcontext` (which should be used instead,", "match other keys. The following expression matches one key and", "(ex: .b, .d) # - `[` followed by anything then", "is dropped). @contextmanager def nullcontext(enter_result: Any = None) -> Iterator[Any]:", "from omegaconf import Container, Node if isinstance(obj, Container): if key", "if isinstance(value, str) and \"${\" in value: if strict_interpolation_validation: #", "or type_ is Dict # pragma: no cover else: #", "True ) -> bool: from omegaconf import Node if not", "return False def is_int(st: str) -> bool: try: int(st) return", "syntax: \"a.b\" -> [\"a\", \"b\"] \"a[b]\" -> [\"a, \"b\"] \".a.b[c].d\"", "getitem syntax: \"a.b\" -> [\"a\", \"b\"] \"a[b]\" -> [\"a, \"b\"]", "is None: if t.__origin__ is not None: name = type_str(", "where the first key starts with brackets, e.g. # [a]", "interpolations by the presence of \"${\" in the string. #", "return type_.__dataclass_params__.frozen # type: ignore def is_attr_frozen(type_: type) -> bool:", "isinstance(obj, type) obj_type = obj if is_type else type(obj) return", "is not None: kt = _resolve_forward(kt, module=module) if vt is", "args = type_.__args__ if len(args) == 2 and args[1] ==", "not None: ex = type_override(str(cause)) ex.__dict__ = copy.deepcopy(cause.__dict__) _raise(ex, cause)", "if key is not None: obj = obj._get_node(key) else: if", "target = OmegaConf.create(target, flags=flags) elif is_structured_config(target): target = OmegaConf.structured(target, flags=flags)", "starting with brackets, like [a], is purposedly *not* # matched", "no other component: we are done. if first_stop == len(key):", "cause: Exception) -> None: # Set the environment variable OC_CAUSE=1", "would # be misleading. Instead, we display it in the", "example: list returns False typing.List returns False typing.List[T] returns True", "or `[`\" # Note that a key starting with brackets,", "# In case `obj` is not a Node, treat it", "= obj._metadata.ref_type if obj._is_optional() and ref_type is not Any: return", "[\"a\", \"b\"] \"a[b]\" -> [\"a, \"b\"] \".a.b[c].d\" -> [\"\", \"a\",", "-> bool: if isinstance(v, str): ret = ( get_value_kind(v, strict_interpolation_validation)", "# We begin by matching the head (in these examples:", "not None: obj = obj._get_node(key) else: if key is not", "\"Invalid input. Supports one of \" + \"[dict,list,DictConfig,ListConfig,dataclass,dataclass instance,attr class,attr", "Tuple # pragma: no cover else: return origin is tuple", "ignore str_representer_added = False @staticmethod def str_representer(dumper: yaml.Dumper, data: str)", "obj: Any, allow_objects: Optional[bool] = None ) -> Dict[str, Any]:", "there isn't an official API in attr that can detect", "cover # Python >= 3.7 if hasattr(t, \"__name__\"): name =", "|\\\\.(?:nan|NaN|NAN))$\"\"\", re.X, ), list(\"-+0123456789.\"), ) loader.yaml_implicit_resolvers = { key: [", "Any) -> Optional[Dict[str, Any]]: \"\"\"Check if obj is an instance", "= OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type for name, attrib in", "= _resolve_optional(resolved_hints[field.name]) type_ = _resolve_forward(type_, obj.__module__) if hasattr(obj, name): value", "attr.fields_dict(obj_type).items(): is_optional, type_ = _resolve_optional(attrib.type) type_ = _resolve_forward(type_, obj.__module__) if", "args is not None and args[0]: element_type = args[0] else:", "not None and len(bases) > 0: args = getattr(bases[0], \"__args__\",", "ConfigTypeError, ConfigValueError, GrammarParseError, OmegaConfBaseException, ValidationError, ) from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN,", "= obj._get_node(key) else: if key is not None: raise ValueError(\"Key", "get_dict_key_value_types(ref_type: Any) -> Tuple[Any, Any]: args = getattr(ref_type, \"__args__\", None)", "Python 3.7+'s `contextlib.nullcontext` (which should be used instead, # once", "from .base import Container, Node if key is not None:", "if len(args) == 2 and args[1] == type(None): # noqa", "string. # Note that escaped interpolations (ex: \"esc: \\${bar}\") are", "Container, Node if key is not None: assert isinstance(obj, Container)", "except ImportError: # pragma: no cover dataclasses = None #", "if is_attr_class(type_): return is_attr_frozen(type_) return False def get_structured_config_field_names(obj: Any) ->", "str]] = None) -> bool: \"\"\"Check `obj` metadata to see", "if type_override is None else type_override if exception_type == TypeError:", "else type(obj) subclasses_dict = is_dict_subclass(obj_type) if subclasses_dict: warnings.warn( f\"Class `{obj_type.__name__}`", "= type_str(ref_type) msg = string.Template(msg).safe_substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, KEY=key, FULL_KEY=full_key, VALUE=value,", "s = string.Template(template=template) message = s.substitute( REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key", "= _resolve_optional(attrib.type) type_ = _resolve_forward(type_, obj.__module__) if not is_type: value", "Any) -> bool: from omegaconf.base import Node if attr is", "# Python >= 3.7 if hasattr(t, \"__name__\"): name = str(t.__name__)", "tokens = key[0:first_stop].split(\".\") # Optimization in case `key` has no", "validate the interpolation syntax. If `False`, this parsing step is", "loader def _get_class(path: str) -> type: from importlib import import_module", "if subclasses_dict: warnings.warn( f\"Class `{obj_type.__name__}` subclasses `Dict`.\" + \" Subclassing", "= str(t.__name__) else: if t.__origin__ is not None: name =", "_resolve_optional(element_type) type_ = _resolve_forward(type_, obj.__module__) try: dict_subclass_data[name] = _maybe_wrap( ref_type=type_,", "\"__args__\", None) if args is not None: args = \",", "dataclasses except ImportError: # pragma: no cover dataclasses = None", "return d def get_dataclass_field_names(obj: Any) -> List[str]: return [field.name for", "contextmanager from enum import Enum from textwrap import dedent from", "other areas it may be dropped. typed_dict = hasattr(type_, \"__base__\")", "sys.version_info < (3, 7, 0): # pragma: no cover #", "followed by any character but `.` or `[`\" # Note", "def _is_missing_literal(value: Any) -> bool: # Uses literal '???' instead", "# need to get rid of: # [a] -> tokens", "= get_list_element_type(type_) if et is not None: et = _resolve_forward(et,", "\"No\", \"NO\", \"true\", \"True\", \"TRUE\", \"false\", \"False\", \"FALSE\", \"on\", \"On\",", "if sys.version_info < (3, 7, 0): return origin is List", "a Node. return True def _resolve_forward(type_: Type[Any], module: str) ->", "== \"???\" def _is_none( value: Any, resolve: bool = False,", "ignore def is_attr_frozen(type_: type) -> bool: # This is very", "raise if isinstance(cause, OmegaConfBaseException) and cause._initialized: ex = cause if", "if dataclasses is None or isinstance(obj, Node): return False return", "is_dataclass_frozen(type_: Any) -> bool: return type_.__dataclass_params__.frozen # type: ignore def", "return value def get_ref_type(obj: Any, key: Any = None) ->", "Any or issubclass(type_, DictKeyType.__args__) # type: ignore def is_primitive_type(type_: Any)", "https://yaml.org/type/bool.html YAML_BOOL_TYPES = [ \"y\", \"Y\", \"yes\", \"Yes\", \"YES\", \"n\",", "if value == attr.NOTHING: value = MISSING if _is_union(type_): e", "\"b\"] \"\"\" # Obtain the first part of the key", "None: key_type = args[0] element_type = args[1] else: key_type =", "obj.items(): is_optional, type_ = _resolve_optional(element_type) type_ = _resolve_forward(type_, obj.__module__) try:", "(ex: \"esc: \\${bar}\") are identified as # interpolations: this is", "not None: et = _resolve_forward(et, module=module) return List[et] # type:", "full_key = node._get_full_key(key=key) except Exception as exc: # Since we", "et = get_list_element_type(type_) if et is not None: et =", "for field in dataclasses.fields(obj): name = field.name is_optional, type_ =", "for key, resolvers in loader.yaml_implicit_resolvers.items() } return loader def _get_class(path:", "type_ in (int, float, bool, str, type(None)) def _is_interpolation(v: Any,", "class instance]\" ) return target def is_generic_list(type_: Any) -> bool:", "bool: # Uses literal '???' instead of the MISSING const", "else: value = field.default_factory() # type: ignore if _is_union(type_): e", "We identify potential interpolations by the presence of \"${\" in", "# pragma: no cover dataclasses = None # type: ignore", "} return loader def _get_class(path: str) -> type: from importlib", "\"???\" def _is_none( value: Any, resolve: bool = False, throw_on_resolution_failure:", "None: vt = _resolve_forward(vt, module=module) return Dict[kt, vt] # type:", "reference_type=$REF_TYPE object_type=$OBJECT_TYPE\"\"\" ) else: template = dedent( \"\"\"\\ $MSG full_key:", "return klass def _is_union(type_: Any) -> bool: return getattr(type_, \"__origin__\",", "d[name] = _maybe_wrap( ref_type=type_, is_optional=is_optional, key=name, value=value, parent=dummy_parent, ) except", "that a key starting with brackets, like [a], is purposedly", "not None else \"\" object_type = None ref_type = None", "anything except `.` or `[` (ex: .b, .d) # -", "assert isinstance(target, (list, dict)) target = OmegaConf.create(target, flags=flags) elif is_structured_config(target):", "or is_structured_config(type_) def _valid_dict_key_annotation_type(type_: Any) -> bool: from omegaconf import", "# be read as a choice between two syntaxes: #", "None: full_key = key if key is not None else", "Containers as is return value def get_ref_type(obj: Any, key: Any", "kind of a value Examples: VALUE: \"10\", \"20\", True MANDATORY_MISSING:", "exception. env_var = os.environ[\"OC_CAUSE\"] if \"OC_CAUSE\" in os.environ else None", "import dataclasses except ImportError: # pragma: no cover dataclasses =", "Config classes is deprecated,\" + \" see github.com/omry/omegaconf/issues/663\", UserWarning, stacklevel=9,", "is_type = isinstance(obj, type) obj_type = obj if is_type else", "head (in these examples: a, a, ..a). # This can", "-> Any: from .base import Container from .nodes import ValueNode", "None and not node._is_none(): child_node = node._get_node(key, validate_access=False) try: full_key", "import Node if isinstance(value, Node): value = value._value() return _is_missing_literal(value)", "def _resolve_forward(type_: Type[Any], module: str) -> Type[Any]: import typing #", "Node if attr is None or isinstance(obj, Node): return False", "to classify. :param strict_interpolation_validation: If `True`, then when `value` is", "name) else: value = attrib.default if value == attr.NOTHING: value", "keys = set() for key_node, value_node in node.value: if key_node.tag", "None: args = \", \".join( [type_str(t, include_module_name=include_module_name) for t in", "`.` followed by anything except `.` or `[` (ex: .b,", "MISSING else: value = field.default_factory() # type: ignore if _is_union(type_):", "be read as \"dots followed by any character but `.`", "and args[1] == type(None): # noqa E721 return True, args[0]", "ref_type is None or ref_type == Dict: key_type = Any", "special case where the first key starts with brackets, e.g.", "-> Any: args = getattr(ref_type, \"__args__\", None) if ref_type is", "type: {type(obj).__name__}\") class ValueKind(Enum): VALUE = 0 MANDATORY_MISSING = 1", "We begin by matching the head (in these examples: a,", "OmegaConfBaseException): ex._initialized = True ex.msg = message ex.parent_node = node", "-> Type[OmegaConfDumper]: if not OmegaConfDumper.str_representer_added: OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer) OmegaConfDumper.str_representer_added = True", "else bracket_key for dot_key, bracket_key in others] return tokens #", "if is_dataclass(obj): return get_dataclass_data(obj, allow_objects=allow_objects) elif is_attr_class(obj): return get_attr_data(obj, allow_objects=allow_objects)", "its individual components. This is similar to `key.split(\".\")` but also", "= {} obj_type = get_type_of(obj) dummy_parent = OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type", "None and isinstance(type_, type) and issubclass(type_, Dict) def is_dict(obj: Any)", "to {type(exc).__name__}: {exc}>\" object_type = OmegaConf.get_type(node) object_type_str = type_str(object_type) ref_type", "= None) -> Any: from omegaconf import OmegaConf if is_primitive_container(target):", "\"builtins\" and t.__module__ != \"typing\" and not t.__module__.startswith(\"omegaconf.\") ): module_prefix", "not None: name = type_str(t.__origin__) else: name = str(t) if", "two syntaxes: # - `.` followed by anything except `.`", "`[` (ex: .b, .d) # - `[` followed by anything", "# pragma: no cover # Regexprs to match key paths", "= 2 def _is_missing_value(value: Any) -> bool: from omegaconf import", "ref_type == Dict: key_type = Any element_type = Any else:", "no cover # Python 3.6 if hasattr(t, \"__name__\"): name =", "is Any: return \"Any\" if t is ...: return \"...\"", "Python >= 3.7 if hasattr(t, \"__name__\"): name = str(t.__name__) else:", "-> tokens = [\"\", \"\", \"\"] but we would like", "that. # noinspection PyProtectedMember return type_.__setattr__ == attr._make._frozen_setattrs # type:", "= ref_type ex.ref_type_str = ref_type_str _raise(ex, cause) def type_str(t: Any,", "not None first_stop = first.span()[1] # `tokens` will contain all", "in `ListConfig.append` and `ListConfig.insert` # where the appended/inserted value might", "-> bool: from omegaconf.base import Node if dataclasses is None", "def get_attr_class_field_names(obj: Any) -> List[str]: is_type = isinstance(obj, type) obj_type", "in (int, float, bool, str, type(None)) def _is_interpolation(v: Any, strict_interpolation_validation:", "# Resolution failure: consider that it is *not* None. return", "= args[1] else: key_type = Any element_type = Any return", "interpolations will only be detected when # `strict_interpolation_validation` is True.", "OmegaConfBaseException) and cause._initialized: ex = cause if type_override is not", "should be used instead, # once support for Python 3.6", "t.__args__] ) ret = f\"{name}[{args}]\" else: ret = name if", "\"__name__\"): name = str(t.__name__) else: if t._name is None: if", "-> bool: type_ = get_type_of(obj) if is_dataclass(type_): return is_dataclass_frozen(type_) if", "dedent( \"\"\"\\ $MSG full_key: $FULL_KEY reference_type=$REF_TYPE object_type=$OBJECT_TYPE\"\"\" ) else: template", "return loader def _get_class(path: str) -> type: from importlib import", "= type_override(str(cause)) ex.__dict__ = copy.deepcopy(cause.__dict__) _raise(ex, cause) object_type: Optional[Type[Any]] object_type_str:", "import Container from .nodes import ValueNode if isinstance(value, ValueNode): return", "allow_objects: Optional[bool] = None ) -> Dict[str, Any]: if is_dataclass(obj):", "len(get_dict_key_value_types(type_)) > 0 def is_container_annotation(type_: Any) -> bool: return is_list_annotation(type_)", "subclasses_dict: warnings.warn( f\"Class `{obj_type.__name__}` subclasses `Dict`.\" + \" Subclassing `Dict`", "examples: a, a, .a, '') first = KEY_PATH_HEAD.match(key) assert first", "= ref_type_str _raise(ex, cause) def type_str(t: Any, include_module_name: bool =", "Tuple, Type, Union, get_type_hints, ) import yaml from .errors import", "areas it may be dropped. typed_dict = hasattr(type_, \"__base__\") and", "has no other component: we are done. if first_stop ==", "node ex.child_node = child_node ex.key = key ex.full_key = full_key", "one for keys starting with a bracket ([b], [c]). #", "return None elif subclasses_dict: dict_subclass_data = {} key_type, element_type =", "# To be used as default value when `None` is", "it may be dropped. typed_dict = hasattr(type_, \"__base__\") and type_.__base__", "bool: try: float(st) return True except ValueError: return False def", "f\"<unresolvable due to {type(exc).__name__}: {exc}>\" object_type = OmegaConf.get_type(node) object_type_str =", "tokens = [\"\"] but we would like [] # ..[a]", "isinstance(type_, type) return type_ def is_structured_config_frozen(obj: Any) -> bool: type_", "ex.parent_node = node ex.child_node = child_node ex.key = key ex.full_key", "def get_list_element_type(ref_type: Optional[Type[Any]]) -> Any: args = getattr(ref_type, \"__args__\", None)", "return False def get_structured_config_field_names(obj: Any) -> List[str]: if is_dataclass(obj): return", ":return: bool \"\"\" return is_list_annotation(type_) and get_list_element_type(type_) is not None", "None: from omegaconf import OmegaConf from omegaconf.base import Node if", "OmegaConf.create({}, flags=flags) dummy_parent._metadata.object_type = obj_type for name, attrib in attr.fields_dict(obj_type).items():", "Optional[bool] = None ) -> Dict[str, Any]: from omegaconf.omegaconf import", "= ( get_value_kind(v, strict_interpolation_validation) == ValueKind.INTERPOLATION ) assert isinstance(ret, bool)", "VALUE: \"10\", \"20\", True MANDATORY_MISSING: \"???\" INTERPOLATION: \"${foo.bar}\", \"${foo.${bar}}\", \"${foo:bar}\",", "`[`\" # Note that a key starting with brackets, like", "need to get rid of: # [a] -> tokens =", "is_primitive_dict(obj) or is_dict_annotation(obj) or is_dict_subclass(obj) def is_primitive_container(obj: Any) -> bool:", "Supports one of \" + \"[dict,list,DictConfig,ListConfig,dataclass,dataclass instance,attr class,attr class instance]\"", "deprecated,\" + \" see github.com/omry/omegaconf/issues/663\", UserWarning, stacklevel=9, ) if is_type:", "= class_or_object if not isinstance(type_, type): type_ = type(class_or_object) assert", "one for keys starting # with a dot (.b, .d)", "attrib in attr.fields_dict(obj_type).items(): is_optional, type_ = _resolve_optional(attrib.type) type_ = _resolve_forward(type_,", "might or might not be a Node. return True def", "hard to detect. # this support is tentative, if it", "f\"{name}[{args}]\" else: ret = name if include_module_name: if ( hasattr(t,", "= [ \"y\", \"Y\", \"yes\", \"Yes\", \"YES\", \"n\", \"N\", \"no\",", "type: ignore def get_type_of(class_or_object: Any) -> Type[Any]: type_ = class_or_object", "False def _get_value(value: Any) -> Any: from .base import Container", "False ) -> ValueKind: \"\"\" Determine the kind of a" ]
[ "config, looking for master parset\") # Load the parset from", "Cluster triggers and run IQUV and/or LOFAR triggering :param list", "getting lost with self.lock: triggers = self.amber_triggers self.amber_triggers = []", "yet, next possible time: {}\".format(self.time_iquv)) else: self.logger.info(\"Sending IQUV trigger\") #", "if HADEC is used if parset['task.directionReferenceFrame'].upper() == 'HADEC': # Get", "mask = np.array(cluster_downsamp) <= width_max cluster_snr = np.array(cluster_snr)[mask] cluster_dm =", "specific sources if src_name in self.lofar_trigger_sources: # check CB number", "not LOFAR triggering should be enabled for new sources if", "DM unit = 1 ms delay across band dm_err =", "and decode raw_parset = util.decode_parset(master_config['parset']) parset = util.parse_parset(raw_parset) except Exception", "e: self.logger.warning( \"Failed to load parset from master config file", "also works if there is one trigger, so just run", "is available if pointing is None: self.logger.error(\"No pointing information available", "create mapping to col index keys = ['beam_id', 'integration_step', 'time',", "not found pass else: # replace source by alias so", "time import sleep import yaml import ast import threading import", "no observation is running - ignoring\") else: with self.lock: self.amber_triggers.append(command['trigger'])", "any trigger starting with #) triggers = [trigger for trigger", "to VO server if enabled # always do this in", "darc import util class AMBERClusteringException(Exception): pass class AMBERClustering(DARCBase): \"\"\" Trigger", "decimal deg 'dec': pointing.dec.deg, # decimal deg 'cb': self.obs_config['beam'], 'sb':", "import SkyCoord from darc import DARCBase, VOEventQueueServer, LOFARTriggerQueueServer from darc.definitions", "BANDWIDTH.to(u.MHz).value dm_delay = 4.148808E3 * dm_to_send * (cent_freq**-2 - max_freq**-2)", ":param dict command: Command to process \"\"\" if command['command'] ==", "triggers_for_clustering = triggers[:, (self.hdr_mapping['DM'], self.hdr_mapping['SNR'], self.hdr_mapping['time'], self.hdr_mapping['integration_step'], self.hdr_mapping['beam_id'])] # known", "or frb dm_src = None src_type = None for key", "for header (always, because it is received once for every", "command): \"\"\" Process command received from queue :param dict command:", "parse parset obs_config['parset'] = self._load_parset(obs_config) # set config self.obs_config =", "LOFAR trigger serverr if enabled # always do this in", "dict sys_params: System parameters (dt, delta_nu_MHz, nu_GHz) :param str utc_start:", "None) :param bool skip_lofar: Skip LOFAR triggering (default: False) \"\"\"", "**sys_params) # select on width mask = np.array(cluster_downsamp) <= width_max", "keeps track of when LOFAR triggers were sent # and", "triggers from queue and start processing for known and/or new", "< self.time_iquv: self.logger.warning(\"Cannot trigger IQUV yet, next possible time: {}\".format(self.time_iquv))", "system\") self.vo_queue.put(lofar_trigger) else: self.logger.error(\"No VOEvent Generator connection available - not", "'src_type': src_type, 'src_name': src_name, 'dm_min': max(dm_src - self.dm_range, self.dm_min_global), 'dm_max':", "if available if dm_src is not None: dm_to_send = dm_src", "= (BANDWIDTH / float(NCHAN)).to(u.MHz).value cent_freq = (self.obs_config['min_freq'] * u.MHz +", "and max DM for new sources with unknown DM thresh_new", "Canceling processing\") continue # split strings and convert to numpy", "in thread so clustering itself does not # delay next", "always ind = np.argmax(cluster_snr[mask]) # estimate flux density based on", "{dm_min} - {dm_max}, \" \"max downsamp={width_max}, min S/N={snr_min}\".format(**thresh_src)) # set", "datetimesource, 'utc': utc_arr, 'tarr': cluster_time[mask][ind], 'importance': 0.1} # add system", "self.logger) # get known source dm and type dm_src, src_type,", "triggers, sys_params, utc_start, datetimesource, dm_min=0, dm_max=np.inf, dm_src=None, width_max=np.inf, snr_min=8, src_type=None,", "max_cands_per_cluster = np.inf # Overrides for specific sources if src_name", "CB number try: allowed_cbs = self.thresh_lofar_override['cb'] if isinstance(allowed_cbs, float): allowed_cbs", "src_name in self.lofar_trigger_sources: thresh_new['skip_lofar'] = not self.thresh_lofar['trigger_on_new_sources'] else: thresh_new['skip_lofar'] =", "central freq (GHz), bandwidth (MHz)) lofar_trigger.update(sys_params) self.logger.info(\"Sending LOFAR trigger to", "self.thresh_iquv['dm_frac_min'], self.dm_min_global), 'dm_max': np.inf, 'width_max': self.thresh_iquv['width_max'], 'snr_min': self.thresh_iquv['snr_min'], 'pointing': pointing,", "continue # split strings and convert to numpy array try:", "Observation config :return: parset as dict \"\"\" try: # encoded", "the full trigger and put on VO queue lofar_trigger =", "command received: {}\".format(command['command'])) def start_observation(self, obs_config, reload=True): \"\"\" Parse obs", "(default: 8) :param str src_type: Source type (pulsar, frb, None)", "in keys: try: self.hdr_mapping[key] = header.index(key) except ValueError: self.logger.error(\"Key missing", "is empty if only header was received if not triggers:", "/ VOEvent system based on AMBER candidates 1. Cluster incoming", "Cluster incoming triggers 2. Apply thresholds (separate for known and", "# # AMBER Clustering import os from time import sleep", "new source, apply all LOFAR thresholds snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar", "def _load_source_list(self): \"\"\" Load the list with known source DMs", ":param str utc_start: start time of observation, in format readable", "below to work # no limit on candidates per cluster", "last trigger time self.time_iquv = now + TimeDelta(self.thresh_iquv['interval'], format='sec') #", "one trigger, so just run it always ind = np.argmax(cluster_snr[mask])", "as e: self.logger.error(\"Cannot read beam from parset, setting CB to", "IQUV / LOFAR triggering self.time_iquv = Time.now() # connect to", "'utc_start': utc_start} dada_triggers.append(dada_trigger) self.target_queue.put({'command': 'trigger', 'trigger': dada_triggers}) # skip LOFAR", "cluster_dm[mask][ind] # set DM uncertainty to DM delay across pulse", "# check if source is a known pulsar or frb", "if src_name in self.lofar_trigger_sources: # check CB number try: allowed_cbs", "cluster_time[i], 'utc_start': utc_start} dada_triggers.append(dada_trigger) self.target_queue.put({'command': 'trigger', 'trigger': dada_triggers}) # skip", "src_name: Source name (default: None) :param float dmgal: galactic maximum", "VOEvent system\") self.vo_queue.put(lofar_trigger) else: self.logger.error(\"No VOEvent Generator connection available -", ".5 * float(parset['task.duration']) * u.s c1, c2 = util.radec_to_hadec(c1, c2,", "src_type == 'pulsar' or skip_lofar: return # select LOFAR thresholds", "self.have_vo = False # connect to LOFAR trigger if self.connect_lofar:", "e: raise AMBERClusteringException(\"Cannot load source list: {}\".format(e)) return source_list def", "command['command'] == 'trigger': if not self.observation_running: self.logger.error(\"Trigger(s) received but no", "{}\".format(key)) self.hdr_mapping = {} return # header should be present", "the master node \"\"\" # Load LOFAR trigger server settings", "'datetimesource': datetimesource, 'utc': utc_arr, 'tarr': cluster_time[mask][ind], 'importance': 0.1} # add", "as u from astropy.coordinates import SkyCoord from darc import DARCBase,", "CB from parset :return: pointing SkyCoord \"\"\" # read parset", "command['command'] == 'get_attr': self.get_attribute(command) else: self.logger.error(\"Unknown command received: {}\".format(command['command'])) def", "self.logger.error(\"Cannot get source name from parset, will not do known-source", "trigger serverr if enabled # always do this in case", "dm_to_send, 'beam': cluster_sb[i], 'width': cluster_downsamp[i], 'snr': cluster_snr[i], 'time': cluster_time[i], 'utc_start':", "candidates is too high (this indicates RFI) mask = (cluster_snr", "triggering should be enabled for new sources if src_type is", "Load the list with known source DMs :return: source list", "except Exception as e: self.logger.warning( \"Failed to load parset from", "not None: dm_to_send = dm_src else: dm_to_send = cluster_dm[i] dada_trigger", "else: known = 'new' self.logger.info(\"Clustered {} raw triggers into {}", "before, but failed at some point if self.connect_vo: try: self.vo_queue", "and width snr = cluster_snr[mask][ind] width = TSAMP.to(u.ms) * cluster_downsamp[mask][ind]", "thresholds (separate for known and new sources, and for IQUV", "obs_config['parset'] = self._load_parset(obs_config) # set config self.obs_config = obs_config self.observation_running", "array try: triggers = np.array(list(map(lambda val: val.split(), triggers)), dtype=float) except", "cluster_downsamp = np.array(cluster_downsamp)[mask].astype(int) cluster_sb = np.array(cluster_sb)[mask].astype(int) ncand_per_cluster = np.array(ncand_per_cluster)[mask].astype(int) ncluster", "if src_type == 'pulsar' or skip_lofar: return # select LOFAR", "source, apply all LOFAR thresholds snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar =", "create SkyCoord object pointing = SkyCoord(c1, c2) return pointing def", "get source name from parset, will not do known-source triggering\")", "'snr': cluster_snr[i], 'time': cluster_time[i], 'utc_start': utc_start} dada_triggers.append(dada_trigger) self.target_queue.put({'command': 'trigger', 'trigger':", "if parset['task.directionReferenceFrame'].upper() == 'HADEC': # Get RA at the mid", "mask = line below to work # no limit on", "VOEvent Generator expects Jy flux = util.get_flux(snr, width).to(u.mJy).value / 1000.", "ind = np.argmax(cluster_snr[mask]) # estimate flux density based on peak", "\\ (cluster_downsamp <= width_max_lofar) & \\ (ncand_per_cluster <= max_cands_per_cluster) #", "{}\".format(header)) # Check if all required params are present and", "not None: self.threads['trigger_known_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_src)", "connect to LOFAR trigger queue on master node \"\"\" super(AMBERClustering,", "# get known source dm and type dm_src, src_type, src_name", "server elif not self.have_lofar: self.logger.error(\"No LOFAR Trigger connection available -", "[allowed_cbs] if self.obs_config['beam'] not in allowed_cbs: return except KeyError: #", "IQUV vs LOFAR) 3. Put IQUV triggers on output queue", "reload config if reload: self.load_config() # clean any old triggers", "False self.amber_triggers = [] self.source_list = None self.lock = mp.Lock()", "running to false self.observation_running = False # clear triggers self.amber_triggers", "on candidates per cluster snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar = dm_min", "KeyError: # any CB is valid if cb key is", "not self.have_lofar: self.logger.error(\"No LOFAR Trigger connection available - cannot trigger", "* u.deg c2 = c2 * u.deg except Exception as", "None: known = 'known' else: known = 'new' self.logger.info(\"Clustered {}", "cluster_downsamp[i], 'snr': cluster_snr[i], 'time': cluster_time[i], 'utc_start': utc_start} dada_triggers.append(dada_trigger) self.target_queue.put({'command': 'trigger',", "and new source triggering, in thread so clustering itself does", "dm_max=np.inf, dm_src=None, width_max=np.inf, snr_min=8, src_type=None, src_name=None, dmgal=0, pointing=None, skip_lofar=False): \"\"\"", "dict and store parset = util.parse_parset(raw_parset) except KeyError: self.logger.info(\"Observation parset", "there is one trigger, so just run it always ind", "can do triggering now = Time.now() if now < self.time_iquv:", "src_type: Source type (pulsar, frb, None) :param str src_name: Source", "if not self.observation_running: self.logger.error(\"Trigger(s) received but no observation is running", "AMBERClusteringException(Exception): pass class AMBERClustering(DARCBase): \"\"\" Trigger IQUV / LOFAR /", "mid point of the observation timestamp = Time(parset['task.startTime']) + .5", "queue self.logger.info(\"VO Generator connection disabled, setting dummy queue\") self.vo_queue =", "= self.amber_triggers self.amber_triggers = [] # check for header (always,", "= 0. else: dm_to_send = cluster_dm[mask][ind] # set DM uncertainty", "connecting to VO server if enabled # always do this", "known source, use same DM threshold as IQUV, but apply", "as e: self.logger.error(\"Failed to connect to VOEvent Generator, setting dummy", "number try: allowed_cbs = self.thresh_lofar_override['cb'] if isinstance(allowed_cbs, float): allowed_cbs =", "= server_config['server_auth'].encode() server = VOEventQueueServer(address=(MASTER, port), authkey=key) server.connect() return server.get_queue()", "self.logger.info(\"Found {} possible LOFAR trigger(s)\".format(ncluster)) # note: the server keeps", "= np.array(cluster_downsamp) <= width_max cluster_snr = np.array(cluster_snr)[mask] cluster_dm = np.array(cluster_dm)[mask]", "there are clusters, do IQUV triggering # check if we", "available before, but failed at some point if self.connect_vo: try:", "src_name=None, dmgal=0, pointing=None, skip_lofar=False): \"\"\" Cluster triggers and run IQUV", "snr_min: mininum S/N (default: 8) :param str src_type: Source type", "per category \"\"\" try: with open(self.source_file, 'r') as f: source_list", "min S/N={snr_min}, skip LOFAR \" \"triggering={skip_lofar}\".format(**thresh_new)) # main loop while", "else: with self.lock: self.amber_triggers.append(command['trigger']) elif command['command'] == 'get_attr': self.get_attribute(command) else:", "or skip_lofar: return # select LOFAR thresholds if src_type is", "received but header not found\") continue # remove headers from", "/ TIME_UNIT, format='unix') datetimesource = self.obs_config['datetimesource'] dt = TSAMP.to(u.second).value chan_width", "= 0 # read beam coordinates from parset try: key", "# Overrides for specific sources if src_name in self.lofar_trigger_sources: #", "failed at some point if self.connect_lofar: try: self.lofar_queue = self.lofar_connector()", "= Time(self.obs_config['startpacket'] / TIME_UNIT, format='unix') datetimesource = self.obs_config['datetimesource'] dt =", "peak S/N and width snr = cluster_snr[mask][ind] width = TSAMP.to(u.ms)", "we are allowed to do IQUV / LOFAR triggering self.time_iquv", "np.array(cluster_downsamp) <= width_max cluster_snr = np.array(cluster_snr)[mask] cluster_dm = np.array(cluster_dm)[mask] cluster_time", "up in other lists self.logger.info(\"Using alias {} for source {}\".format(alias,", "self.lofar_queue = self.dummy_queue self.have_lofar = False else: # dummy queue", "load parset from master config file {}, \" \"setting parset", "pointing.ra.deg, # decimal deg 'dec': pointing.dec.deg, # decimal deg 'cb':", "(i.e. any trigger starting with #) triggers = [trigger for", "server settings VOEventQueueServer.register('get_queue') with open(self.config_file, 'r') as f: server_config =", "we are connected to the server elif not self.have_lofar: self.logger.error(\"No", "{} # clear config self.obs_config = None # clear threads", "in thread self.threads['processing'] = threading.Thread(target=self._process_triggers) self.threads['processing'].start() self.logger.info(\"Observation started\") def stop_observation(self,", "to LOFAR trigger queue on master node \"\"\" super(AMBERClustering, self).__init__(*args,", "None # convert HA to RA if HADEC is used", "'IQUV', 'dm': dm_to_send, 'beam': cluster_sb[i], 'width': cluster_downsamp[i], 'snr': cluster_snr[i], 'time':", "config self.obs_config = None # clear threads for key, thread", "dm if available if dm_src is not None: dm_to_send =", "return server.get_queue() def lofar_connector(self): \"\"\" Connect to the LOFAR triggering", "has roughly 1 DM unit = 1 ms delay across", "to col index keys = ['beam_id', 'integration_step', 'time', 'DM', 'SNR']", "VOEventQueueServer.register('get_queue') with open(self.config_file, 'r') as f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['voevent_generator']", "cannot trigger LOFAR\") # do the trigger else: # create", "parameters (dt, central freq (GHz), bandwidth (MHz)) lofar_trigger.update(sys_params) self.logger.info(\"Sending LOFAR", "util.get_flux(snr, width).to(u.mJy).value / 1000. # select known source DM if", "arrival time at reference frequency = central frequency cent_freq =", "based on AMBER candidates 1. Cluster incoming triggers 2. Apply", "server = LOFARTriggerQueueServer(address=(MASTER, port), authkey=key) server.connect() return server.get_queue() def _get_source(self):", "* self.thresh_iquv['dm_frac_min'], self.dm_min_global), 'dm_max': np.inf, 'width_max': self.thresh_iquv['width_max'], 'snr_min': self.thresh_iquv['snr_min'], 'pointing':", ":return: source list with dict per category \"\"\" try: with", "thread in self.threads.items(): if thread is not None: thread.join() self.threads[key]", "= trigger.split()[1:] self.logger.info(\"Received header: {}\".format(header)) # Check if all required", "this in case a connection was available before, but failed", "# pick columns to feed to clustering algorithm triggers_for_clustering =", "return # there are clusters, do IQUV triggering # check", "trigger DM range to {dm_min} - {dm_max}, \" \"max downsamp={width_max},", "known and/or new sources \"\"\" # set observation parameters utc_start", "if we can do triggering now = Time.now() if now", "available if pointing is None: self.logger.error(\"No pointing information available -", "False else: # dummy queue self.logger.info(\"LOFAR Trigger connection disabled, setting", "except KeyError as e: self.logger.error(\"Cannot read beam from parset, setting", "# astropy units only knows mJy, but the VOEvent Generator", "src_type=None, src_name=None, dmgal=0, pointing=None, skip_lofar=False): \"\"\" Cluster triggers and run", "= True # (re)load source list in case of changes", "def stop_observation(self, *args, **kwargs): \"\"\" Stop observation \"\"\" # set", "util.radec_to_hadec(c1, c2, timestamp) # create SkyCoord object pointing = SkyCoord(c1,", "with dict per category \"\"\" try: with open(self.source_file, 'r') as", "to LOFAR Trigger on master node\") self.have_lofar = True except", "triggers is empty if only header was received if not", "= util.parse_parset(raw_parset) except Exception as e: self.logger.warning( \"Failed to load", "clear triggers self.amber_triggers = [] # clear header self.hdr_mapping =", "self.have_lofar = False def _load_source_list(self): \"\"\" Load the list with", "encoded parset is already in config on master node #", "by alias so we can look it up in other", "'pointing': pointing, 'dmgal': dmgal } # if known source, check", "settings LOFARTriggerQueueServer.register('get_queue') with open(self.config_file, 'r') as f: server_config = yaml.load(f,", "cluster_sb = np.array(cluster_sb)[mask].astype(int) ncand_per_cluster = np.array(ncand_per_cluster)[mask].astype(int) ncluster = len(cluster_snr) if", "thread.join() self.threads[key] = None def voevent_connector(self): \"\"\" Connect to the", "settings VOEventQueueServer.register('get_queue') with open(self.config_file, 'r') as f: server_config = yaml.load(f,", "dada_triggers.append(dada_trigger) self.target_queue.put({'command': 'trigger', 'trigger': dada_triggers}) # skip LOFAR triggering for", "except ValueError: self.logger.error(\"Key missing from clusters header: {}\".format(key)) self.hdr_mapping =", "check CB number try: allowed_cbs = self.thresh_lofar_override['cb'] if isinstance(allowed_cbs, float):", "VOEvent generator if self.connect_vo: try: self.vo_queue = self.voevent_connector() self.logger.info(\"Connected to", "= cluster_dm[i] dada_trigger = {'stokes': 'IQUV', 'dm': dm_to_send, 'beam': cluster_sb[i],", "def _check_triggers(self, triggers, sys_params, utc_start, datetimesource, dm_min=0, dm_max=np.inf, dm_src=None, width_max=np.inf,", "= np.sum(mask) self.logger.info(\"Found {} possible LOFAR trigger(s)\".format(ncluster)) # note: the", "datetimesource), kwargs=thresh_new) self.threads['trigger_new_source'].start() sleep(self.interval) self.logger.info(\"Observation finished\") def _get_pointing(self): \"\"\" Get", "thresh_new['skip_lofar'] = not self.thresh_lofar['trigger_on_new_sources'] else: thresh_new['skip_lofar'] = False self.logger.info(\"Setting new", "triggering self.time_iquv = Time.now() # connect to VOEvent generator if", "server_config = yaml.load(f, Loader=yaml.SafeLoader)['voevent_generator'] port = server_config['server_port'] key = server_config['server_auth'].encode()", "dm_min width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster = np.inf # Overrides for", "= self._load_source_list() # try connecting to VO server if enabled", "queue\") self.vo_queue = mp.Queue() self.have_vo = False # connect to", "IQUV / LOFAR / VOEvent system based on AMBER candidates", "source = self.obs_config['parset']['task.source.name'] except KeyError: self.logger.error(\"Cannot get source name from", "\"\"\" Load the list with known source DMs :return: source", "**kwargs): \"\"\" :param bool connect_vo: Whether or not to connect", "in ['pulsars', 'frbs']: try: dm_src = self.source_list[key][source] src_type = key[:-1]", "# encoded parset is already in config on master node", "format='sec') # trigger IQUV dada_triggers = [] for i in", "looking for master parset\") # Load the parset from the", "# (re)load source list in case of changes self.source_list =", "no limit on candidates per cluster snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar", "self.time_iquv: self.logger.warning(\"Cannot trigger IQUV yet, next possible time: {}\".format(self.time_iquv)) else:", "ValueError: self.logger.error(\"Key missing from clusters header: {}\".format(key)) self.hdr_mapping = {}", "ncluster = len(cluster_snr) if src_type is not None: known =", "header should be present now if not self.hdr_mapping: self.logger.error(\"First clusters", "lost with self.lock: triggers = self.amber_triggers self.amber_triggers = [] #", "= np.array(list(map(lambda val: val.split(), triggers)), dtype=float) except Exception as e:", "'HADEC': # Get RA at the mid point of the", "triggers = [trigger for trigger in triggers if not trigger.startswith('#')]", "e)) return None # convert HA to RA if HADEC", "not None: name = src_type else: name = 'candidate' #", "present now if not self.hdr_mapping: self.logger.error(\"First clusters received but header", "# cluster using IQUV thresholds # LOFAR thresholds are assumed", "master node\") self.have_vo = True except Exception as e: self.logger.error(\"Failed", "Generator connection available - not sending VO trigger\") def _process_triggers(self):", "triggers if ncluster > 1: self.logger.info(\"Multiple triggers - selecting trigger", "self.threads.items(): if thread is not None: thread.join() self.threads[key] = None", "DM thresh_new = {'src_type': None, 'src_name': None, 'dm_min': max(dmgal *", "else: dm_to_send = cluster_dm[i] dada_trigger = {'stokes': 'IQUV', 'dm': dm_to_send,", "\"\"\" def __init__(self, *args, connect_vo=True, connect_lofar=True, **kwargs): \"\"\" :param bool", "to RA if HADEC is used if parset['task.directionReferenceFrame'].upper() == 'HADEC':", "# check CB number try: allowed_cbs = self.thresh_lofar_override['cb'] if isinstance(allowed_cbs,", "# do the trigger else: # create the full trigger", "dummy queue ({})\".format(e)) self.vo_queue = self.dummy_queue self.have_vo = False #", "'integration_step', 'time', 'DM', 'SNR'] for key in keys: try: self.hdr_mapping[key]", "= self._load_parset(obs_config) # set config self.obs_config = obs_config self.observation_running =", "'candidate' # check whether or not pointing information is available", "parset and decode raw_parset = util.decode_parset(master_config['parset']) parset = util.parse_parset(raw_parset) except", "return server.get_queue() def _get_source(self): \"\"\" Try to get DM for", "known source dm and type dm_src, src_type, src_name = self._get_source()", "TimeDelta(self.thresh_iquv['interval'], format='sec') # trigger IQUV dada_triggers = [] for i", "self.have_lofar = False # process triggers in thread self.threads['processing'] =", "if src_type is not None: # known source, use same", "amber instance) if not self.hdr_mapping: for trigger in triggers: if", "def _get_pointing(self): \"\"\" Get pointing of this CB from parset", "\"\"\" super(AMBERClustering, self).__init__(*args, **kwargs) self.connect_vo = connect_vo self.connect_lofar = connect_lofar", "no clusters if ncluster == 0: return # there are", "try connecting to LOFAR trigger serverr if enabled # always", "trigger LOFAR\") # do the trigger else: # create the", "None src_type = None for key in ['pulsars', 'frbs']: try:", "width_max_lofar) & \\ (ncand_per_cluster <= max_cands_per_cluster) # check for any", "decimal deg 'cb': self.obs_config['beam'], 'sb': cluster_sb[mask][ind], 'ymw16': dmgal, 'semiMaj': 15,", "DM delay across pulse width # Apertif has roughly 1", "dm_min: minimum DM (default: 0) :param float dm_max: maximum DM", "if reload: self.load_config() # clean any old triggers self.amber_triggers =", "Continuously read AMBER triggers from queue and start processing for", "sb_filter_period_max=self.sb_filter_period_max, **sys_params) # select on width mask = np.array(cluster_downsamp) <=", "to {dm_min} - {dm_max}, \" \"max downsamp={width_max}, min S/N={snr_min}, skip", "to be more strict for every parameter cluster_snr, cluster_dm, cluster_time,", "triggers: if trigger.startswith('#'): # read header, remove comment symbol header", "source :return: DM for known source, else None \"\"\" #", "queue ({})\".format(e)) self.lofar_queue = self.dummy_queue self.have_lofar = False # process", "Overrides for specific sources if src_name in self.lofar_trigger_sources: # check", "trigger.startswith('#')] # triggers is empty if only header was received", "#) triggers = [trigger for trigger in triggers if not", "(default: None) :param bool skip_lofar: Skip LOFAR triggering (default: False)", "the VOEvent Generator expects Jy flux = util.get_flux(snr, width).to(u.mJy).value /", "not trigger.startswith('#')] # triggers is empty if only header was", "self.amber_triggers: # Copy the triggers so class-wide list can receive", "only header was received if not triggers: self.logger.info(\"Only header received", "width_max_lofar)) else: # new source, apply all LOFAR thresholds snr_min_lofar", "# DM_min effectively does nothing here because the value is", "if there is one trigger, so just run it always", "{}\".format(self.time_iquv)) else: self.logger.info(\"Sending IQUV trigger\") # update last trigger time", "# check if we are connected to the server elif", "= False self.logger.info(\"Setting new source trigger DM range to {dm_min}", ">= dm_min_lofar) & \\ (cluster_downsamp <= width_max_lofar) & \\ (ncand_per_cluster", "serverr if enabled # always do this in case a", "and convert to numpy array try: triggers = np.array(list(map(lambda val:", "of the observation timestamp = Time(parset['task.startTime']) + .5 * float(parset['task.duration'])", "to dict master_config = util.parse_parset(master_config) # extract obs parset and", "None: # known source, use same DM threshold as IQUV,", "src_name = self._get_source() if src_type is not None: thresh_src =", "'dm_max': dm_src + self.dm_range, 'width_max': np.inf, 'snr_min': self.snr_min_global, 'pointing': pointing,", "# clean any old triggers self.amber_triggers = [] # parse", "float dmgal: galactic maximum DM :param astropy.coordinates.SkyCoord pointing: Pointing for", "c1 * u.deg c2 = c2 * u.deg except Exception", "VOEventQueueServer(address=(MASTER, port), authkey=key) server.connect() return server.get_queue() def lofar_connector(self): \"\"\" Connect", "trigger(s) \" \"for {} source\".format(len(triggers), ncluster, known)) # return if", "open(self.config_file, 'r') as f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['voevent_generator'] port =", "setting dummy queue ({})\".format(e)) self.vo_queue = self.dummy_queue self.have_vo = False", "so clustering itself does not # delay next run #", "ncluster > 1: self.logger.info(\"Multiple triggers - selecting trigger with highest", "frequency = central frequency cent_freq = sys_params['nu_GHz'] * 1000. max_freq", "\"max downsamp={width_max}, min S/N={snr_min}\".format(**thresh_src)) # set min and max DM", "thread is not None: thread.join() self.threads[key] = None def voevent_connector(self):", "# main loop while self.observation_running: if self.amber_triggers: # Copy the", "not self.hdr_mapping: for trigger in triggers: if trigger.startswith('#'): # read", "# clear triggers self.amber_triggers = [] # clear header self.hdr_mapping", "KeyError as e: self.logger.error(\"Cannot read beam from parset, setting CB", "in triggers if not trigger.startswith('#')] # triggers is empty if", "+ self.dm_range, 'width_max': np.inf, 'snr_min': self.snr_min_global, 'pointing': pointing, 'dmgal': dmgal", "except KeyError: # any CB is valid if cb key", "# Convert to dict master_config = util.parse_parset(master_config) # extract obs", ":param dict obs_config: Observation config :return: parset as dict \"\"\"", "f: source_list = yaml.load(f, Loader=yaml.SafeLoader) except OSError as e: raise", "{src_name} trigger DM range to {dm_min} - {dm_max}, \" \"max", "triggers - selecting trigger with highest S/N\") # argmax also", "range to {dm_min} - {dm_max}, \" \"max downsamp={width_max}, min S/N={snr_min}\".format(**thresh_src))", "np.sum(mask) self.logger.info(\"Found {} possible LOFAR trigger(s)\".format(ncluster)) # note: the server", "source trigger DM range to {dm_min} - {dm_max}, \" \"max", "reload: self.load_config() # clean any old triggers self.amber_triggers = []", "not self.hdr_mapping: self.logger.error(\"First clusters received but header not found\") continue", "sleep import yaml import ast import threading import multiprocessing as", "# delay next run # known source triggering if src_type", "self.time_iquv = now + TimeDelta(self.thresh_iquv['interval'], format='sec') # trigger IQUV dada_triggers", "'dmgal': dmgal } # if known source, check whether or", "to {dm_min} - {dm_max}, \" \"max downsamp={width_max}, min S/N={snr_min}\".format(**thresh_src)) #", "return None, None, None # check if source is in", "check whether or not pointing information is available if pointing", "valid if cb key is not present pass else: #", "else: # create the full trigger and put on VO", "dm_src is not None: dm_to_send = dm_src else: dm_to_send =", "thresh_new = {'src_type': None, 'src_name': None, 'dm_min': max(dmgal * self.thresh_iquv['dm_frac_min'],", "AMBERClustering(DARCBase): \"\"\" Trigger IQUV / LOFAR / VOEvent system based", "self.connect_vo = connect_vo self.connect_lofar = connect_lofar self.dummy_queue = mp.Queue() self.threads", "thresholds # LOFAR thresholds are assumed to be more strict", "self.vo_queue = mp.Queue() self.have_vo = False # connect to LOFAR", "__init__(self, *args, connect_vo=True, connect_lofar=True, **kwargs): \"\"\" :param bool connect_vo: Whether", "class AMBERClusteringException(Exception): pass class AMBERClustering(DARCBase): \"\"\" Trigger IQUV / LOFAR", "(cent_freq**-2 - max_freq**-2) utc_arr = (utc_start + TimeDelta(cluster_time[mask][ind] - dm_delay,", "return dm_src, src_type, source def _check_triggers(self, triggers, sys_params, utc_start, datetimesource,", "time: {}\".format(self.time_iquv)) else: self.logger.info(\"Sending IQUV trigger\") # update last trigger", "on queue :param dict obs_config: Observation configuration :param bool reload:", "python3 # # AMBER Clustering import os from time import", "parset from the master parset file master_config_file = os.path.join(obs_config['master_dir'], 'parset',", "# if known source, check whether or not LOFAR triggering", "Exception as e: self.logger.error(\"Failed to process triggers: {}\".format(e)) continue #", "return pointing def _load_parset(self, obs_config): \"\"\" Load the observation parset", "# extract obs parset and decode raw_parset = util.decode_parset(master_config['parset']) parset", "# connect to VOEvent generator if self.connect_vo: try: self.vo_queue =", "queue on master node :param bool connect_lofar: Whether or not", "np.inf # Overrides for specific sources if src_name in self.lofar_trigger_sources:", "None: thresh_src = {'dm_src': dm_src, 'src_type': src_type, 'src_name': src_name, 'dm_min':", "= ast.literal_eval(parset[key].replace('deg', '')) c1 = c1 * u.deg c2 =", "= server_config['server_auth'].encode() server = LOFARTriggerQueueServer(address=(MASTER, port), authkey=key) server.connect() return server.get_queue()", "known source DM if available if dm_src is not None:", "triggers)), dtype=float) except Exception as e: self.logger.error(\"Failed to process triggers:", "import tools from darc import util class AMBERClusteringException(Exception): pass class", "= np.array(cluster_snr)[mask] cluster_dm = np.array(cluster_dm)[mask] cluster_time = np.array(cluster_time)[mask] cluster_downsamp =", "import DARCBase, VOEventQueueServer, LOFARTriggerQueueServer from darc.definitions import TSAMP, NCHAN, BANDWIDTH,", "self._load_source_list() # try connecting to VO server if enabled #", "triggering, in thread so clustering itself does not # delay", "self.thresh_lofar_override['cb'] if isinstance(allowed_cbs, float): allowed_cbs = [allowed_cbs] if self.obs_config['beam'] not", "BANDWIDTH).to(u.GHz).value sys_params = {'dt': dt, 'delta_nu_MHz': chan_width, 'nu_GHz': cent_freq} pointing", "from darc import DARCBase, VOEventQueueServer, LOFARTriggerQueueServer from darc.definitions import TSAMP,", "on master node \"\"\" super(AMBERClustering, self).__init__(*args, **kwargs) self.connect_vo = connect_vo", "connect to LOFAR trigger if self.connect_lofar: try: self.lofar_queue = self.lofar_connector()", "cluster_sb[i], 'width': cluster_downsamp[i], 'snr': cluster_snr[i], 'time': cluster_time[i], 'utc_start': utc_start} dada_triggers.append(dada_trigger)", "dmgal, 'semiMaj': 15, # arcmin, CB 'semiMin': 15, # arcmin,", "0 ({})\".format(e)) beam = 0 # read beam coordinates from", "at some point if self.connect_vo: try: self.vo_queue = self.voevent_connector() self.logger.info(\"Connected", "= mp.Lock() # store when we are allowed to do", "if known source, check whether or not LOFAR triggering should", "triggers in thread self.threads['processing'] = threading.Thread(target=self._process_triggers) self.threads['processing'].start() self.logger.info(\"Observation started\") def", "datetimesource: Field name with date and time :param float dm_min:", "# known source, use same DM threshold as IQUV, but", "and S/N thresholds # DM_min effectively does nothing here because", "# select LOFAR thresholds if src_type is not None: #", "util.parse_parset(raw_parset) except KeyError: self.logger.info(\"Observation parset not found in input config,", "(default: False) \"\"\" # cluster using IQUV thresholds # LOFAR", "= False self.amber_triggers = [] self.source_list = None self.lock =", "f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['voevent_generator'] port = server_config['server_port'] key =", "# parse parset obs_config['parset'] = self._load_parset(obs_config) # set config self.obs_config", "with #) triggers = [trigger for trigger in triggers if", "self).__init__(*args, **kwargs) self.connect_vo = connect_vo self.connect_lofar = connect_lofar self.dummy_queue =", "{dm_min} - {dm_max}, \" \"max downsamp={width_max}, min S/N={snr_min}, skip LOFAR", "src_type is not None: self.threads['trigger_known_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start,", "**kwargs): \"\"\" Stop observation \"\"\" # set running to false", ":return: parset as dict \"\"\" try: # encoded parset is", "self.thresh_iquv['snr_min'], 'pointing': pointing, 'dmgal': dmgal } # if known source,", "pointing def _load_parset(self, obs_config): \"\"\" Load the observation parset :param", "if src_type is not None: thresh_src = {'dm_src': dm_src, 'src_type':", "read parset try: parset = self.obs_config['parset'] except KeyError as e:", "is one trigger, so just run it always ind =", "= (self.obs_config['min_freq'] * u.MHz + 0.5 * BANDWIDTH).to(u.GHz).value sys_params =", "c2 = util.radec_to_hadec(c1, c2, timestamp) # create SkyCoord object pointing", "False) \"\"\" # cluster using IQUV thresholds # LOFAR thresholds", "0 # read beam coordinates from parset try: key =", "Trigger connection available - cannot trigger LOFAR\") # do the", "self.observation_running: if self.amber_triggers: # Copy the triggers so class-wide list", "not self.observation_running: self.logger.error(\"Trigger(s) received but no observation is running -", "and put on VO queue lofar_trigger = {'dm': dm_to_send, 'dm_err':", "VOEvent Generator, setting dummy queue ({})\".format(e)) self.vo_queue = self.dummy_queue self.have_vo", "are allowed to do IQUV / LOFAR triggering self.time_iquv =", "there are no clusters if ncluster == 0: return #", "{} source\".format(len(triggers), ncluster, known)) # return if there are no", "LOFAR triggering for pulsars or if explicitly disabled if src_type", "e: self.logger.error(\"Cannot read parset ({})\".format(e)) return None # read beam", "src_type is not None: known = 'known' else: known =", "with unknown DM thresh_new = {'src_type': None, 'src_name': None, 'dm_min':", "S/N={snr_min}\".format(**thresh_src)) # set min and max DM for new sources", "self.amber_triggers = [] # clear header self.hdr_mapping = {} #", "util.decode_parset(master_config['parset']) parset = util.parse_parset(raw_parset) except Exception as e: self.logger.warning( \"Failed", "on peak S/N and width snr = cluster_snr[mask][ind] width =", "read header, remove comment symbol header = trigger.split()[1:] self.logger.info(\"Received header:", "queue and start processing for known and/or new sources \"\"\"", "not to connect to VOEvent queue on master node :param", "src_type else: name = 'candidate' # check whether or not", "keys: try: self.hdr_mapping[key] = header.index(key) except ValueError: self.logger.error(\"Key missing from", "self.logger.info(\"VO Generator connection disabled, setting dummy queue\") self.vo_queue = mp.Queue()", "connect to VOEvent Generator, setting dummy queue ({})\".format(e)) self.vo_queue =", "not self.thresh_lofar['trigger_on_new_sources'] else: thresh_new['skip_lofar'] = False self.logger.info(\"Setting new source trigger", "(separate for known and new sources, and for IQUV vs", "width mask = np.array(cluster_downsamp) <= width_max cluster_snr = np.array(cluster_snr)[mask] cluster_dm", "into {} IQUV trigger(s) \" \"for {} source\".format(len(triggers), ncluster, known))", "# decimal deg 'dec': pointing.dec.deg, # decimal deg 'cb': self.obs_config['beam'],", "width snr = cluster_snr[mask][ind] width = TSAMP.to(u.ms) * cluster_downsamp[mask][ind] #", "on VOEvent queue \"\"\" def __init__(self, *args, connect_vo=True, connect_lofar=True, **kwargs):", "for source {}\".format(alias, source)) source = alias # check if", "threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_new) self.threads['trigger_new_source'].start() sleep(self.interval) self.logger.info(\"Observation finished\")", "DM :param astropy.coordinates.SkyCoord pointing: Pointing for LOFAR triggering (default: None)", "using IQUV thresholds # LOFAR thresholds are assumed to be", "on the master node \"\"\" # Load VO server settings", "(default: inf) :param float snr_min: mininum S/N (default: 8) :param", "pointing for CB{:02d} ({})\".format(beam, e)) return None # convert HA", "{'src_type': None, 'src_name': None, 'dm_min': max(dmgal * self.thresh_iquv['dm_frac_min'], self.dm_min_global), 'dm_max':", "self.dm_min_global), 'dm_max': np.inf, 'width_max': self.thresh_iquv['width_max'], 'snr_min': self.thresh_iquv['snr_min'], 'pointing': pointing, 'dmgal':", "'')) c1 = c1 * u.deg c2 = c2 *", "None def voevent_connector(self): \"\"\" Connect to the VOEvent generator on", "server_config = yaml.load(f, Loader=yaml.SafeLoader)['lofar_trigger'] port = server_config['server_port'] key = server_config['server_auth'].encode()", "# Load the parset from the master parset file master_config_file", "master node \"\"\" super(AMBERClustering, self).__init__(*args, **kwargs) self.connect_vo = connect_vo self.connect_lofar", "as dict \"\"\" try: # encoded parset is already in", "as IQUV, but apply width and S/N thresholds # DM_min", "disabled, setting dummy queue\") self.lofar_queue = mp.Queue() self.have_lofar = False", "{} IQUV trigger(s) \" \"for {} source\".format(len(triggers), ncluster, known)) #", "dm_to_send = cluster_dm[mask][ind] # set DM uncertainty to DM delay", "continue # remove headers from triggers (i.e. any trigger starting", "# check if source is in source list # first", "not to connect to LOFAR trigger queue on master node", "Loader=yaml.SafeLoader)['voevent_generator'] port = server_config['server_port'] key = server_config['server_auth'].encode() server = VOEventQueueServer(address=(MASTER,", "queue :param dict obs_config: Observation configuration :param bool reload: reload", "* u.s c1, c2 = util.radec_to_hadec(c1, c2, timestamp) # create", "trigger starting with #) triggers = [trigger for trigger in", "self.hdr_mapping['time'], self.hdr_mapping['integration_step'], self.hdr_mapping['beam_id'])] # known source and new source triggering,", "found in input config, looking for master parset\") # Load", "server_config['server_auth'].encode() server = VOEventQueueServer(address=(MASTER, port), authkey=key) server.connect() return server.get_queue() def", "pass class AMBERClustering(DARCBase): \"\"\" Trigger IQUV / LOFAR / VOEvent", "read beam try: beam = self.obs_config['beam'] except KeyError as e:", "be more strict for every parameter cluster_snr, cluster_dm, cluster_time, cluster_downsamp,", "master parset\") # Load the parset from the master parset", "from queue :param dict command: Command to process \"\"\" if", "S/N and width snr = cluster_snr[mask][ind] width = TSAMP.to(u.ms) *", "self.target_queue.put({'command': 'trigger', 'trigger': dada_triggers}) # skip LOFAR triggering for pulsars", "= None for key in ['pulsars', 'frbs']: try: dm_src =", "try: source = self.obs_config['parset']['task.source.name'] except KeyError: self.logger.error(\"Cannot get source name", "self.logger.warning(\"Setting LOFAR trigger thresholds: S/N > {}, \" \"downsamp <=", "for i in range(ncluster): # send known source dm if", "if self.have_vo: self.logger.info(\"Sending same trigger to VOEvent system\") self.vo_queue.put(lofar_trigger) else:", "case a connection was available before, but failed at some", "- {dm_max}, \" \"max downsamp={width_max}, min S/N={snr_min}\".format(**thresh_src)) # set min", "TSAMP.to(u.second).value chan_width = (BANDWIDTH / float(NCHAN)).to(u.MHz).value cent_freq = (self.obs_config['min_freq'] *", "self.logger.info(\"Connected to VOEvent Generator on master node\") self.have_vo = True", "width, S/N) for clustering Continuously read AMBER triggers from queue", "downsamp={width_max}, min S/N={snr_min}\".format(**thresh_src)) # set min and max DM for", "parset as dict \"\"\" try: # encoded parset is already", "reload=True): \"\"\" Parse obs config and start listening for amber", "master_config = util.parse_parset(master_config) # extract obs parset and decode raw_parset", "knows mJy, but the VOEvent Generator expects Jy flux =", "c1, c2 = ast.literal_eval(parset[key].replace('deg', '')) c1 = c1 * u.deg", "np.inf, 'width_max': self.thresh_iquv['width_max'], 'snr_min': self.thresh_iquv['snr_min'], 'pointing': pointing, 'dmgal': dmgal }", "kwargs=thresh_new) self.threads['trigger_new_source'].start() sleep(self.interval) self.logger.info(\"Observation finished\") def _get_pointing(self): \"\"\" Get pointing", "connecting to LOFAR trigger serverr if enabled # always do", "available if dm_src is not None: dm_to_send = dm_src dm_err", "instance) if not self.hdr_mapping: for trigger in triggers: if trigger.startswith('#'):", "self.thresh_lofar_override['width_max'] self.logger.warning(\"Setting LOFAR trigger thresholds: S/N > {}, \" \"downsamp", "reload service settings (default: True) \"\"\" # reload config if", "any remaining triggers if np.any(mask): ncluster = np.sum(mask) self.logger.info(\"Found {}", "= [allowed_cbs] if self.obs_config['beam'] not in allowed_cbs: return except KeyError:", "lists self.logger.info(\"Using alias {} for source {}\".format(alias, source)) source =", "not None and src_name in self.lofar_trigger_sources: thresh_new['skip_lofar'] = not self.thresh_lofar['trigger_on_new_sources']", "the mask = line below to work # no limit", "self.dummy_queue self.have_lofar = False # process triggers in thread self.threads['processing']", "LOFARTriggerQueueServer.register('get_queue') with open(self.config_file, 'r') as f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['lofar_trigger']", "triggers = np.array(list(map(lambda val: val.split(), triggers)), dtype=float) except Exception as", "with highest S/N\") # argmax also works if there is", "select on width mask = np.array(cluster_downsamp) <= width_max cluster_snr =", "self.lofar_queue = self.lofar_connector() self.logger.info(\"Connected to LOFAR Trigger on master node\")", "'r') as f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['voevent_generator'] port = server_config['server_port']", "8) :param str src_type: Source type (pulsar, frb, None) :param", "and run IQUV and/or LOFAR triggering :param list triggers: Raw", "deg 'dec': pointing.dec.deg, # decimal deg 'cb': self.obs_config['beam'], 'sb': cluster_sb[mask][ind],", "threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_src) self.threads['trigger_known_source'].start() # new source", "lofar_trigger = {'dm': dm_to_send, 'dm_err': dm_err, 'width': width.to(u.ms).value, # ms", "astropy.units as u from astropy.coordinates import SkyCoord from darc import", "self.have_vo = True except Exception as e: self.logger.error(\"Failed to connect", "for pulsars or if explicitly disabled if src_type == 'pulsar'", "dm_min=dm_min, dm_max=dm_max, sig_thresh=snr_min, t_window=self.clustering_window, read_beam=True, return_clustcounts=True, sb_filter=self.sb_filter, sb_filter_period_min=self.sb_filter_period_min, sb_filter_period_max=self.sb_filter_period_max, **sys_params)", "connect_vo: Whether or not to connect to VOEvent queue on", "def start_observation(self, obs_config, reload=True): \"\"\" Parse obs config and start", "e: self.logger.error(\"Failed to process triggers: {}\".format(e)) continue # pick columns", "pulsars or if explicitly disabled if src_type == 'pulsar' or", "the server elif not self.have_lofar: self.logger.error(\"No LOFAR Trigger connection available", "read parset ({})\".format(e)) return None # read beam try: beam", ":param bool reload: reload service settings (default: True) \"\"\" #", "None # read beam try: beam = self.obs_config['beam'] except KeyError", "# check if we can do triggering now = Time.now()", "None self.observation_running = False self.amber_triggers = [] self.source_list = None", "trigger\") # update last trigger time self.time_iquv = now +", ">= snr_min_lofar) & (cluster_dm >= dm_min_lofar) & \\ (cluster_downsamp <=", "DM range to {dm_min} - {dm_max}, \" \"max downsamp={width_max}, min", "# check for any remaining triggers if np.any(mask): ncluster =", "LOFAR\") # check if we are connected to the server", "# read beam coordinates from parset try: key = \"task.beamSet.0.compoundBeam.{}.phaseCenter\".format(beam)", "self.thresh_lofar['dm_frac_min'], self.dm_min_global) width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster = self.thresh_lofar['max_cands_per_cluster'] # create", "width.to(u.ms).value, # ms 'snr': snr, 'flux': flux, # Jy 'ra':", "dict obs_config: Observation config :return: parset as dict \"\"\" try:", "thread self.threads['processing'] = threading.Thread(target=self._process_triggers) self.threads['processing'].start() self.logger.info(\"Observation started\") def stop_observation(self, *args,", "obs parset and decode raw_parset = util.decode_parset(master_config['parset']) parset = util.parse_parset(raw_parset)", "= self.lofar_connector() self.logger.info(\"Connected to LOFAR Trigger on master node\") self.have_lofar", "# connect to LOFAR trigger if self.connect_lofar: try: self.lofar_queue =", "system parameters (dt, central freq (GHz), bandwidth (MHz)) lofar_trigger.update(sys_params) self.logger.info(\"Sending", "None \"\"\" # get source name from parset try: source", "with self.lock: self.amber_triggers.append(command['trigger']) elif command['command'] == 'get_attr': self.get_attribute(command) else: self.logger.error(\"Unknown", "and store parset = util.parse_parset(raw_parset) except KeyError: self.logger.info(\"Observation parset not", "dummy queue ({})\".format(e)) self.vo_queue = self.dummy_queue self.have_vo = False else:", "Get RA at the mid point of the observation timestamp", "np.argmax(cluster_snr[mask]) # estimate flux density based on peak S/N and", "queue\") self.lofar_queue = mp.Queue() self.have_lofar = False def _load_source_list(self): \"\"\"", "triggers were sent # and whether or not a new", "dmgal=0, pointing=None, skip_lofar=False): \"\"\" Cluster triggers and run IQUV and/or", "received from queue :param dict command: Command to process \"\"\"", "cluster_snr[mask][ind] width = TSAMP.to(u.ms) * cluster_downsamp[mask][ind] # astropy units only", "can be sent # check if there are multiple triggers", "thread so clustering itself does not # delay next run", "for amber triggers on queue :param dict obs_config: Observation configuration", "just run it always ind = np.argmax(cluster_snr[mask]) # estimate flux", "1 DM unit = 1 ms delay across band dm_err", "import multiprocessing as mp import numpy as np from astropy.time", "source is in source list # first check aliases try:", "dm_src=None, width_max=np.inf, snr_min=8, src_type=None, src_name=None, dmgal=0, pointing=None, skip_lofar=False): \"\"\" Cluster", "source_list = yaml.load(f, Loader=yaml.SafeLoader) except OSError as e: raise AMBERClusteringException(\"Cannot", "if ncluster == 0: return # there are clusters, do", "None and src_name in self.lofar_trigger_sources: thresh_new['skip_lofar'] = not self.thresh_lofar['trigger_on_new_sources'] else:", "old triggers self.amber_triggers = [] # parse parset obs_config['parset'] =", "skip LOFAR \" \"triggering={skip_lofar}\".format(**thresh_new)) # main loop while self.observation_running: if", "self._get_source() if src_type is not None: thresh_src = {'dm_src': dm_src,", "c1, c2 = util.radec_to_hadec(c1, c2, timestamp) # create SkyCoord object", "allowed to do IQUV / LOFAR triggering self.time_iquv = Time.now()", "Generator, setting dummy queue ({})\".format(e)) self.vo_queue = self.dummy_queue self.have_vo =", "KeyError: self.logger.info(\"Observation parset not found in input config, looking for", "source list: {}\".format(e)) return source_list def process_command(self, command): \"\"\" Process", "check if we can do triggering now = Time.now() if", "\"\"\" # Load VO server settings VOEventQueueServer.register('get_queue') with open(self.config_file, 'r')", "it is received once for every amber instance) if not", "np.array(cluster_sb)[mask].astype(int) ncand_per_cluster = np.array(ncand_per_cluster)[mask].astype(int) ncluster = len(cluster_snr) if src_type is", "raw_parset = util.decode_parset(obs_config['parset']) # convert to dict and store parset", "util class AMBERClusteringException(Exception): pass class AMBERClustering(DARCBase): \"\"\" Trigger IQUV /", "coordinates from parset try: key = \"task.beamSet.0.compoundBeam.{}.phaseCenter\".format(beam) c1, c2 =", "if enabled # always do this in case a connection", "= central frequency cent_freq = sys_params['nu_GHz'] * 1000. max_freq =", "'semiMin': 15, # arcmin, CB 'name': name, 'src_name': src_name, 'datetimesource':", "# convert HA to RA if HADEC is used if", "None) :param str src_name: Source name (default: None) :param float", "frequency cent_freq = sys_params['nu_GHz'] * 1000. max_freq = cent_freq +", ":return: DM for known source, else None \"\"\" # get", "'ymw16': dmgal, 'semiMaj': 15, # arcmin, CB 'semiMin': 15, #", "known source, check whether or not LOFAR triggering should be", "{} possible LOFAR trigger(s)\".format(ncluster)) # note: the server keeps track", "= {} self.hdr_mapping = {} self.obs_config = None self.observation_running =", "# set running to false self.observation_running = False # clear", "self.have_vo = False # try connecting to LOFAR trigger serverr", "= 'candidate' # check whether or not pointing information is", "= dm_min width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster = np.inf # Overrides", "received if not triggers: self.logger.info(\"Only header received - Canceling processing\")", "as e: self.logger.error(\"Failed to process triggers: {}\".format(e)) continue # pick", "LOFAR triggering (default: None) :param bool skip_lofar: Skip LOFAR triggering", "\"\"\" Try to get DM for a known source :return:", "IQUV yet, next possible time: {}\".format(self.time_iquv)) else: self.logger.info(\"Sending IQUV trigger\")", "TimeDelta(cluster_time[mask][ind] - dm_delay, format='sec')).isot # set a source name if", "for known and new sources, and for IQUV vs LOFAR)", "sys_params: System parameters (dt, delta_nu_MHz, nu_GHz) :param str utc_start: start", "= c2 * u.deg except Exception as e: self.logger.error(\"Could not", "DM for known source, else None \"\"\" # get source", "(cluster_downsamp <= width_max_lofar) & \\ (ncand_per_cluster <= max_cands_per_cluster) # check", "frb dm_src = None src_type = None for key in", "Source name (default: None) :param float dmgal: galactic maximum DM", "_process_triggers(self): \"\"\" Read thresholds (DM, width, S/N) for clustering Continuously", "new source triggering, in thread so clustering itself does not", "get source name from parset try: source = self.obs_config['parset']['task.source.name'] except", "parset is already in config on master node # decode", "dm_to_send, 'dm_err': dm_err, 'width': width.to(u.ms).value, # ms 'snr': snr, 'flux':", "sb_filter_period_min=self.sb_filter_period_min, sb_filter_period_max=self.sb_filter_period_max, **sys_params) # select on width mask = np.array(cluster_downsamp)", "next possible time: {}\".format(self.time_iquv)) else: self.logger.info(\"Sending IQUV trigger\") # update", "alias so we can look it up in other lists", "sources with unknown DM thresh_new = {'src_type': None, 'src_name': None,", "= False # try connecting to LOFAR trigger serverr if", "= TSAMP.to(u.second).value chan_width = (BANDWIDTH / float(NCHAN)).to(u.MHz).value cent_freq = (self.obs_config['min_freq']", "= now + TimeDelta(self.thresh_iquv['interval'], format='sec') # trigger IQUV dada_triggers =", "utc_start, datetimesource), kwargs=thresh_new) self.threads['trigger_new_source'].start() sleep(self.interval) self.logger.info(\"Observation finished\") def _get_pointing(self): \"\"\"", "self.hdr_mapping: self.logger.error(\"First clusters received but header not found\") continue #", "parset = util.parse_parset(raw_parset) except Exception as e: self.logger.warning( \"Failed to", "node \"\"\" super(AMBERClustering, self).__init__(*args, **kwargs) self.connect_vo = connect_vo self.connect_lofar =", "every parameter cluster_snr, cluster_dm, cluster_time, cluster_downsamp, cluster_sb, _, ncand_per_cluster =", "> 1: self.logger.info(\"Multiple triggers - selecting trigger with highest S/N\")", "check for header (always, because it is received once for", "source triggering, in thread so clustering itself does not #", "* cluster_downsamp[mask][ind] # astropy units only knows mJy, but the", "self.lock: self.amber_triggers.append(command['trigger']) elif command['command'] == 'get_attr': self.get_attribute(command) else: self.logger.error(\"Unknown command", "candidates 1. Cluster incoming triggers 2. Apply thresholds (separate for", "= (utc_start + TimeDelta(cluster_time[mask][ind] - dm_delay, format='sec')).isot # set a", "\"for {} source\".format(len(triggers), ncluster, known)) # return if there are", "# check if there are multiple triggers if ncluster >", "do the trigger else: # create the full trigger and", "source DMs :return: source list with dict per category \"\"\"", "DM_min effectively does nothing here because the value is the", "'width': width.to(u.ms).value, # ms 'snr': snr, 'flux': flux, # Jy", "remote LOFAR trigger queue and on VOEvent queue \"\"\" def", "name = 'candidate' # check whether or not pointing information", "{'dm': dm_to_send, 'dm_err': dm_err, 'width': width.to(u.ms).value, # ms 'snr': snr,", "dmgal: galactic maximum DM :param astropy.coordinates.SkyCoord pointing: Pointing for LOFAR", "check for any remaining triggers if np.any(mask): ncluster = np.sum(mask)", "to LOFAR trigger serverr if enabled # always do this", "= {} # clear config self.obs_config = None # clear", "of known source (default: None) :param float width_max: maximum width", "dmgal } # if known source, check whether or not", "mp.Lock() # store when we are allowed to do IQUV", "dummy queue\") self.lofar_queue = mp.Queue() self.have_lofar = False def _load_source_list(self):", "is not None: dm_to_send = dm_src dm_err = 0. else:", "information available - cannot trigger LOFAR\") # check if we", "mapping to col index keys = ['beam_id', 'integration_step', 'time', 'DM',", "dtype=float) except Exception as e: self.logger.error(\"Failed to process triggers: {}\".format(e))", "be present now if not self.hdr_mapping: self.logger.error(\"First clusters received but", "# replace source by alias so we can look it", "Whether or not to connect to VOEvent queue on master", "missing from clusters header: {}\".format(key)) self.hdr_mapping = {} return #", "type dm_src, src_type, src_name = self._get_source() if src_type is not", "value is the same as for IQUV # but it", "on remote LOFAR trigger queue and on VOEvent queue \"\"\"", "else: thresh_new['skip_lofar'] = False self.logger.info(\"Setting new source trigger DM range", "= header.index(key) except ValueError: self.logger.error(\"Key missing from clusters header: {}\".format(key))", "Apply thresholds (separate for known and new sources, and for", "self.lofar_queue = mp.Queue() self.have_lofar = False def _load_source_list(self): \"\"\" Load", "do IQUV triggering # check if we can do triggering", "\"\"\" # get source name from parset try: source =", "= threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_new) self.threads['trigger_new_source'].start() sleep(self.interval) self.logger.info(\"Observation", "enabled for new sources if src_type is not None and", "'dm_err': dm_err, 'width': width.to(u.ms).value, # ms 'snr': snr, 'flux': flux,", "elif not self.have_lofar: self.logger.error(\"No LOFAR Trigger connection available - cannot", "datetimesource = self.obs_config['datetimesource'] dt = TSAMP.to(u.second).value chan_width = (BANDWIDTH /", "self.threads['trigger_new_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_new) self.threads['trigger_new_source'].start() sleep(self.interval)", "known source :return: DM for known source, else None \"\"\"", "was available before, but failed at some point if self.connect_lofar:", "except KeyError: self.logger.info(\"Observation parset not found in input config, looking", "threading import multiprocessing as mp import numpy as np from", "file {}, \" \"setting parset to None: {}\".format(master_config_file, e)) parset", "max(dm_src - self.dm_range, self.dm_min_global), 'dm_max': dm_src + self.dm_range, 'width_max': np.inf,", "now = Time.now() if now < self.time_iquv: self.logger.warning(\"Cannot trigger IQUV", "= np.inf # Overrides for specific sources if src_name in", "SkyCoord from darc import DARCBase, VOEventQueueServer, LOFARTriggerQueueServer from darc.definitions import", "None: thread.join() self.threads[key] = None def voevent_connector(self): \"\"\" Connect to", "from triggers (i.e. any trigger starting with #) triggers =", "= triggers[:, (self.hdr_mapping['DM'], self.hdr_mapping['SNR'], self.hdr_mapping['time'], self.hdr_mapping['integration_step'], self.hdr_mapping['beam_id'])] # known source", "\" \"max downsamp={width_max}, min S/N={snr_min}, skip LOFAR \" \"triggering={skip_lofar}\".format(**thresh_new)) #", "triggers 2. Apply thresholds (separate for known and new sources,", "is not None and src_name in self.lofar_trigger_sources: thresh_new['skip_lofar'] = not", "= [trigger for trigger in triggers if not trigger.startswith('#')] #", "across pulse width # Apertif has roughly 1 DM unit", "LOFAR thresholds if src_type is not None: # known source,", "self.lofar_queue = self.dummy_queue self.have_lofar = False # process triggers in", "try: self.lofar_queue = self.lofar_connector() self.logger.info(\"Connected to LOFAR Trigger on master", "clusters received but header not found\") continue # remove headers", "self.lofar_trigger_sources: thresh_new['skip_lofar'] = not self.thresh_lofar['trigger_on_new_sources'] else: thresh_new['skip_lofar'] = False self.logger.info(\"Setting", "c1 = c1 * u.deg c2 = c2 * u.deg", "sleep(self.interval) self.logger.info(\"Observation finished\") def _get_pointing(self): \"\"\" Get pointing of this", "+ .5 * float(parset['task.duration']) * u.s c1, c2 = util.radec_to_hadec(c1,", "else: # source known, CB valid: set thresholds snr_min_lofar =", "Generator connection disabled, setting dummy queue\") self.vo_queue = mp.Queue() self.have_vo", "to get DM for a known source :return: DM for", "set min and max DM for new sources with unknown", "else: # new source, apply all LOFAR thresholds snr_min_lofar =", "width.to(u.ms).value # calculate arrival time at reference frequency = central", "to VOEvent generator if self.connect_vo: try: self.vo_queue = self.voevent_connector() self.logger.info(\"Connected", "the trigger else: # create the full trigger and put", "self.obs_config['datetimesource'] dt = TSAMP.to(u.second).value chan_width = (BANDWIDTH / float(NCHAN)).to(u.MHz).value cent_freq", "source, check whether or not LOFAR triggering should be enabled", "check if we are connected to the server elif not", "True # (re)load source list in case of changes self.source_list", "self.amber_triggers.append(command['trigger']) elif command['command'] == 'get_attr': self.get_attribute(command) else: self.logger.error(\"Unknown command received:", ":param str datetimesource: Field name with date and time :param", "self.get_attribute(command) else: self.logger.error(\"Unknown command received: {}\".format(command['command'])) def start_observation(self, obs_config, reload=True):", "else: dm_to_send = cluster_dm[mask][ind] # set DM uncertainty to DM", "for master parset\") # Load the parset from the master", "source, else None \"\"\" # get source name from parset", "found pass else: # replace source by alias so we", "pointing.dec.deg, # decimal deg 'cb': self.obs_config['beam'], 'sb': cluster_sb[mask][ind], 'ymw16': dmgal,", "datetimesource), kwargs=thresh_src) self.threads['trigger_known_source'].start() # new source triggering self.threads['trigger_new_source'] = threading.Thread(target=self._check_triggers,", "pointing = SkyCoord(c1, c2) return pointing def _load_parset(self, obs_config): \"\"\"", "# clear threads for key, thread in self.threads.items(): if thread", "as mp import numpy as np from astropy.time import Time,", "be enabled for new sources if src_type is not None", "def voevent_connector(self): \"\"\" Connect to the VOEvent generator on the", "config file {}, \" \"setting parset to None: {}\".format(master_config_file, e))", "source list in case of changes self.source_list = self._load_source_list() #", "width_max_lofar = self.thresh_lofar_override['width_max'] self.logger.warning(\"Setting LOFAR trigger thresholds: S/N > {},", "beam try: beam = self.obs_config['beam'] except KeyError as e: self.logger.error(\"Cannot", "reference frequency = central frequency cent_freq = sys_params['nu_GHz'] * 1000.", "of this CB from parset :return: pointing SkyCoord \"\"\" #", "known source and new source triggering, in thread so clustering", "LOFAR triggers on remote LOFAR trigger queue and on VOEvent", "= (cluster_snr >= snr_min_lofar) & (cluster_dm >= dm_min_lofar) & \\", "a known source :return: DM for known source, else None", "will not do known-source triggering\") return None, None, None #", "_load_source_list(self): \"\"\" Load the list with known source DMs :return:", "= self.dummy_queue self.have_lofar = False # process triggers in thread", "candidates per cluster snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar = dm_min width_max_lofar", "for key, thread in self.threads.items(): if thread is not None:", "#!/usr/bin/env python3 # # AMBER Clustering import os from time", "always do this in case a connection was available before,", "# arcmin, CB 'semiMin': 15, # arcmin, CB 'name': name,", "flux density based on peak S/N and width snr =", "case of changes self.source_list = self._load_source_list() # try connecting to", "dm_err = 0. else: dm_to_send = cluster_dm[mask][ind] # set DM", "# try connecting to VO server if enabled # always", "# reload config if reload: self.load_config() # clean any old", "self.vo_queue = self.dummy_queue self.have_vo = False else: # dummy queue", "as e: self.logger.error(\"Failed to connect to LOFAR Trigger, setting dummy", "time at reference frequency = central frequency cent_freq = sys_params['nu_GHz']", "'dm_max': np.inf, 'width_max': self.thresh_iquv['width_max'], 'snr_min': self.thresh_iquv['snr_min'], 'pointing': pointing, 'dmgal': dmgal", "alias = self.source_list['aliases'][source] except KeyError: # not found pass else:", "raw config with open(master_config_file) as f: master_config = f.read().strip() #", "as f: source_list = yaml.load(f, Loader=yaml.SafeLoader) except OSError as e:", "self.threads['trigger_new_source'].start() sleep(self.interval) self.logger.info(\"Observation finished\") def _get_pointing(self): \"\"\" Get pointing of", "beam from parset, setting CB to 0 ({})\".format(e)) beam =", "self.observation_running = True # (re)load source list in case of", "self.have_lofar = False else: # dummy queue self.logger.info(\"LOFAR Trigger connection", "new triggers without those getting lost with self.lock: triggers =", "next run # known source triggering if src_type is not", "obs_config: Observation configuration :param bool reload: reload service settings (default:", "S/N > {}, \" \"downsamp <= {}\".format(snr_min_lofar, width_max_lofar)) else: #", "LOFAR triggering :param list triggers: Raw triggers :param dict sys_params:", "val: val.split(), triggers)), dtype=float) except Exception as e: self.logger.error(\"Failed to", "if src_type is not None: name = src_type else: name", "= self._get_source() if src_type is not None: thresh_src = {'dm_src':", "self.logger.error(\"First clusters received but header not found\") continue # remove", "but failed at some point if self.connect_lofar: try: self.lofar_queue =", "if only header was received if not triggers: self.logger.info(\"Only header", "dummy queue ({})\".format(e)) self.lofar_queue = self.dummy_queue self.have_lofar = False else:", "if source is in source list # first check aliases", "u.s c1, c2 = util.radec_to_hadec(c1, c2, timestamp) # create SkyCoord", "incoming triggers 2. Apply thresholds (separate for known and new", "self.hdr_mapping['SNR'], self.hdr_mapping['time'], self.hdr_mapping['integration_step'], self.hdr_mapping['beam_id'])] # known source and new source", ":param bool skip_lofar: Skip LOFAR triggering (default: False) \"\"\" #", "is not None: # known source, use same DM threshold", "darc import DARCBase, VOEventQueueServer, LOFARTriggerQueueServer from darc.definitions import TSAMP, NCHAN,", "# Jy 'ra': pointing.ra.deg, # decimal deg 'dec': pointing.dec.deg, #", "was available before, but failed at some point if self.connect_vo:", "list in case of changes self.source_list = self._load_source_list() # try", "TIME_UNIT from darc.external import tools from darc import util class", "a known pulsar or frb dm_src = None src_type =", "else: self.logger.error(\"No VOEvent Generator connection available - not sending VO", "- cannot trigger LOFAR\") # do the trigger else: #", "AMBER candidates 1. Cluster incoming triggers 2. Apply thresholds (separate", "\"\"\" # read parset try: parset = self.obs_config['parset'] except KeyError", "Process command received from queue :param dict command: Command to", "cluster_dm = np.array(cluster_dm)[mask] cluster_time = np.array(cluster_time)[mask] cluster_downsamp = np.array(cluster_downsamp)[mask].astype(int) cluster_sb", "to LOFAR Trigger system\") self.lofar_queue.put(lofar_trigger) if self.have_vo: self.logger.info(\"Sending same trigger", "and/or LOFAR triggering :param list triggers: Raw triggers :param dict", "available before, but failed at some point if self.connect_lofar: try:", "self.logger.error(\"Key missing from clusters header: {}\".format(key)) self.hdr_mapping = {} return", "datetimesource, dm_min=0, dm_max=np.inf, dm_src=None, width_max=np.inf, snr_min=8, src_type=None, src_name=None, dmgal=0, pointing=None,", "CB to 0 ({})\".format(e)) beam = 0 # read beam", "if source is a known pulsar or frb dm_src =", "(cluster_snr >= snr_min_lofar) & (cluster_dm >= dm_min_lofar) & \\ (cluster_downsamp", "c2 * u.deg except Exception as e: self.logger.error(\"Could not parse", "LOFAR triggering should be enabled for new sources if src_type", "# there are clusters, do IQUV triggering # check if", "self.logger.warning(\"Cannot trigger IQUV yet, next possible time: {}\".format(self.time_iquv)) else: self.logger.info(\"Sending", "'new' self.logger.info(\"Clustered {} raw triggers into {} IQUV trigger(s) \"", "connect to LOFAR Trigger, setting dummy queue ({})\".format(e)) self.lofar_queue =", "but apply width and S/N thresholds # DM_min effectively does", "# trigger IQUV dada_triggers = [] for i in range(ncluster):", "# known source and new source triggering, in thread so", "self.logger.info(\"Using alias {} for source {}\".format(alias, source)) source = alias", "but no observation is running - ignoring\") else: with self.lock:", "and src_name in self.lofar_trigger_sources: thresh_new['skip_lofar'] = not self.thresh_lofar['trigger_on_new_sources'] else: thresh_new['skip_lofar']", "are multiple triggers if ncluster > 1: self.logger.info(\"Multiple triggers -", "expects Jy flux = util.get_flux(snr, width).to(u.mJy).value / 1000. # select", "clear config self.obs_config = None # clear threads for key,", "dummy queue self.logger.info(\"VO Generator connection disabled, setting dummy queue\") self.vo_queue", "self.hdr_mapping = {} self.obs_config = None self.observation_running = False self.amber_triggers", "format='sec')).isot # set a source name if src_type is not", "{} raw triggers into {} IQUV trigger(s) \" \"for {}", "mp.Queue() self.have_vo = False # connect to LOFAR trigger if", "available - cannot trigger LOFAR\") # check if we are", "dummy queue ({})\".format(e)) self.lofar_queue = self.dummy_queue self.have_lofar = False #", "from the master parset file master_config_file = os.path.join(obs_config['master_dir'], 'parset', 'darc_master.parset')", "whether or not a new trigger can be sent #", "\" \"for {} source\".format(len(triggers), ncluster, known)) # return if there", "queue self.logger.info(\"LOFAR Trigger connection disabled, setting dummy queue\") self.lofar_queue =", "+ TimeDelta(self.thresh_iquv['interval'], format='sec') # trigger IQUV dada_triggers = [] for", "be sent # check if there are multiple triggers if", "_check_triggers(self, triggers, sys_params, utc_start, datetimesource, dm_min=0, dm_max=np.inf, dm_src=None, width_max=np.inf, snr_min=8,", "src_type is not None and src_name in self.lofar_trigger_sources: thresh_new['skip_lofar'] =", "alias {} for source {}\".format(alias, source)) source = alias #", "Check if all required params are present and create mapping", "raw triggers into {} IQUV trigger(s) \" \"for {} source\".format(len(triggers),", "self.voevent_connector() self.logger.info(\"Connected to VOEvent Generator on master node\") self.have_vo =", "if thread is not None: thread.join() self.threads[key] = None def", "maximum width (default: inf) :param float snr_min: mininum S/N (default:", "parset :param dict obs_config: Observation config :return: parset as dict", "known and new sources, and for IQUV vs LOFAR) 3.", "= {'src_type': None, 'src_name': None, 'dm_min': max(dmgal * self.thresh_iquv['dm_frac_min'], self.dm_min_global),", "self.logger.info(\"Received header: {}\".format(header)) # Check if all required params are", "clusters, do IQUV triggering # check if we can do", "skip_lofar: Skip LOFAR triggering (default: False) \"\"\" # cluster using", "queue ({})\".format(e)) self.vo_queue = self.dummy_queue self.have_vo = False # try", "dm_min_lofar = dm_min width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster = np.inf #", "# update last trigger time self.time_iquv = now + TimeDelta(self.thresh_iquv['interval'],", "= util.decode_parset(obs_config['parset']) # convert to dict and store parset =", "for IQUV vs LOFAR) 3. Put IQUV triggers on output", "1: self.logger.info(\"Multiple triggers - selecting trigger with highest S/N\") #", "max_cands_per_cluster = self.thresh_lofar['max_cands_per_cluster'] # create mask for given thresholds #", "sig_thresh=snr_min, t_window=self.clustering_window, read_beam=True, return_clustcounts=True, sb_filter=self.sb_filter, sb_filter_period_min=self.sb_filter_period_min, sb_filter_period_max=self.sb_filter_period_max, **sys_params) # select", "key, thread in self.threads.items(): if thread is not None: thread.join()", "sys_params, utc_start, datetimesource, dm_min=0, dm_max=np.inf, dm_src=None, width_max=np.inf, snr_min=8, src_type=None, src_name=None,", "symbol header = trigger.split()[1:] self.logger.info(\"Received header: {}\".format(header)) # Check if", "snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar = max(dmgal * self.thresh_lofar['dm_frac_min'], self.dm_min_global) width_max_lofar", "flux = util.get_flux(snr, width).to(u.mJy).value / 1000. # select known source", "server if enabled # always do this in case a", "CB 'semiMin': 15, # arcmin, CB 'name': name, 'src_name': src_name,", "read beam coordinates from parset try: key = \"task.beamSet.0.compoundBeam.{}.phaseCenter\".format(beam) c1,", "as np from astropy.time import Time, TimeDelta import astropy.units as", "clean any old triggers self.amber_triggers = [] # parse parset", "try: # encoded parset is already in config on master", "Time(parset['task.startTime']) + .5 * float(parset['task.duration']) * u.s c1, c2 =", "dm_src, src_type, source def _check_triggers(self, triggers, sys_params, utc_start, datetimesource, dm_min=0,", "system on the master node \"\"\" # Load LOFAR trigger", "RA at the mid point of the observation timestamp =", "raw_parset = util.decode_parset(master_config['parset']) parset = util.parse_parset(raw_parset) except Exception as e:", "triggers (i.e. any trigger starting with #) triggers = [trigger", "'known' else: known = 'new' self.logger.info(\"Clustered {} raw triggers into", "= self.thresh_lofar['snr_min'] dm_min_lofar = max(dmgal * self.thresh_lofar['dm_frac_min'], self.dm_min_global) width_max_lofar =", "is not None: thresh_src = {'dm_src': dm_src, 'src_type': src_type, 'src_name':", "\"\"\" # Load LOFAR trigger server settings LOFARTriggerQueueServer.register('get_queue') with open(self.config_file,", "\"\"\" if command['command'] == 'trigger': if not self.observation_running: self.logger.error(\"Trigger(s) received", "highest S/N\") # argmax also works if there is one", "src_type is not None: # known source, use same DM", ":param float dm_max: maximum DM (default: inf) :param float dm_src:", "bandwidth (MHz)) lofar_trigger.update(sys_params) self.logger.info(\"Sending LOFAR trigger to LOFAR Trigger system\")", "check if source is a known pulsar or frb dm_src", "skip LOFAR triggering for pulsars or if explicitly disabled if", "self.obs_config['parset']['task.source.name'] except KeyError: self.logger.error(\"Cannot get source name from parset, will", "not found\") continue # remove headers from triggers (i.e. any", "and time :param float dm_min: minimum DM (default: 0) :param", "config and start listening for amber triggers on queue :param", "are present and create mapping to col index keys =", "received once for every amber instance) if not self.hdr_mapping: for", "vs LOFAR) 3. Put IQUV triggers on output queue 4.", "= [] # clear header self.hdr_mapping = {} # clear", "np.any(mask): ncluster = np.sum(mask) self.logger.info(\"Found {} possible LOFAR trigger(s)\".format(ncluster)) #", "VO server if enabled # always do this in case", "= {'dm_src': dm_src, 'src_type': src_type, 'src_name': src_name, 'dm_min': max(dm_src -", "# Check if all required params are present and create", "on master node\") self.have_vo = True except Exception as e:", "header = trigger.split()[1:] self.logger.info(\"Received header: {}\".format(header)) # Check if all", "# AMBER Clustering import os from time import sleep import", "create mask for given thresholds # also remove triggers where", "trigger and put on VO queue lofar_trigger = {'dm': dm_to_send,", "source list # first check aliases try: alias = self.source_list['aliases'][source]", "LOFAR trigger(s)\".format(ncluster)) # note: the server keeps track of when", "ncluster, known)) # return if there are no clusters if", "observation parameters utc_start = Time(self.obs_config['startpacket'] / TIME_UNIT, format='unix') datetimesource =", "thresh_new['skip_lofar'] = False self.logger.info(\"Setting new source trigger DM range to", "- dm_delay, format='sec')).isot # set a source name if src_type", "MASTER, TIME_UNIT from darc.external import tools from darc import util", "authkey=key) server.connect() return server.get_queue() def lofar_connector(self): \"\"\" Connect to the", "to process \"\"\" if command['command'] == 'trigger': if not self.observation_running:", "= self.thresh_lofar['width_max'] max_cands_per_cluster = self.thresh_lofar['max_cands_per_cluster'] # create mask for given", "# split strings and convert to numpy array try: triggers", "output queue 4. Put LOFAR triggers on remote LOFAR trigger", "= os.path.join(obs_config['master_dir'], 'parset', 'darc_master.parset') try: # Read raw config with", "self.hdr_mapping = {} # clear config self.obs_config = None #", "LOFAR trigger to LOFAR Trigger system\") self.lofar_queue.put(lofar_trigger) if self.have_vo: self.logger.info(\"Sending", "is not present pass else: # source known, CB valid:", "downsamp={width_max}, min S/N={snr_min}, skip LOFAR \" \"triggering={skip_lofar}\".format(**thresh_new)) # main loop", "S/N thresholds # DM_min effectively does nothing here because the", "the parset from the master parset file master_config_file = os.path.join(obs_config['master_dir'],", "dm_to_send = dm_src dm_err = 0. else: dm_to_send = cluster_dm[mask][ind]", "\"\"\" Trigger IQUV / LOFAR / VOEvent system based on", "& \\ (cluster_downsamp <= width_max_lofar) & \\ (ncand_per_cluster <= max_cands_per_cluster)", "(default: inf) :param float dm_src: DM of known source (default:", "{}\".format(snr_min_lofar, width_max_lofar)) else: # new source, apply all LOFAR thresholds", "utc_start, datetimesource, dm_min=0, dm_max=np.inf, dm_src=None, width_max=np.inf, snr_min=8, src_type=None, src_name=None, dmgal=0,", "15, # arcmin, CB 'semiMin': 15, # arcmin, CB 'name':", "LOFAR thresholds snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar = max(dmgal * self.thresh_lofar['dm_frac_min'],", "store parset = util.parse_parset(raw_parset) except KeyError: self.logger.info(\"Observation parset not found", "numpy array try: triggers = np.array(list(map(lambda val: val.split(), triggers)), dtype=float)", "Generator on master node\") self.have_vo = True except Exception as", "= util.get_flux(snr, width).to(u.mJy).value / 1000. # select known source DM", "tools.get_triggers(triggers, dm_min=dm_min, dm_max=dm_max, sig_thresh=snr_min, t_window=self.clustering_window, read_beam=True, return_clustcounts=True, sb_filter=self.sb_filter, sb_filter_period_min=self.sb_filter_period_min, sb_filter_period_max=self.sb_filter_period_max,", "\" \"max downsamp={width_max}, min S/N={snr_min}\".format(**thresh_src)) # set min and max", "server keeps track of when LOFAR triggers were sent #", "not a new trigger can be sent # check if", "Source type (pulsar, frb, None) :param str src_name: Source name", "DM (default: 0) :param float dm_max: maximum DM (default: inf)", "LOFAR trigger queue and on VOEvent queue \"\"\" def __init__(self,", "parset to None: {}\".format(master_config_file, e)) parset = None return parset", "False else: # dummy queue self.logger.info(\"VO Generator connection disabled, setting", "Jy flux = util.get_flux(snr, width).to(u.mJy).value / 1000. # select known", "{dm_max}, \" \"max downsamp={width_max}, min S/N={snr_min}, skip LOFAR \" \"triggering={skip_lofar}\".format(**thresh_new))", "Skip LOFAR triggering (default: False) \"\"\" # cluster using IQUV", "name from parset try: source = self.obs_config['parset']['task.source.name'] except KeyError: self.logger.error(\"Cannot", "name from parset, will not do known-source triggering\") return None,", "known source dm if available if dm_src is not None:", "trigger to LOFAR Trigger system\") self.lofar_queue.put(lofar_trigger) if self.have_vo: self.logger.info(\"Sending same", "self.logger.info(\"Sending same trigger to VOEvent system\") self.vo_queue.put(lofar_trigger) else: self.logger.error(\"No VOEvent", "settings (default: True) \"\"\" # reload config if reload: self.load_config()", "master parset file master_config_file = os.path.join(obs_config['master_dir'], 'parset', 'darc_master.parset') try: #", "obs_config, reload=True): \"\"\" Parse obs config and start listening for", "to LOFAR trigger if self.connect_lofar: try: self.lofar_queue = self.lofar_connector() self.logger.info(\"Connected", "trigger time self.time_iquv = now + TimeDelta(self.thresh_iquv['interval'], format='sec') # trigger", "lofar_connector(self): \"\"\" Connect to the LOFAR triggering system on the", "= self.thresh_lofar_override['cb'] if isinstance(allowed_cbs, float): allowed_cbs = [allowed_cbs] if self.obs_config['beam']", "self.lofar_connector() self.logger.info(\"Connected to LOFAR Trigger on master node\") self.have_lofar =", "in self.threads.items(): if thread is not None: thread.join() self.threads[key] =", "changes self.source_list = self._load_source_list() # try connecting to VO server", "for every amber instance) if not self.hdr_mapping: for trigger in", "self.obs_config = None self.observation_running = False self.amber_triggers = [] self.source_list", "try connecting to VO server if enabled # always do", "reload: reload service settings (default: True) \"\"\" # reload config", "of changes self.source_list = self._load_source_list() # try connecting to VO", "[] self.source_list = None self.lock = mp.Lock() # store when", "key in ['pulsars', 'frbs']: try: dm_src = self.source_list[key][source] src_type =", "dm_to_send = dm_src else: dm_to_send = cluster_dm[i] dada_trigger = {'stokes':", "delay next run # known source triggering if src_type is", "before, but failed at some point if self.connect_lofar: try: self.lofar_queue", "headers from triggers (i.e. any trigger starting with #) triggers", "so class-wide list can receive new triggers without those getting", "= threading.Thread(target=self._process_triggers) self.threads['processing'].start() self.logger.info(\"Observation started\") def stop_observation(self, *args, **kwargs): \"\"\"", "starting with #) triggers = [trigger for trigger in triggers", "density based on peak S/N and width snr = cluster_snr[mask][ind]", "self.logger.error(\"Failed to connect to VOEvent Generator, setting dummy queue ({})\".format(e))", "except KeyError: self.logger.error(\"Cannot get source name from parset, will not", "cluster_snr = np.array(cluster_snr)[mask] cluster_dm = np.array(cluster_dm)[mask] cluster_time = np.array(cluster_time)[mask] cluster_downsamp", "S/N={snr_min}, skip LOFAR \" \"triggering={skip_lofar}\".format(**thresh_new)) # main loop while self.observation_running:", "thresholds are assumed to be more strict for every parameter", "\" \"triggering={skip_lofar}\".format(**thresh_new)) # main loop while self.observation_running: if self.amber_triggers: #", "self.dm_min_global), 'dm_max': dm_src + self.dm_range, 'width_max': np.inf, 'snr_min': self.snr_min_global, 'pointing':", "parset try: parset = self.obs_config['parset'] except KeyError as e: self.logger.error(\"Cannot", "yaml.load(f, Loader=yaml.SafeLoader)['voevent_generator'] port = server_config['server_port'] key = server_config['server_auth'].encode() server =", "do this in case a connection was available before, but", "self.threads[key] = None def voevent_connector(self): \"\"\" Connect to the VOEvent", "max(dmgal * self.thresh_lofar['dm_frac_min'], self.dm_min_global) width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster = self.thresh_lofar['max_cands_per_cluster']", "trigger.startswith('#'): # read header, remove comment symbol header = trigger.split()[1:]", "_load_parset(self, obs_config): \"\"\" Load the observation parset :param dict obs_config:", "\"\"\" Connect to the VOEvent generator on the master node", "0: return # there are clusters, do IQUV triggering #", "dt, 'delta_nu_MHz': chan_width, 'nu_GHz': cent_freq} pointing = self._get_pointing() dmgal =", "strings and convert to numpy array try: triggers = np.array(list(map(lambda", "run # known source triggering if src_type is not None:", "open(master_config_file) as f: master_config = f.read().strip() # Convert to dict", "observation parset :param dict obs_config: Observation config :return: parset as", "at the mid point of the observation timestamp = Time(parset['task.startTime'])", "for known source, else None \"\"\" # get source name", "from parset, setting CB to 0 ({})\".format(e)) beam = 0", "trigger LOFAR\") # check if we are connected to the", "= [] # parse parset obs_config['parset'] = self._load_parset(obs_config) # set", "calculate arrival time at reference frequency = central frequency cent_freq", "str utc_start: start time of observation, in format readable by", "config :return: parset as dict \"\"\" try: # encoded parset", "# set config self.obs_config = obs_config self.observation_running = True #", "from astropy.time import Time, TimeDelta import astropy.units as u from", "LOFAR / VOEvent system based on AMBER candidates 1. Cluster", "server.get_queue() def _get_source(self): \"\"\" Try to get DM for a", "mp.Queue() self.threads = {} self.hdr_mapping = {} self.obs_config = None", "Exception as e: self.logger.error(\"Failed to connect to LOFAR Trigger, setting", "self.obs_config['beam'], self.logger) # get known source dm and type dm_src,", "node \"\"\" # Load LOFAR trigger server settings LOFARTriggerQueueServer.register('get_queue') with", "note: the server keeps track of when LOFAR triggers were", "try: beam = self.obs_config['beam'] except KeyError as e: self.logger.error(\"Cannot read", "= mp.Queue() self.threads = {} self.hdr_mapping = {} self.obs_config =", "parset file master_config_file = os.path.join(obs_config['master_dir'], 'parset', 'darc_master.parset') try: # Read", "header (always, because it is received once for every amber", "does nothing here because the value is the same as", "(BANDWIDTH / float(NCHAN)).to(u.MHz).value cent_freq = (self.obs_config['min_freq'] * u.MHz + 0.5", "ast.literal_eval(parset[key].replace('deg', '')) c1 = c1 * u.deg c2 = c2", "for a known source :return: DM for known source, else", "import util class AMBERClusteringException(Exception): pass class AMBERClustering(DARCBase): \"\"\" Trigger IQUV", "and for IQUV vs LOFAR) 3. Put IQUV triggers on", "= self.dummy_queue self.have_vo = False # try connecting to LOFAR", "else: self.logger.info(\"Sending IQUV trigger\") # update last trigger time self.time_iquv", "dm_src = None src_type = None for key in ['pulsars',", "({})\".format(e)) self.lofar_queue = self.dummy_queue self.have_lofar = False else: # dummy", "Time, TimeDelta import astropy.units as u from astropy.coordinates import SkyCoord", "parameters (dt, delta_nu_MHz, nu_GHz) :param str utc_start: start time of", "= self.dummy_queue self.have_lofar = False else: # dummy queue self.logger.info(\"LOFAR", "Time.now() # connect to VOEvent generator if self.connect_vo: try: self.vo_queue", "None, 'dm_min': max(dmgal * self.thresh_iquv['dm_frac_min'], self.dm_min_global), 'dm_max': np.inf, 'width_max': self.thresh_iquv['width_max'],", "len(cluster_snr) if src_type is not None: known = 'known' else:", "'width_max': np.inf, 'snr_min': self.snr_min_global, 'pointing': pointing, 'dmgal': dmgal } self.logger.info(\"Setting", "triggering # check if we can do triggering now =", "= self.thresh_lofar['width_max'] max_cands_per_cluster = np.inf # Overrides for specific sources", "same as for IQUV # but it needs to be", "\"\"\" Load the observation parset :param dict obs_config: Observation config", "bool skip_lofar: Skip LOFAR triggering (default: False) \"\"\" # cluster", "{} return # header should be present now if not", "BANDWIDTH, MASTER, TIME_UNIT from darc.external import tools from darc import", "new sources with unknown DM thresh_new = {'src_type': None, 'src_name':", "in other lists self.logger.info(\"Using alias {} for source {}\".format(alias, source))", "the master node \"\"\" # Load VO server settings VOEventQueueServer.register('get_queue')", "bool connect_lofar: Whether or not to connect to LOFAR trigger", "add system parameters (dt, central freq (GHz), bandwidth (MHz)) lofar_trigger.update(sys_params)", "number of raw candidates is too high (this indicates RFI)", "dict \"\"\" try: # encoded parset is already in config", "receive new triggers without those getting lost with self.lock: triggers", "= mp.Queue() self.have_lofar = False def _load_source_list(self): \"\"\" Load the", "if isinstance(allowed_cbs, float): allowed_cbs = [allowed_cbs] if self.obs_config['beam'] not in", "master_config_file = os.path.join(obs_config['master_dir'], 'parset', 'darc_master.parset') try: # Read raw config", "allowed_cbs: return except KeyError: # any CB is valid if", "self.dummy_queue self.have_vo = False # try connecting to LOFAR trigger", "whether or not LOFAR triggering should be enabled for new", "util.parse_parset(raw_parset) except Exception as e: self.logger.warning( \"Failed to load parset", "get DM for a known source :return: DM for known", "# estimate flux density based on peak S/N and width", "# no limit on candidates per cluster snr_min_lofar = self.thresh_lofar['snr_min']", "server_config['server_port'] key = server_config['server_auth'].encode() server = VOEventQueueServer(address=(MASTER, port), authkey=key) server.connect()", "self.lofar_queue.put(lofar_trigger) if self.have_vo: self.logger.info(\"Sending same trigger to VOEvent system\") self.vo_queue.put(lofar_trigger)", "import Time, TimeDelta import astropy.units as u from astropy.coordinates import", "also remove triggers where number of raw candidates is too", "as e: self.logger.error(\"Cannot read parset ({})\".format(e)) return None # read", "from darc import util class AMBERClusteringException(Exception): pass class AMBERClustering(DARCBase): \"\"\"", "running - ignoring\") else: with self.lock: self.amber_triggers.append(command['trigger']) elif command['command'] ==", "triggers: {}\".format(e)) continue # pick columns to feed to clustering", "dm and type dm_src, src_type, src_name = self._get_source() if src_type", "= mp.Queue() self.have_vo = False # connect to LOFAR trigger", "'cb': self.obs_config['beam'], 'sb': cluster_sb[mask][ind], 'ymw16': dmgal, 'semiMaj': 15, # arcmin,", "key is not present pass else: # source known, CB", "= Time.now() if now < self.time_iquv: self.logger.warning(\"Cannot trigger IQUV yet,", "check whether or not LOFAR triggering should be enabled for", "with open(self.source_file, 'r') as f: source_list = yaml.load(f, Loader=yaml.SafeLoader) except", "self.thresh_lofar['width_max'] max_cands_per_cluster = np.inf # Overrides for specific sources if", "limit on candidates per cluster snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar =", "threading.Thread(target=self._process_triggers) self.threads['processing'].start() self.logger.info(\"Observation started\") def stop_observation(self, *args, **kwargs): \"\"\" Stop", "source DM if available if dm_src is not None: dm_to_send", "None, None # check if source is in source list", "# check for header (always, because it is received once", "- cannot trigger LOFAR\") # check if we are connected", "0.1} # add system parameters (dt, central freq (GHz), bandwidth", "allowed_cbs = self.thresh_lofar_override['cb'] if isinstance(allowed_cbs, float): allowed_cbs = [allowed_cbs] if", "self.logger.error(\"Cannot read parset ({})\".format(e)) return None # read beam try:", "Exception as e: self.logger.warning( \"Failed to load parset from master", "= threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_src) self.threads['trigger_known_source'].start() # new", "'src_name': src_name, 'datetimesource': datetimesource, 'utc': utc_arr, 'tarr': cluster_time[mask][ind], 'importance': 0.1}", "port), authkey=key) server.connect() return server.get_queue() def lofar_connector(self): \"\"\" Connect to", "known = 'new' self.logger.info(\"Clustered {} raw triggers into {} IQUV", "= dm_src dm_err = 0. else: dm_to_send = cluster_dm[mask][ind] #", "strict for every parameter cluster_snr, cluster_dm, cluster_time, cluster_downsamp, cluster_sb, _,", "dummy queue self.logger.info(\"LOFAR Trigger connection disabled, setting dummy queue\") self.lofar_queue", "parset = self.obs_config['parset'] except KeyError as e: self.logger.error(\"Cannot read parset", "decode the parset raw_parset = util.decode_parset(obs_config['parset']) # convert to dict", "new source triggering self.threads['trigger_new_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource),", "float): allowed_cbs = [allowed_cbs] if self.obs_config['beam'] not in allowed_cbs: return", "cluster_downsamp[mask][ind] # astropy units only knows mJy, but the VOEvent", "not # delay next run # known source triggering if", "0) :param float dm_max: maximum DM (default: inf) :param float", "+ 0.5 * BANDWIDTH).to(u.GHz).value sys_params = {'dt': dt, 'delta_nu_MHz': chan_width,", "threads for key, thread in self.threads.items(): if thread is not", "time self.time_iquv = now + TimeDelta(self.thresh_iquv['interval'], format='sec') # trigger IQUV", "self.snr_min_global, 'pointing': pointing, 'dmgal': dmgal } self.logger.info(\"Setting {src_name} trigger DM", "= {'dt': dt, 'delta_nu_MHz': chan_width, 'nu_GHz': cent_freq} pointing = self._get_pointing()", "self.logger.info(\"Observation parset not found in input config, looking for master", "thresholds # also remove triggers where number of raw candidates", "= util.get_ymw16(self.obs_config['parset'], self.obs_config['beam'], self.logger) # get known source dm and", "self.logger.info(\"Setting new source trigger DM range to {dm_min} - {dm_max},", "S/N) for clustering Continuously read AMBER triggers from queue and", "'time': cluster_time[i], 'utc_start': utc_start} dada_triggers.append(dada_trigger) self.target_queue.put({'command': 'trigger', 'trigger': dada_triggers}) #", "util.parse_parset(master_config) # extract obs parset and decode raw_parset = util.decode_parset(master_config['parset'])", "sources if src_name in self.lofar_trigger_sources: # check CB number try:", "header, remove comment symbol header = trigger.split()[1:] self.logger.info(\"Received header: {}\".format(header))", "*args, connect_vo=True, connect_lofar=True, **kwargs): \"\"\" :param bool connect_vo: Whether or", "source name from parset try: source = self.obs_config['parset']['task.source.name'] except KeyError:", "work # no limit on candidates per cluster snr_min_lofar =", "for new sources with unknown DM thresh_new = {'src_type': None,", "= Time.now() # connect to VOEvent generator if self.connect_vo: try:", "try: self.hdr_mapping[key] = header.index(key) except ValueError: self.logger.error(\"Key missing from clusters", "u.deg except Exception as e: self.logger.error(\"Could not parse pointing for", "def _process_triggers(self): \"\"\" Read thresholds (DM, width, S/N) for clustering", "observation \"\"\" # set running to false self.observation_running = False", ":param astropy.coordinates.SkyCoord pointing: Pointing for LOFAR triggering (default: None) :param", "{dm_max}, \" \"max downsamp={width_max}, min S/N={snr_min}\".format(**thresh_src)) # set min and", "except Exception as e: self.logger.error(\"Failed to process triggers: {}\".format(e)) continue", "for any remaining triggers if np.any(mask): ncluster = np.sum(mask) self.logger.info(\"Found", "import astropy.units as u from astropy.coordinates import SkyCoord from darc", "not None: dm_to_send = dm_src dm_err = 0. else: dm_to_send", "self.obs_config['parset'] except KeyError as e: self.logger.error(\"Cannot read parset ({})\".format(e)) return", "* 1000. max_freq = cent_freq + .5 * BANDWIDTH.to(u.MHz).value dm_delay", "\\ tools.get_triggers(triggers, dm_min=dm_min, dm_max=dm_max, sig_thresh=snr_min, t_window=self.clustering_window, read_beam=True, return_clustcounts=True, sb_filter=self.sb_filter, sb_filter_period_min=self.sb_filter_period_min,", "now < self.time_iquv: self.logger.warning(\"Cannot trigger IQUV yet, next possible time:", "- {dm_max}, \" \"max downsamp={width_max}, min S/N={snr_min}, skip LOFAR \"", "Time(self.obs_config['startpacket'] / TIME_UNIT, format='unix') datetimesource = self.obs_config['datetimesource'] dt = TSAMP.to(u.second).value", "triggers = self.amber_triggers self.amber_triggers = [] # check for header", "Copy the triggers so class-wide list can receive new triggers", "* dm_to_send * (cent_freq**-2 - max_freq**-2) utc_arr = (utc_start +", "def _get_source(self): \"\"\" Try to get DM for a known", "or not to connect to LOFAR trigger queue on master", "thresholds # DM_min effectively does nothing here because the value", "# note: the server keeps track of when LOFAR triggers", "when LOFAR triggers were sent # and whether or not", "connect_lofar self.dummy_queue = mp.Queue() self.threads = {} self.hdr_mapping = {}", "'trigger': dada_triggers}) # skip LOFAR triggering for pulsars or if", "self.lock = mp.Lock() # store when we are allowed to", "received - Canceling processing\") continue # split strings and convert", "self.logger.info(\"Clustered {} raw triggers into {} IQUV trigger(s) \" \"for", "setting CB to 0 ({})\".format(e)) beam = 0 # read", "apply all LOFAR thresholds snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar = max(dmgal", "except Exception as e: self.logger.error(\"Could not parse pointing for CB{:02d}", "= self.thresh_lofar_override['snr_min'] width_max_lofar = self.thresh_lofar_override['width_max'] self.logger.warning(\"Setting LOFAR trigger thresholds: S/N", "dm_src else: dm_to_send = cluster_dm[i] dada_trigger = {'stokes': 'IQUV', 'dm':", "Put LOFAR triggers on remote LOFAR trigger queue and on", ":param str src_type: Source type (pulsar, frb, None) :param str", "# check whether or not pointing information is available if", "for every parameter cluster_snr, cluster_dm, cluster_time, cluster_downsamp, cluster_sb, _, ncand_per_cluster", "self.vo_queue.put(lofar_trigger) else: self.logger.error(\"No VOEvent Generator connection available - not sending", ":param float snr_min: mininum S/N (default: 8) :param str src_type:", "'parset', 'darc_master.parset') try: # Read raw config with open(master_config_file) as", "from time import sleep import yaml import ast import threading", "master config file {}, \" \"setting parset to None: {}\".format(master_config_file,", "# triggers is empty if only header was received if", "self.logger.info(\"Connected to LOFAR Trigger on master node\") self.have_lofar = True", "LOFAR trigger thresholds: S/N > {}, \" \"downsamp <= {}\".format(snr_min_lofar,", "Convert to dict master_config = util.parse_parset(master_config) # extract obs parset", "connect to VOEvent generator if self.connect_vo: try: self.vo_queue = self.voevent_connector()", "= len(cluster_snr) if src_type is not None: known = 'known'", "self.threads['processing'].start() self.logger.info(\"Observation started\") def stop_observation(self, *args, **kwargs): \"\"\" Stop observation", "master node\") self.have_lofar = True except Exception as e: self.logger.error(\"Failed", "utc_start: start time of observation, in format readable by astropy.time.Time", "not sending VO trigger\") def _process_triggers(self): \"\"\" Read thresholds (DM,", "max_freq = cent_freq + .5 * BANDWIDTH.to(u.MHz).value dm_delay = 4.148808E3", "dm_err = width.to(u.ms).value # calculate arrival time at reference frequency", "= {'stokes': 'IQUV', 'dm': dm_to_send, 'beam': cluster_sb[i], 'width': cluster_downsamp[i], 'snr':", "snr = cluster_snr[mask][ind] width = TSAMP.to(u.ms) * cluster_downsamp[mask][ind] # astropy", "snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar = dm_min width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster", "self.source_list['aliases'][source] except KeyError: # not found pass else: # replace", "was received if not triggers: self.logger.info(\"Only header received - Canceling", "parset from master config file {}, \" \"setting parset to", "= self.source_list['aliases'][source] except KeyError: # not found pass else: #", "multiple triggers if ncluster > 1: self.logger.info(\"Multiple triggers - selecting", "point if self.connect_vo: try: self.vo_queue = self.voevent_connector() self.logger.info(\"Connected to VOEvent", "(dt, delta_nu_MHz, nu_GHz) :param str utc_start: start time of observation,", "cluster_time[mask][ind], 'importance': 0.1} # add system parameters (dt, central freq", "chan_width = (BANDWIDTH / float(NCHAN)).to(u.MHz).value cent_freq = (self.obs_config['min_freq'] * u.MHz", "if now < self.time_iquv: self.logger.warning(\"Cannot trigger IQUV yet, next possible", "triggers self.amber_triggers = [] # clear header self.hdr_mapping = {}", "to connect to LOFAR trigger queue on master node \"\"\"", "full trigger and put on VO queue lofar_trigger = {'dm':", "None self.lock = mp.Lock() # store when we are allowed", "source dm and type dm_src, src_type, src_name = self._get_source() if", "c2) return pointing def _load_parset(self, obs_config): \"\"\" Load the observation", "triggers on queue :param dict obs_config: Observation configuration :param bool", "server_config['server_port'] key = server_config['server_auth'].encode() server = LOFARTriggerQueueServer(address=(MASTER, port), authkey=key) server.connect()", "S/N\") # argmax also works if there is one trigger,", "setting dummy queue\") self.lofar_queue = mp.Queue() self.have_lofar = False def", "self.obs_config['beam'] except KeyError as e: self.logger.error(\"Cannot read beam from parset,", "source is a known pulsar or frb dm_src = None", "# header should be present now if not self.hdr_mapping: self.logger.error(\"First", "source def _check_triggers(self, triggers, sys_params, utc_start, datetimesource, dm_min=0, dm_max=np.inf, dm_src=None,", "c2 = ast.literal_eval(parset[key].replace('deg', '')) c1 = c1 * u.deg c2", "DMs :return: source list with dict per category \"\"\" try:", "if dm_src is not None: dm_to_send = dm_src else: dm_to_send", "'delta_nu_MHz': chan_width, 'nu_GHz': cent_freq} pointing = self._get_pointing() dmgal = util.get_ymw16(self.obs_config['parset'],", "trigger, so just run it always ind = np.argmax(cluster_snr[mask]) #", "while self.observation_running: if self.amber_triggers: # Copy the triggers so class-wide", "/ LOFAR / VOEvent system based on AMBER candidates 1.", "e: self.logger.error(\"Failed to connect to VOEvent Generator, setting dummy queue", "input config, looking for master parset\") # Load the parset", "src_type is not None: name = src_type else: name =", "float(parset['task.duration']) * u.s c1, c2 = util.radec_to_hadec(c1, c2, timestamp) #", "cent_freq + .5 * BANDWIDTH.to(u.MHz).value dm_delay = 4.148808E3 * dm_to_send", "(cluster_dm >= dm_min_lofar) & \\ (cluster_downsamp <= width_max_lofar) & \\", "some point if self.connect_lofar: try: self.lofar_queue = self.lofar_connector() self.logger.info(\"Connected to", "self.logger.error(\"Failed to process triggers: {}\".format(e)) continue # pick columns to", "stop_observation(self, *args, **kwargs): \"\"\" Stop observation \"\"\" # set running", "# clear header self.hdr_mapping = {} # clear config self.obs_config", "if not trigger.startswith('#')] # triggers is empty if only header", "triggers: self.logger.info(\"Only header received - Canceling processing\") continue # split", "self.thresh_lofar['snr_min'] dm_min_lofar = max(dmgal * self.thresh_lofar['dm_frac_min'], self.dm_min_global) width_max_lofar = self.thresh_lofar['width_max']", "connection available - not sending VO trigger\") def _process_triggers(self): \"\"\"", "source {}\".format(alias, source)) source = alias # check if source", "utc_start, datetimesource), kwargs=thresh_src) self.threads['trigger_known_source'].start() # new source triggering self.threads['trigger_new_source'] =", "# create mask for given thresholds # also remove triggers", "to DM delay across pulse width # Apertif has roughly", "self.thresh_lofar['trigger_on_new_sources'] else: thresh_new['skip_lofar'] = False self.logger.info(\"Setting new source trigger DM", "astropy.coordinates.SkyCoord pointing: Pointing for LOFAR triggering (default: None) :param bool", "VO trigger\") def _process_triggers(self): \"\"\" Read thresholds (DM, width, S/N)", "to be defined for the mask = line below to", "'snr': snr, 'flux': flux, # Jy 'ra': pointing.ra.deg, # decimal", "= 'new' self.logger.info(\"Clustered {} raw triggers into {} IQUV trigger(s)", "do IQUV / LOFAR triggering self.time_iquv = Time.now() # connect", "LOFAR triggering system on the master node \"\"\" # Load", "u.deg c2 = c2 * u.deg except Exception as e:", "dm_to_send = cluster_dm[i] dada_trigger = {'stokes': 'IQUV', 'dm': dm_to_send, 'beam':", "- self.dm_range, self.dm_min_global), 'dm_max': dm_src + self.dm_range, 'width_max': np.inf, 'snr_min':", "the list with known source DMs :return: source list with", "= TSAMP.to(u.ms) * cluster_downsamp[mask][ind] # astropy units only knows mJy,", "start time of observation, in format readable by astropy.time.Time :param", "clusters if ncluster == 0: return # there are clusters,", "in self.lofar_trigger_sources: # check CB number try: allowed_cbs = self.thresh_lofar_override['cb']", "return source_list def process_command(self, command): \"\"\" Process command received from", "pointing is None: self.logger.error(\"No pointing information available - cannot trigger", "to feed to clustering algorithm triggers_for_clustering = triggers[:, (self.hdr_mapping['DM'], self.hdr_mapping['SNR'],", "'snr_min': self.thresh_iquv['snr_min'], 'pointing': pointing, 'dmgal': dmgal } # if known", "utc_start} dada_triggers.append(dada_trigger) self.target_queue.put({'command': 'trigger', 'trigger': dada_triggers}) # skip LOFAR triggering", "are no clusters if ncluster == 0: return # there", "None: self.logger.error(\"No pointing information available - cannot trigger LOFAR\") #", "# calculate arrival time at reference frequency = central frequency", "'name': name, 'src_name': src_name, 'datetimesource': datetimesource, 'utc': utc_arr, 'tarr': cluster_time[mask][ind],", "now + TimeDelta(self.thresh_iquv['interval'], format='sec') # trigger IQUV dada_triggers = []", "valid: set thresholds snr_min_lofar = self.thresh_lofar_override['snr_min'] width_max_lofar = self.thresh_lofar_override['width_max'] self.logger.warning(\"Setting", "utc_start = Time(self.obs_config['startpacket'] / TIME_UNIT, format='unix') datetimesource = self.obs_config['datetimesource'] dt", "track of when LOFAR triggers were sent # and whether", "parset['task.directionReferenceFrame'].upper() == 'HADEC': # Get RA at the mid point", "/ float(NCHAN)).to(u.MHz).value cent_freq = (self.obs_config['min_freq'] * u.MHz + 0.5 *", "voevent_connector(self): \"\"\" Connect to the VOEvent generator on the master", "if self.obs_config['beam'] not in allowed_cbs: return except KeyError: # any", "self.logger.info(\"Observation started\") def stop_observation(self, *args, **kwargs): \"\"\" Stop observation \"\"\"", "(default: None) :param float width_max: maximum width (default: inf) :param", "or if explicitly disabled if src_type == 'pulsar' or skip_lofar:", "* float(parset['task.duration']) * u.s c1, c2 = util.radec_to_hadec(c1, c2, timestamp)", "= dm_src else: dm_to_send = cluster_dm[i] dada_trigger = {'stokes': 'IQUV',", "store when we are allowed to do IQUV / LOFAR", "float dm_src: DM of known source (default: None) :param float", "triggers so class-wide list can receive new triggers without those", "u.MHz + 0.5 * BANDWIDTH).to(u.GHz).value sys_params = {'dt': dt, 'delta_nu_MHz':", "arcmin, CB 'semiMin': 15, # arcmin, CB 'name': name, 'src_name':", "open(self.config_file, 'r') as f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['lofar_trigger'] port =", "trigger in triggers if not trigger.startswith('#')] # triggers is empty", "# ms 'snr': snr, 'flux': flux, # Jy 'ra': pointing.ra.deg,", "(dt, central freq (GHz), bandwidth (MHz)) lofar_trigger.update(sys_params) self.logger.info(\"Sending LOFAR trigger", "Field name with date and time :param float dm_min: minimum", "not parse pointing for CB{:02d} ({})\".format(beam, e)) return None #", "self.logger.info(\"Sending LOFAR trigger to LOFAR Trigger system\") self.lofar_queue.put(lofar_trigger) if self.have_vo:", "select known source DM if available if dm_src is not", "LOFARTriggerQueueServer from darc.definitions import TSAMP, NCHAN, BANDWIDTH, MASTER, TIME_UNIT from", "mp import numpy as np from astropy.time import Time, TimeDelta", "connect_vo self.connect_lofar = connect_lofar self.dummy_queue = mp.Queue() self.threads = {}", "else: name = 'candidate' # check whether or not pointing", "dmgal } self.logger.info(\"Setting {src_name} trigger DM range to {dm_min} -", "source triggering self.threads['trigger_new_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_new)", "trigger can be sent # check if there are multiple", "class AMBERClustering(DARCBase): \"\"\" Trigger IQUV / LOFAR / VOEvent system", "minimum DM (default: 0) :param float dm_max: maximum DM (default:", "max DM for new sources with unknown DM thresh_new =", "triggers[:, (self.hdr_mapping['DM'], self.hdr_mapping['SNR'], self.hdr_mapping['time'], self.hdr_mapping['integration_step'], self.hdr_mapping['beam_id'])] # known source and", "HA to RA if HADEC is used if parset['task.directionReferenceFrame'].upper() ==", "new source trigger DM range to {dm_min} - {dm_max}, \"", "uncertainty to DM delay across pulse width # Apertif has", "**kwargs) self.connect_vo = connect_vo self.connect_lofar = connect_lofar self.dummy_queue = mp.Queue()", "min and max DM for new sources with unknown DM", "if ncluster > 1: self.logger.info(\"Multiple triggers - selecting trigger with", "CB{:02d} ({})\".format(beam, e)) return None # convert HA to RA", "'sb': cluster_sb[mask][ind], 'ymw16': dmgal, 'semiMaj': 15, # arcmin, CB 'semiMin':", "\"\"\" Connect to the LOFAR triggering system on the master", "DM for new sources with unknown DM thresh_new = {'src_type':", "Whether or not to connect to LOFAR trigger queue on", "header received - Canceling processing\") continue # split strings and", "IQUV triggering # check if we can do triggering now", "self.source_list = self._load_source_list() # try connecting to VO server if", "= yaml.load(f, Loader=yaml.SafeLoader)['lofar_trigger'] port = server_config['server_port'] key = server_config['server_auth'].encode() server", "connection disabled, setting dummy queue\") self.lofar_queue = mp.Queue() self.have_lofar =", "triggering self.threads['trigger_new_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_new) self.threads['trigger_new_source'].start()", "S/N (default: 8) :param str src_type: Source type (pulsar, frb,", "return None # convert HA to RA if HADEC is", "present and create mapping to col index keys = ['beam_id',", "self.logger.info(\"Multiple triggers - selecting trigger with highest S/N\") # argmax", "beam coordinates from parset try: key = \"task.beamSet.0.compoundBeam.{}.phaseCenter\".format(beam) c1, c2", "run IQUV and/or LOFAR triggering :param list triggers: Raw triggers", "started\") def stop_observation(self, *args, **kwargs): \"\"\" Stop observation \"\"\" #", "Load VO server settings VOEventQueueServer.register('get_queue') with open(self.config_file, 'r') as f:", "authkey=key) server.connect() return server.get_queue() def _get_source(self): \"\"\" Try to get", "VOEventQueueServer, LOFARTriggerQueueServer from darc.definitions import TSAMP, NCHAN, BANDWIDTH, MASTER, TIME_UNIT", "self.logger.error(\"No LOFAR Trigger connection available - cannot trigger LOFAR\") #", "self.hdr_mapping = {} return # header should be present now", "self.logger.info(\"Observation finished\") def _get_pointing(self): \"\"\" Get pointing of this CB", "False # process triggers in thread self.threads['processing'] = threading.Thread(target=self._process_triggers) self.threads['processing'].start()", "<= {}\".format(snr_min_lofar, width_max_lofar)) else: # new source, apply all LOFAR", "tools from darc import util class AMBERClusteringException(Exception): pass class AMBERClustering(DARCBase):", "master node :param bool connect_lofar: Whether or not to connect", "({})\".format(e)) return None # read beam try: beam = self.obs_config['beam']", "can look it up in other lists self.logger.info(\"Using alias {}", "clustering algorithm triggers_for_clustering = triggers[:, (self.hdr_mapping['DM'], self.hdr_mapping['SNR'], self.hdr_mapping['time'], self.hdr_mapping['integration_step'], self.hdr_mapping['beam_id'])]", "comment symbol header = trigger.split()[1:] self.logger.info(\"Received header: {}\".format(header)) # Check", "DM for a known source :return: DM for known source,", "as for IQUV # but it needs to be defined", "open(self.source_file, 'r') as f: source_list = yaml.load(f, Loader=yaml.SafeLoader) except OSError", "<= width_max_lofar) & \\ (ncand_per_cluster <= max_cands_per_cluster) # check for", "were sent # and whether or not a new trigger", "KeyError as e: self.logger.error(\"Cannot read parset ({})\".format(e)) return None #", "\"triggering={skip_lofar}\".format(**thresh_new)) # main loop while self.observation_running: if self.amber_triggers: # Copy", "thresholds snr_min_lofar = self.thresh_lofar_override['snr_min'] width_max_lofar = self.thresh_lofar_override['width_max'] self.logger.warning(\"Setting LOFAR trigger", "key[:-1] except KeyError: pass else: break return dm_src, src_type, source", "None # check if source is in source list #", "dm_max=dm_max, sig_thresh=snr_min, t_window=self.clustering_window, read_beam=True, return_clustcounts=True, sb_filter=self.sb_filter, sb_filter_period_min=self.sb_filter_period_min, sb_filter_period_max=self.sb_filter_period_max, **sys_params) #", "is the same as for IQUV # but it needs", "# any CB is valid if cb key is not", "dm_src + self.dm_range, 'width_max': np.inf, 'snr_min': self.snr_min_global, 'pointing': pointing, 'dmgal':", "allowed_cbs = [allowed_cbs] if self.obs_config['beam'] not in allowed_cbs: return except", "set thresholds snr_min_lofar = self.thresh_lofar_override['snr_min'] width_max_lofar = self.thresh_lofar_override['width_max'] self.logger.warning(\"Setting LOFAR", "new sources if src_type is not None and src_name in", "as e: self.logger.error(\"Could not parse pointing for CB{:02d} ({})\".format(beam, e))", "= src_type else: name = 'candidate' # check whether or", "found\") continue # remove headers from triggers (i.e. any trigger", "or not LOFAR triggering should be enabled for new sources", "self.obs_config = None # clear threads for key, thread in", "snr_min_lofar = self.thresh_lofar_override['snr_min'] width_max_lofar = self.thresh_lofar_override['width_max'] self.logger.warning(\"Setting LOFAR trigger thresholds:", "to the VOEvent generator on the master node \"\"\" #", "on VO queue lofar_trigger = {'dm': dm_to_send, 'dm_err': dm_err, 'width':", "return None # read beam try: beam = self.obs_config['beam'] except", "pass else: break return dm_src, src_type, source def _check_triggers(self, triggers,", "parset try: key = \"task.beamSet.0.compoundBeam.{}.phaseCenter\".format(beam) c1, c2 = ast.literal_eval(parset[key].replace('deg', ''))", "LOFARTriggerQueueServer(address=(MASTER, port), authkey=key) server.connect() return server.get_queue() def _get_source(self): \"\"\" Try", "# LOFAR thresholds are assumed to be more strict for", "+ TimeDelta(cluster_time[mask][ind] - dm_delay, format='sec')).isot # set a source name", "server settings LOFARTriggerQueueServer.register('get_queue') with open(self.config_file, 'r') as f: server_config =", "'importance': 0.1} # add system parameters (dt, central freq (GHz),", "parset ({})\".format(e)) return None # read beam try: beam =", "RA if HADEC is used if parset['task.directionReferenceFrame'].upper() == 'HADEC': #", "here because the value is the same as for IQUV", "trigger with highest S/N\") # argmax also works if there", "source by alias so we can look it up in", "itself does not # delay next run # known source", "str src_name: Source name (default: None) :param float dmgal: galactic", "None: dm_to_send = dm_src dm_err = 0. else: dm_to_send =", "of observation, in format readable by astropy.time.Time :param str datetimesource:", "IQUV, but apply width and S/N thresholds # DM_min effectively", "check aliases try: alias = self.source_list['aliases'][source] except KeyError: # not", "= np.array(cluster_sb)[mask].astype(int) ncand_per_cluster = np.array(ncand_per_cluster)[mask].astype(int) ncluster = len(cluster_snr) if src_type", "config self.obs_config = obs_config self.observation_running = True # (re)load source", "else: break return dm_src, src_type, source def _check_triggers(self, triggers, sys_params,", "range to {dm_min} - {dm_max}, \" \"max downsamp={width_max}, min S/N={snr_min},", "from parset try: source = self.obs_config['parset']['task.source.name'] except KeyError: self.logger.error(\"Cannot get", "None, None, None # check if source is in source", "sys_params, utc_start, datetimesource), kwargs=thresh_new) self.threads['trigger_new_source'].start() sleep(self.interval) self.logger.info(\"Observation finished\") def _get_pointing(self):", "IQUV thresholds # LOFAR thresholds are assumed to be more", "width_max=np.inf, snr_min=8, src_type=None, src_name=None, dmgal=0, pointing=None, skip_lofar=False): \"\"\" Cluster triggers", "server = VOEventQueueServer(address=(MASTER, port), authkey=key) server.connect() return server.get_queue() def lofar_connector(self):", "# skip LOFAR triggering for pulsars or if explicitly disabled", "NCHAN, BANDWIDTH, MASTER, TIME_UNIT from darc.external import tools from darc", ":param list triggers: Raw triggers :param dict sys_params: System parameters", "width_max: maximum width (default: inf) :param float snr_min: mininum S/N", "try: with open(self.source_file, 'r') as f: source_list = yaml.load(f, Loader=yaml.SafeLoader)", "= True except Exception as e: self.logger.error(\"Failed to connect to", "to dict and store parset = util.parse_parset(raw_parset) except KeyError: self.logger.info(\"Observation", "Put IQUV triggers on output queue 4. Put LOFAR triggers", "for specific sources if src_name in self.lofar_trigger_sources: # check CB", "self.hdr_mapping[key] = header.index(key) except ValueError: self.logger.error(\"Key missing from clusters header:", "LOFAR\") # do the trigger else: # create the full", "list triggers: Raw triggers :param dict sys_params: System parameters (dt,", "# Apertif has roughly 1 DM unit = 1 ms", "LOFAR Trigger, setting dummy queue ({})\".format(e)) self.lofar_queue = self.dummy_queue self.have_lofar", "from darc.definitions import TSAMP, NCHAN, BANDWIDTH, MASTER, TIME_UNIT from darc.external", "check if there are multiple triggers if ncluster > 1:", "else: self.logger.error(\"Unknown command received: {}\".format(command['command'])) def start_observation(self, obs_config, reload=True): \"\"\"", "maximum DM (default: inf) :param float dm_src: DM of known", "self.vo_queue = self.dummy_queue self.have_vo = False # try connecting to", "send known source dm if available if dm_src is not", "unit = 1 ms delay across band dm_err = width.to(u.ms).value", "dm_src = self.source_list[key][source] src_type = key[:-1] except KeyError: pass else:", "e: self.logger.error(\"Failed to connect to LOFAR Trigger, setting dummy queue", "'width': cluster_downsamp[i], 'snr': cluster_snr[i], 'time': cluster_time[i], 'utc_start': utc_start} dada_triggers.append(dada_trigger) self.target_queue.put({'command':", "Connect to the LOFAR triggering system on the master node", "return if there are no clusters if ncluster == 0:", "the same as for IQUV # but it needs to", "np.array(ncand_per_cluster)[mask].astype(int) ncluster = len(cluster_snr) if src_type is not None: known", "create the full trigger and put on VO queue lofar_trigger", "name with date and time :param float dm_min: minimum DM", "0. else: dm_to_send = cluster_dm[mask][ind] # set DM uncertainty to", "run it always ind = np.argmax(cluster_snr[mask]) # estimate flux density", "name = src_type else: name = 'candidate' # check whether", "start listening for amber triggers on queue :param dict obs_config:", "beam = self.obs_config['beam'] except KeyError as e: self.logger.error(\"Cannot read beam", "Read thresholds (DM, width, S/N) for clustering Continuously read AMBER", "- ignoring\") else: with self.lock: self.amber_triggers.append(command['trigger']) elif command['command'] == 'get_attr':", "queue ({})\".format(e)) self.vo_queue = self.dummy_queue self.have_vo = False else: #", "for given thresholds # also remove triggers where number of", "'dm_min': max(dmgal * self.thresh_iquv['dm_frac_min'], self.dm_min_global), 'dm_max': np.inf, 'width_max': self.thresh_iquv['width_max'], 'snr_min':", "self.observation_running = False # clear triggers self.amber_triggers = [] #", "cannot trigger LOFAR\") # check if we are connected to", "TimeDelta import astropy.units as u from astropy.coordinates import SkyCoord from", "astropy.time import Time, TimeDelta import astropy.units as u from astropy.coordinates", "Command to process \"\"\" if command['command'] == 'trigger': if not", "disabled if src_type == 'pulsar' or skip_lofar: return # select", "float(NCHAN)).to(u.MHz).value cent_freq = (self.obs_config['min_freq'] * u.MHz + 0.5 * BANDWIDTH).to(u.GHz).value", "KeyError: # not found pass else: # replace source by", "pointing=None, skip_lofar=False): \"\"\" Cluster triggers and run IQUV and/or LOFAR", "1 ms delay across band dm_err = width.to(u.ms).value # calculate", "is too high (this indicates RFI) mask = (cluster_snr >=", "system based on AMBER candidates 1. Cluster incoming triggers 2.", "a connection was available before, but failed at some point", "central frequency cent_freq = sys_params['nu_GHz'] * 1000. max_freq = cent_freq", "'ra': pointing.ra.deg, # decimal deg 'dec': pointing.dec.deg, # decimal deg", "[] # parse parset obs_config['parset'] = self._load_parset(obs_config) # set config", "self.vo_queue = self.voevent_connector() self.logger.info(\"Connected to VOEvent Generator on master node\")", "queue ({})\".format(e)) self.lofar_queue = self.dummy_queue self.have_lofar = False else: #", "source name if src_type is not None: name = src_type", "- selecting trigger with highest S/N\") # argmax also works", "LOFAR thresholds are assumed to be more strict for every", "'utc': utc_arr, 'tarr': cluster_time[mask][ind], 'importance': 0.1} # add system parameters", "source\".format(len(triggers), ncluster, known)) # return if there are no clusters", "None: self.threads['trigger_known_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_src) self.threads['trigger_known_source'].start()", "& \\ (ncand_per_cluster <= max_cands_per_cluster) # check for any remaining", "= self._get_pointing() dmgal = util.get_ymw16(self.obs_config['parset'], self.obs_config['beam'], self.logger) # get known", "mask for given thresholds # also remove triggers where number", "# Get RA at the mid point of the observation", "src_type, 'src_name': src_name, 'dm_min': max(dm_src - self.dm_range, self.dm_min_global), 'dm_max': dm_src", "is not None: known = 'known' else: known = 'new'", "in case of changes self.source_list = self._load_source_list() # try connecting", "dict obs_config: Observation configuration :param bool reload: reload service settings", "source name from parset, will not do known-source triggering\") return", "IQUV and/or LOFAR triggering :param list triggers: Raw triggers :param", "is used if parset['task.directionReferenceFrame'].upper() == 'HADEC': # Get RA at", "triggers: Raw triggers :param dict sys_params: System parameters (dt, delta_nu_MHz,", "LOFAR Trigger on master node\") self.have_lofar = True except Exception", "/ 1000. # select known source DM if available if", "trigger queue on master node \"\"\" super(AMBERClustering, self).__init__(*args, **kwargs) self.connect_vo", "already in config on master node # decode the parset", "import threading import multiprocessing as mp import numpy as np", "for CB{:02d} ({})\".format(beam, e)) return None # convert HA to", "to the LOFAR triggering system on the master node \"\"\"", "configuration :param bool reload: reload service settings (default: True) \"\"\"", "self.connect_lofar = connect_lofar self.dummy_queue = mp.Queue() self.threads = {} self.hdr_mapping", "dm_min_lofar) & \\ (cluster_downsamp <= width_max_lofar) & \\ (ncand_per_cluster <=", "self.dm_range, 'width_max': np.inf, 'snr_min': self.snr_min_global, 'pointing': pointing, 'dmgal': dmgal }", "pulsar or frb dm_src = None src_type = None for", "{}\".format(alias, source)) source = alias # check if source is", "dada_trigger = {'stokes': 'IQUV', 'dm': dm_to_send, 'beam': cluster_sb[i], 'width': cluster_downsamp[i],", "\\ (ncand_per_cluster <= max_cands_per_cluster) # check for any remaining triggers", "VOEvent queue on master node :param bool connect_lofar: Whether or", "source dm if available if dm_src is not None: dm_to_send", "and whether or not a new trigger can be sent", "'pointing': pointing, 'dmgal': dmgal } self.logger.info(\"Setting {src_name} trigger DM range", "\"\"\" Cluster triggers and run IQUV and/or LOFAR triggering :param", ":param bool connect_lofar: Whether or not to connect to LOFAR", "lofar_trigger.update(sys_params) self.logger.info(\"Sending LOFAR trigger to LOFAR Trigger system\") self.lofar_queue.put(lofar_trigger) if", "Pointing for LOFAR triggering (default: None) :param bool skip_lofar: Skip", "try: dm_src = self.source_list[key][source] src_type = key[:-1] except KeyError: pass", "np.array(cluster_downsamp)[mask].astype(int) cluster_sb = np.array(cluster_sb)[mask].astype(int) ncand_per_cluster = np.array(ncand_per_cluster)[mask].astype(int) ncluster = len(cluster_snr)", "{}, \" \"setting parset to None: {}\".format(master_config_file, e)) parset =", "known = 'known' else: known = 'new' self.logger.info(\"Clustered {} raw", "LOFAR triggering (default: False) \"\"\" # cluster using IQUV thresholds", "selecting trigger with highest S/N\") # argmax also works if", "skip_lofar=False): \"\"\" Cluster triggers and run IQUV and/or LOFAR triggering", "works if there is one trigger, so just run it", "{}, \" \"downsamp <= {}\".format(snr_min_lofar, width_max_lofar)) else: # new source,", "= obs_config self.observation_running = True # (re)load source list in", "VOEvent system based on AMBER candidates 1. Cluster incoming triggers", "is not None: name = src_type else: name = 'candidate'", "from queue and start processing for known and/or new sources", "width = TSAMP.to(u.ms) * cluster_downsamp[mask][ind] # astropy units only knows", "a new trigger can be sent # check if there", "str datetimesource: Field name with date and time :param float", "# store when we are allowed to do IQUV /", "connect_vo=True, connect_lofar=True, **kwargs): \"\"\" :param bool connect_vo: Whether or not", "({})\".format(e)) self.lofar_queue = self.dummy_queue self.have_lofar = False # process triggers", "(this indicates RFI) mask = (cluster_snr >= snr_min_lofar) & (cluster_dm", "timestamp) # create SkyCoord object pointing = SkyCoord(c1, c2) return", "self.obs_config = obs_config self.observation_running = True # (re)load source list", "to connect to VOEvent Generator, setting dummy queue ({})\".format(e)) self.vo_queue", "source (default: None) :param float width_max: maximum width (default: inf)", "\"\"\" try: with open(self.source_file, 'r') as f: source_list = yaml.load(f,", "darc.external import tools from darc import util class AMBERClusteringException(Exception): pass", "empty if only header was received if not triggers: self.logger.info(\"Only", "SkyCoord(c1, c2) return pointing def _load_parset(self, obs_config): \"\"\" Load the", "if there are multiple triggers if ncluster > 1: self.logger.info(\"Multiple", "parse pointing for CB{:02d} ({})\".format(beam, e)) return None # convert", "thresholds if src_type is not None: # known source, use", "bool connect_vo: Whether or not to connect to VOEvent queue", "src_name in self.lofar_trigger_sources: # check CB number try: allowed_cbs =", "sources \"\"\" # set observation parameters utc_start = Time(self.obs_config['startpacket'] /", "self.time_iquv = Time.now() # connect to VOEvent generator if self.connect_vo:", "# add system parameters (dt, central freq (GHz), bandwidth (MHz))", "set a source name if src_type is not None: name", "[] # clear header self.hdr_mapping = {} # clear config", "command received from queue :param dict command: Command to process", "Observation configuration :param bool reload: reload service settings (default: True)", "given thresholds # also remove triggers where number of raw", "= False # connect to LOFAR trigger if self.connect_lofar: try:", "not in allowed_cbs: return except KeyError: # any CB is", "trigger IQUV yet, next possible time: {}\".format(self.time_iquv)) else: self.logger.info(\"Sending IQUV", "self.logger.error(\"No VOEvent Generator connection available - not sending VO trigger\")", "cb key is not present pass else: # source known,", "algorithm triggers_for_clustering = triggers[:, (self.hdr_mapping['DM'], self.hdr_mapping['SNR'], self.hdr_mapping['time'], self.hdr_mapping['integration_step'], self.hdr_mapping['beam_id'])] #", "{} for source {}\".format(alias, source)) source = alias # check", "put on VO queue lofar_trigger = {'dm': dm_to_send, 'dm_err': dm_err,", "aliases try: alias = self.source_list['aliases'][source] except KeyError: # not found", "to the server elif not self.have_lofar: self.logger.error(\"No LOFAR Trigger connection", "clear threads for key, thread in self.threads.items(): if thread is", "self.thresh_iquv['width_max'], 'snr_min': self.thresh_iquv['snr_min'], 'pointing': pointing, 'dmgal': dmgal } # if", "to 0 ({})\".format(e)) beam = 0 # read beam coordinates", "triggering now = Time.now() if now < self.time_iquv: self.logger.warning(\"Cannot trigger", "indicates RFI) mask = (cluster_snr >= snr_min_lofar) & (cluster_dm >=", "import os from time import sleep import yaml import ast", "freq (GHz), bandwidth (MHz)) lofar_trigger.update(sys_params) self.logger.info(\"Sending LOFAR trigger to LOFAR", "cent_freq} pointing = self._get_pointing() dmgal = util.get_ymw16(self.obs_config['parset'], self.obs_config['beam'], self.logger) #", "decode raw_parset = util.decode_parset(master_config['parset']) parset = util.parse_parset(raw_parset) except Exception as", "kwargs=thresh_src) self.threads['trigger_known_source'].start() # new source triggering self.threads['trigger_new_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering,", "pick columns to feed to clustering algorithm triggers_for_clustering = triggers[:,", "from darc.external import tools from darc import util class AMBERClusteringException(Exception):", "from astropy.coordinates import SkyCoord from darc import DARCBase, VOEventQueueServer, LOFARTriggerQueueServer", "# Read raw config with open(master_config_file) as f: master_config =", "if self.connect_vo: try: self.vo_queue = self.voevent_connector() self.logger.info(\"Connected to VOEvent Generator", "else: # replace source by alias so we can look", "all LOFAR thresholds snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar = max(dmgal *", "sys_params['nu_GHz'] * 1000. max_freq = cent_freq + .5 * BANDWIDTH.to(u.MHz).value", "1. Cluster incoming triggers 2. Apply thresholds (separate for known", "Try to get DM for a known source :return: DM", "key = server_config['server_auth'].encode() server = LOFARTriggerQueueServer(address=(MASTER, port), authkey=key) server.connect() return", "darc.definitions import TSAMP, NCHAN, BANDWIDTH, MASTER, TIME_UNIT from darc.external import", "width).to(u.mJy).value / 1000. # select known source DM if available", "sending VO trigger\") def _process_triggers(self): \"\"\" Read thresholds (DM, width,", "(utc_start + TimeDelta(cluster_time[mask][ind] - dm_delay, format='sec')).isot # set a source", "= util.radec_to_hadec(c1, c2, timestamp) # create SkyCoord object pointing =", "connect_lofar: Whether or not to connect to LOFAR trigger queue", "any CB is valid if cb key is not present", "point if self.connect_lofar: try: self.lofar_queue = self.lofar_connector() self.logger.info(\"Connected to LOFAR", "# select known source DM if available if dm_src is", "Time.now() if now < self.time_iquv: self.logger.warning(\"Cannot trigger IQUV yet, next", "effectively does nothing here because the value is the same", "* u.deg except Exception as e: self.logger.error(\"Could not parse pointing", "\"Failed to load parset from master config file {}, \"", "class-wide list can receive new triggers without those getting lost", "src_type, source def _check_triggers(self, triggers, sys_params, utc_start, datetimesource, dm_min=0, dm_max=np.inf,", "np.array(cluster_snr)[mask] cluster_dm = np.array(cluster_dm)[mask] cluster_time = np.array(cluster_time)[mask] cluster_downsamp = np.array(cluster_downsamp)[mask].astype(int)", "server.connect() return server.get_queue() def lofar_connector(self): \"\"\" Connect to the LOFAR", "with date and time :param float dm_min: minimum DM (default:", "as f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['voevent_generator'] port = server_config['server_port'] key", "master node \"\"\" # Load LOFAR trigger server settings LOFARTriggerQueueServer.register('get_queue')", "set observation parameters utc_start = Time(self.obs_config['startpacket'] / TIME_UNIT, format='unix') datetimesource", "use same DM threshold as IQUV, but apply width and", "not found in input config, looking for master parset\") #", "IQUV dada_triggers = [] for i in range(ncluster): # send", "parset obs_config['parset'] = self._load_parset(obs_config) # set config self.obs_config = obs_config", "connected to the server elif not self.have_lofar: self.logger.error(\"No LOFAR Trigger", "ignoring\") else: with self.lock: self.amber_triggers.append(command['trigger']) elif command['command'] == 'get_attr': self.get_attribute(command)", "(default: None) :param float dmgal: galactic maximum DM :param astropy.coordinates.SkyCoord", "and start listening for amber triggers on queue :param dict", "= \\ tools.get_triggers(triggers, dm_min=dm_min, dm_max=dm_max, sig_thresh=snr_min, t_window=self.clustering_window, read_beam=True, return_clustcounts=True, sb_filter=self.sb_filter,", "explicitly disabled if src_type == 'pulsar' or skip_lofar: return #", "server.get_queue() def lofar_connector(self): \"\"\" Connect to the LOFAR triggering system", "= c1 * u.deg c2 = c2 * u.deg except", "= line below to work # no limit on candidates", "= np.argmax(cluster_snr[mask]) # estimate flux density based on peak S/N", "AMBER triggers from queue and start processing for known and/or", "\"setting parset to None: {}\".format(master_config_file, e)) parset = None return", "we can do triggering now = Time.now() if now <", "LOFAR triggers were sent # and whether or not a", "False # try connecting to LOFAR trigger serverr if enabled", "VOEvent generator on the master node \"\"\" # Load VO", "DM uncertainty to DM delay across pulse width # Apertif", "delay across pulse width # Apertif has roughly 1 DM", "processing for known and/or new sources \"\"\" # set observation", "remaining triggers if np.any(mask): ncluster = np.sum(mask) self.logger.info(\"Found {} possible", "Stop observation \"\"\" # set running to false self.observation_running =", "self.thresh_lofar['snr_min'] dm_min_lofar = dm_min width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster = np.inf", "astropy units only knows mJy, but the VOEvent Generator expects", "for new sources if src_type is not None and src_name", "IQUV trigger\") # update last trigger time self.time_iquv = now", "arcmin, CB 'name': name, 'src_name': src_name, 'datetimesource': datetimesource, 'utc': utc_arr,", "Parse obs config and start listening for amber triggers on", "ncluster == 0: return # there are clusters, do IQUV", "parset, will not do known-source triggering\") return None, None, None", "float dm_min: minimum DM (default: 0) :param float dm_max: maximum", "possible time: {}\".format(self.time_iquv)) else: self.logger.info(\"Sending IQUV trigger\") # update last", "with open(self.config_file, 'r') as f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['lofar_trigger'] port", "/ LOFAR triggering self.time_iquv = Time.now() # connect to VOEvent", "Trigger, setting dummy queue ({})\".format(e)) self.lofar_queue = self.dummy_queue self.have_lofar =", "mJy, but the VOEvent Generator expects Jy flux = util.get_flux(snr,", "= 1 ms delay across band dm_err = width.to(u.ms).value #", "raise AMBERClusteringException(\"Cannot load source list: {}\".format(e)) return source_list def process_command(self,", "with self.lock: triggers = self.amber_triggers self.amber_triggers = [] # check", "triggers and run IQUV and/or LOFAR triggering :param list triggers:", "= self.thresh_lofar['snr_min'] dm_min_lofar = dm_min width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster =", "= \"task.beamSet.0.compoundBeam.{}.phaseCenter\".format(beam) c1, c2 = ast.literal_eval(parset[key].replace('deg', '')) c1 = c1", "self.source_list[key][source] src_type = key[:-1] except KeyError: pass else: break return", "self.logger.info(\"Sending IQUV trigger\") # update last trigger time self.time_iquv =", ":param dict sys_params: System parameters (dt, delta_nu_MHz, nu_GHz) :param str", "= server_config['server_port'] key = server_config['server_auth'].encode() server = VOEventQueueServer(address=(MASTER, port), authkey=key)", "to VOEvent queue on master node :param bool connect_lofar: Whether", "triggering if src_type is not None: self.threads['trigger_known_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering,", "with known source DMs :return: source list with dict per", "not None: known = 'known' else: known = 'new' self.logger.info(\"Clustered", "observation timestamp = Time(parset['task.startTime']) + .5 * float(parset['task.duration']) * u.s", "t_window=self.clustering_window, read_beam=True, return_clustcounts=True, sb_filter=self.sb_filter, sb_filter_period_min=self.sb_filter_period_min, sb_filter_period_max=self.sb_filter_period_max, **sys_params) # select on", "= yaml.load(f, Loader=yaml.SafeLoader) except OSError as e: raise AMBERClusteringException(\"Cannot load", "are clusters, do IQUV triggering # check if we can", "[trigger for trigger in triggers if not trigger.startswith('#')] # triggers", "triggering :param list triggers: Raw triggers :param dict sys_params: System", "self.observation_running: self.logger.error(\"Trigger(s) received but no observation is running - ignoring\")", "queue lofar_trigger = {'dm': dm_to_send, 'dm_err': dm_err, 'width': width.to(u.ms).value, #", "try: allowed_cbs = self.thresh_lofar_override['cb'] if isinstance(allowed_cbs, float): allowed_cbs = [allowed_cbs]", "= 'known' else: known = 'new' self.logger.info(\"Clustered {} raw triggers", "AMBER Clustering import os from time import sleep import yaml", "def process_command(self, command): \"\"\" Process command received from queue :param", "trigger server settings LOFARTriggerQueueServer.register('get_queue') with open(self.config_file, 'r') as f: server_config", ":param float width_max: maximum width (default: inf) :param float snr_min:", "key = server_config['server_auth'].encode() server = VOEventQueueServer(address=(MASTER, port), authkey=key) server.connect() return", "3. Put IQUV triggers on output queue 4. Put LOFAR", "file master_config_file = os.path.join(obs_config['master_dir'], 'parset', 'darc_master.parset') try: # Read raw", "# but it needs to be defined for the mask", "trigger to VOEvent system\") self.vo_queue.put(lofar_trigger) else: self.logger.error(\"No VOEvent Generator connection", "with open(master_config_file) as f: master_config = f.read().strip() # Convert to", "triggers without those getting lost with self.lock: triggers = self.amber_triggers", "triggering\") return None, None, None # check if source is", "do triggering now = Time.now() if now < self.time_iquv: self.logger.warning(\"Cannot", "self.threads['trigger_known_source'].start() # new source triggering self.threads['trigger_new_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params,", "nu_GHz) :param str utc_start: start time of observation, in format", "skip_lofar: return # select LOFAR thresholds if src_type is not", "at reference frequency = central frequency cent_freq = sys_params['nu_GHz'] *", "(default: True) \"\"\" # reload config if reload: self.load_config() #", "VOEvent Generator connection available - not sending VO trigger\") def", "# dummy queue self.logger.info(\"VO Generator connection disabled, setting dummy queue\")", "# create SkyCoord object pointing = SkyCoord(c1, c2) return pointing", "update last trigger time self.time_iquv = now + TimeDelta(self.thresh_iquv['interval'], format='sec')", "high (this indicates RFI) mask = (cluster_snr >= snr_min_lofar) &", "port), authkey=key) server.connect() return server.get_queue() def _get_source(self): \"\"\" Try to", "2. Apply thresholds (separate for known and new sources, and", "dm_err, 'width': width.to(u.ms).value, # ms 'snr': snr, 'flux': flux, #", "as f: master_config = f.read().strip() # Convert to dict master_config", "elif command['command'] == 'get_attr': self.get_attribute(command) else: self.logger.error(\"Unknown command received: {}\".format(command['command']))", "= None src_type = None for key in ['pulsars', 'frbs']:", "ncluster = np.sum(mask) self.logger.info(\"Found {} possible LOFAR trigger(s)\".format(ncluster)) # note:", "self.have_vo: self.logger.info(\"Sending same trigger to VOEvent system\") self.vo_queue.put(lofar_trigger) else: self.logger.error(\"No", "is not None: thread.join() self.threads[key] = None def voevent_connector(self): \"\"\"", "src_name, 'dm_min': max(dm_src - self.dm_range, self.dm_min_global), 'dm_max': dm_src + self.dm_range,", "width and S/N thresholds # DM_min effectively does nothing here", "header: {}\".format(key)) self.hdr_mapping = {} return # header should be", "'SNR'] for key in keys: try: self.hdr_mapping[key] = header.index(key) except", "feed to clustering algorithm triggers_for_clustering = triggers[:, (self.hdr_mapping['DM'], self.hdr_mapping['SNR'], self.hdr_mapping['time'],", "'tarr': cluster_time[mask][ind], 'importance': 0.1} # add system parameters (dt, central", "f.read().strip() # Convert to dict master_config = util.parse_parset(master_config) # extract", "if explicitly disabled if src_type == 'pulsar' or skip_lofar: return", "the triggers so class-wide list can receive new triggers without", "\" \"setting parset to None: {}\".format(master_config_file, e)) parset = None", ":param float dm_src: DM of known source (default: None) :param", "it always ind = np.argmax(cluster_snr[mask]) # estimate flux density based", "(GHz), bandwidth (MHz)) lofar_trigger.update(sys_params) self.logger.info(\"Sending LOFAR trigger to LOFAR Trigger", "not present pass else: # source known, CB valid: set", "_, ncand_per_cluster = \\ tools.get_triggers(triggers, dm_min=dm_min, dm_max=dm_max, sig_thresh=snr_min, t_window=self.clustering_window, read_beam=True,", "but the VOEvent Generator expects Jy flux = util.get_flux(snr, width).to(u.mJy).value", "os.path.join(obs_config['master_dir'], 'parset', 'darc_master.parset') try: # Read raw config with open(master_config_file)", "it needs to be defined for the mask = line", "for clustering Continuously read AMBER triggers from queue and start", "{}\".format(command['command'])) def start_observation(self, obs_config, reload=True): \"\"\" Parse obs config and", "service settings (default: True) \"\"\" # reload config if reload:", "header was received if not triggers: self.logger.info(\"Only header received -", "server.connect() return server.get_queue() def _get_source(self): \"\"\" Try to get DM", "# read beam try: beam = self.obs_config['beam'] except KeyError as", "from parset try: key = \"task.beamSet.0.compoundBeam.{}.phaseCenter\".format(beam) c1, c2 = ast.literal_eval(parset[key].replace('deg',", "dict per category \"\"\" try: with open(self.source_file, 'r') as f:", "this CB from parset :return: pointing SkyCoord \"\"\" # read", "not pointing information is available if pointing is None: self.logger.error(\"No", "'snr_min': self.snr_min_global, 'pointing': pointing, 'dmgal': dmgal } self.logger.info(\"Setting {src_name} trigger", "_get_pointing(self): \"\"\" Get pointing of this CB from parset :return:", "DARCBase, VOEventQueueServer, LOFARTriggerQueueServer from darc.definitions import TSAMP, NCHAN, BANDWIDTH, MASTER,", "trigger\") def _process_triggers(self): \"\"\" Read thresholds (DM, width, S/N) for", "to connect to LOFAR Trigger, setting dummy queue ({})\".format(e)) self.lofar_queue", "columns to feed to clustering algorithm triggers_for_clustering = triggers[:, (self.hdr_mapping['DM'],", "port = server_config['server_port'] key = server_config['server_auth'].encode() server = LOFARTriggerQueueServer(address=(MASTER, port),", "= np.array(ncand_per_cluster)[mask].astype(int) ncluster = len(cluster_snr) if src_type is not None:", "in input config, looking for master parset\") # Load the", "self.observation_running = False self.amber_triggers = [] self.source_list = None self.lock", "triggering system on the master node \"\"\" # Load LOFAR", "if not self.hdr_mapping: self.logger.error(\"First clusters received but header not found\")", "without those getting lost with self.lock: triggers = self.amber_triggers self.amber_triggers", "sys_params, utc_start, datetimesource), kwargs=thresh_src) self.threads['trigger_known_source'].start() # new source triggering self.threads['trigger_new_source']", "but failed at some point if self.connect_vo: try: self.vo_queue =", "dm_to_send * (cent_freq**-2 - max_freq**-2) utc_arr = (utc_start + TimeDelta(cluster_time[mask][ind]", "SkyCoord \"\"\" # read parset try: parset = self.obs_config['parset'] except", "params are present and create mapping to col index keys", "new sources \"\"\" # set observation parameters utc_start = Time(self.obs_config['startpacket']", "convert to numpy array try: triggers = np.array(list(map(lambda val: val.split(),", "None, 'src_name': None, 'dm_min': max(dmgal * self.thresh_iquv['dm_frac_min'], self.dm_min_global), 'dm_max': np.inf,", "new trigger can be sent # check if there are", "= ['beam_id', 'integration_step', 'time', 'DM', 'SNR'] for key in keys:", "if not self.hdr_mapping: for trigger in triggers: if trigger.startswith('#'): #", "self.obs_config['beam'], 'sb': cluster_sb[mask][ind], 'ymw16': dmgal, 'semiMaj': 15, # arcmin, CB", "triggers if not trigger.startswith('#')] # triggers is empty if only", "triggering (default: None) :param bool skip_lofar: Skip LOFAR triggering (default:", "obs_config self.observation_running = True # (re)load source list in case", "import TSAMP, NCHAN, BANDWIDTH, MASTER, TIME_UNIT from darc.external import tools", "load source list: {}\".format(e)) return source_list def process_command(self, command): \"\"\"", "set running to false self.observation_running = False # clear triggers", "cluster_sb, _, ncand_per_cluster = \\ tools.get_triggers(triggers, dm_min=dm_min, dm_max=dm_max, sig_thresh=snr_min, t_window=self.clustering_window,", "trigger IQUV dada_triggers = [] for i in range(ncluster): #", "first check aliases try: alias = self.source_list['aliases'][source] except KeyError: #", "self.logger.warning( \"Failed to load parset from master config file {},", "'semiMaj': 15, # arcmin, CB 'semiMin': 15, # arcmin, CB", "connect_lofar=True, **kwargs): \"\"\" :param bool connect_vo: Whether or not to", "# select on width mask = np.array(cluster_downsamp) <= width_max cluster_snr", "config with open(master_config_file) as f: master_config = f.read().strip() # Convert", "self.amber_triggers = [] # parse parset obs_config['parset'] = self._load_parset(obs_config) #", "KeyError: pass else: break return dm_src, src_type, source def _check_triggers(self,", "the VOEvent generator on the master node \"\"\" # Load", "'dec': pointing.dec.deg, # decimal deg 'cb': self.obs_config['beam'], 'sb': cluster_sb[mask][ind], 'ymw16':", "= False # clear triggers self.amber_triggers = [] # clear", "4. Put LOFAR triggers on remote LOFAR trigger queue and", "except KeyError: pass else: break return dm_src, src_type, source def", "pointing = self._get_pointing() dmgal = util.get_ymw16(self.obs_config['parset'], self.obs_config['beam'], self.logger) # get", "False self.logger.info(\"Setting new source trigger DM range to {dm_min} -", "15, # arcmin, CB 'name': name, 'src_name': src_name, 'datetimesource': datetimesource,", "assumed to be more strict for every parameter cluster_snr, cluster_dm,", "['beam_id', 'integration_step', 'time', 'DM', 'SNR'] for key in keys: try:", "with open(self.config_file, 'r') as f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['voevent_generator'] port", "= {} return # header should be present now if", "for LOFAR triggering (default: None) :param bool skip_lofar: Skip LOFAR", "'darc_master.parset') try: # Read raw config with open(master_config_file) as f:", "config if reload: self.load_config() # clean any old triggers self.amber_triggers", "on AMBER candidates 1. Cluster incoming triggers 2. Apply thresholds", "is None: self.logger.error(\"No pointing information available - cannot trigger LOFAR\")", "time of observation, in format readable by astropy.time.Time :param str", "whether or not pointing information is available if pointing is", "= server_config['server_port'] key = server_config['server_auth'].encode() server = LOFARTriggerQueueServer(address=(MASTER, port), authkey=key)", "def __init__(self, *args, connect_vo=True, connect_lofar=True, **kwargs): \"\"\" :param bool connect_vo:", "pointing SkyCoord \"\"\" # read parset try: parset = self.obs_config['parset']", "parset raw_parset = util.decode_parset(obs_config['parset']) # convert to dict and store", "self.hdr_mapping['beam_id'])] # known source and new source triggering, in thread", "'frbs']: try: dm_src = self.source_list[key][source] src_type = key[:-1] except KeyError:", "if trigger.startswith('#'): # read header, remove comment symbol header =", "setting dummy queue\") self.vo_queue = mp.Queue() self.have_vo = False #", "pointing, 'dmgal': dmgal } # if known source, check whether", "dm_min_lofar = max(dmgal * self.thresh_lofar['dm_frac_min'], self.dm_min_global) width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster", "['pulsars', 'frbs']: try: dm_src = self.source_list[key][source] src_type = key[:-1] except", "on width mask = np.array(cluster_downsamp) <= width_max cluster_snr = np.array(cluster_snr)[mask]", "and on VOEvent queue \"\"\" def __init__(self, *args, connect_vo=True, connect_lofar=True,", "listening for amber triggers on queue :param dict obs_config: Observation", "if np.any(mask): ncluster = np.sum(mask) self.logger.info(\"Found {} possible LOFAR trigger(s)\".format(ncluster))", "threshold as IQUV, but apply width and S/N thresholds #", "# set min and max DM for new sources with", "per cluster snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar = dm_min width_max_lofar =", "for key in ['pulsars', 'frbs']: try: dm_src = self.source_list[key][source] src_type", "loop while self.observation_running: if self.amber_triggers: # Copy the triggers so", "processing\") continue # split strings and convert to numpy array", "width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster = np.inf # Overrides for specific", "ncand_per_cluster = \\ tools.get_triggers(triggers, dm_min=dm_min, dm_max=dm_max, sig_thresh=snr_min, t_window=self.clustering_window, read_beam=True, return_clustcounts=True,", "+ .5 * BANDWIDTH.to(u.MHz).value dm_delay = 4.148808E3 * dm_to_send *", "name if src_type is not None: name = src_type else:", "of raw candidates is too high (this indicates RFI) mask", "\"\"\" Stop observation \"\"\" # set running to false self.observation_running", "should be present now if not self.hdr_mapping: self.logger.error(\"First clusters received", "DM threshold as IQUV, but apply width and S/N thresholds", "max_cands_per_cluster) # check for any remaining triggers if np.any(mask): ncluster", "\"task.beamSet.0.compoundBeam.{}.phaseCenter\".format(beam) c1, c2 = ast.literal_eval(parset[key].replace('deg', '')) c1 = c1 *", "object pointing = SkyCoord(c1, c2) return pointing def _load_parset(self, obs_config):", "yaml import ast import threading import multiprocessing as mp import", "except KeyError: # not found pass else: # replace source", "from clusters header: {}\".format(key)) self.hdr_mapping = {} return # header", "(default: 0) :param float dm_max: maximum DM (default: inf) :param", "band dm_err = width.to(u.ms).value # calculate arrival time at reference", "# also remove triggers where number of raw candidates is", "received: {}\".format(command['command'])) def start_observation(self, obs_config, reload=True): \"\"\" Parse obs config", "list can receive new triggers without those getting lost with", "Loader=yaml.SafeLoader)['lofar_trigger'] port = server_config['server_port'] key = server_config['server_auth'].encode() server = LOFARTriggerQueueServer(address=(MASTER,", "triggers into {} IQUV trigger(s) \" \"for {} source\".format(len(triggers), ncluster,", "node :param bool connect_lofar: Whether or not to connect to", "SkyCoord object pointing = SkyCoord(c1, c2) return pointing def _load_parset(self,", "= np.array(cluster_time)[mask] cluster_downsamp = np.array(cluster_downsamp)[mask].astype(int) cluster_sb = np.array(cluster_sb)[mask].astype(int) ncand_per_cluster =", "c2, timestamp) # create SkyCoord object pointing = SkyCoord(c1, c2)", "source and new source triggering, in thread so clustering itself", "\"\"\" # reload config if reload: self.load_config() # clean any", "for trigger in triggers: if trigger.startswith('#'): # read header, remove", "type (pulsar, frb, None) :param str src_name: Source name (default:", "not None: thresh_src = {'dm_src': dm_src, 'src_type': src_type, 'src_name': src_name,", "KeyError: self.logger.error(\"Cannot get source name from parset, will not do", "get known source dm and type dm_src, src_type, src_name =", "on master node\") self.have_lofar = True except Exception as e:", "ms delay across band dm_err = width.to(u.ms).value # calculate arrival", "# remove headers from triggers (i.e. any trigger starting with", "parset, setting CB to 0 ({})\".format(e)) beam = 0 #", "parset = util.parse_parset(raw_parset) except KeyError: self.logger.info(\"Observation parset not found in", "to work # no limit on candidates per cluster snr_min_lofar", "setting dummy queue ({})\".format(e)) self.lofar_queue = self.dummy_queue self.have_lofar = False", "self.load_config() # clean any old triggers self.amber_triggers = [] #", "} self.logger.info(\"Setting {src_name} trigger DM range to {dm_min} - {dm_max},", ":return: pointing SkyCoord \"\"\" # read parset try: parset =", "max(dmgal * self.thresh_iquv['dm_frac_min'], self.dm_min_global), 'dm_max': np.inf, 'width_max': self.thresh_iquv['width_max'], 'snr_min': self.thresh_iquv['snr_min'],", "self.threads['trigger_known_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_src) self.threads['trigger_known_source'].start() #", "estimate flux density based on peak S/N and width snr", "LOFAR) 3. Put IQUV triggers on output queue 4. Put", "except Exception as e: self.logger.error(\"Failed to connect to LOFAR Trigger,", "parameters utc_start = Time(self.obs_config['startpacket'] / TIME_UNIT, format='unix') datetimesource = self.obs_config['datetimesource']", "col index keys = ['beam_id', 'integration_step', 'time', 'DM', 'SNR'] for", "can receive new triggers without those getting lost with self.lock:", "astropy.time.Time :param str datetimesource: Field name with date and time", "master_config = f.read().strip() # Convert to dict master_config = util.parse_parset(master_config)", "0.5 * BANDWIDTH).to(u.GHz).value sys_params = {'dt': dt, 'delta_nu_MHz': chan_width, 'nu_GHz':", "connect to VOEvent queue on master node :param bool connect_lofar:", "LOFAR trigger server settings LOFARTriggerQueueServer.register('get_queue') with open(self.config_file, 'r') as f:", "# always do this in case a connection was available", "pass else: # source known, CB valid: set thresholds snr_min_lofar", "convert to dict and store parset = util.parse_parset(raw_parset) except KeyError:", "self.amber_triggers self.amber_triggers = [] # check for header (always, because", "is in source list # first check aliases try: alias", "pulse width # Apertif has roughly 1 DM unit =", "e: self.logger.error(\"Cannot read beam from parset, setting CB to 0", "if not triggers: self.logger.info(\"Only header received - Canceling processing\") continue", "- max_freq**-2) utc_arr = (utc_start + TimeDelta(cluster_time[mask][ind] - dm_delay, format='sec')).isot", "= f.read().strip() # Convert to dict master_config = util.parse_parset(master_config) #", "= None self.observation_running = False self.amber_triggers = [] self.source_list =", "IQUV triggers on output queue 4. Put LOFAR triggers on", "'trigger', 'trigger': dada_triggers}) # skip LOFAR triggering for pulsars or", "IQUV trigger(s) \" \"for {} source\".format(len(triggers), ncluster, known)) # return", "VO server settings VOEventQueueServer.register('get_queue') with open(self.config_file, 'r') as f: server_config", "i in range(ncluster): # send known source dm if available", "Generator expects Jy flux = util.get_flux(snr, width).to(u.mJy).value / 1000. #", "source, use same DM threshold as IQUV, but apply width", "DM of known source (default: None) :param float width_max: maximum", "only knows mJy, but the VOEvent Generator expects Jy flux", "self.dummy_queue = mp.Queue() self.threads = {} self.hdr_mapping = {} self.obs_config", "system\") self.lofar_queue.put(lofar_trigger) if self.have_vo: self.logger.info(\"Sending same trigger to VOEvent system\")", "LOFAR triggering self.time_iquv = Time.now() # connect to VOEvent generator", "Apertif has roughly 1 DM unit = 1 ms delay", "point of the observation timestamp = Time(parset['task.startTime']) + .5 *", "'r') as f: source_list = yaml.load(f, Loader=yaml.SafeLoader) except OSError as", "header self.hdr_mapping = {} # clear config self.obs_config = None", "return # header should be present now if not self.hdr_mapping:", "cluster_snr, cluster_dm, cluster_time, cluster_downsamp, cluster_sb, _, ncand_per_cluster = \\ tools.get_triggers(triggers,", "\"max downsamp={width_max}, min S/N={snr_min}, skip LOFAR \" \"triggering={skip_lofar}\".format(**thresh_new)) # main", "'dmgal': dmgal } self.logger.info(\"Setting {src_name} trigger DM range to {dm_min}", "self.threads = {} self.hdr_mapping = {} self.obs_config = None self.observation_running", "IQUV # but it needs to be defined for the", "known-source triggering\") return None, None, None # check if source", "'nu_GHz': cent_freq} pointing = self._get_pointing() dmgal = util.get_ymw16(self.obs_config['parset'], self.obs_config['beam'], self.logger)", "parset\") # Load the parset from the master parset file", "f: master_config = f.read().strip() # Convert to dict master_config =", "obs config and start listening for amber triggers on queue", "generator if self.connect_vo: try: self.vo_queue = self.voevent_connector() self.logger.info(\"Connected to VOEvent", "DM if available if dm_src is not None: dm_to_send =", "present pass else: # source known, CB valid: set thresholds", "= self.voevent_connector() self.logger.info(\"Connected to VOEvent Generator on master node\") self.have_vo", "connection was available before, but failed at some point if", "dict master_config = util.parse_parset(master_config) # extract obs parset and decode", "= connect_vo self.connect_lofar = connect_lofar self.dummy_queue = mp.Queue() self.threads =", "snr_min_lofar) & (cluster_dm >= dm_min_lofar) & \\ (cluster_downsamp <= width_max_lofar)", "<gh_stars>0 #!/usr/bin/env python3 # # AMBER Clustering import os from", "select LOFAR thresholds if src_type is not None: # known", "for IQUV # but it needs to be defined for", "to LOFAR Trigger, setting dummy queue ({})\".format(e)) self.lofar_queue = self.dummy_queue", "<= width_max cluster_snr = np.array(cluster_snr)[mask] cluster_dm = np.array(cluster_dm)[mask] cluster_time =", "# new source triggering self.threads['trigger_new_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start,", "roughly 1 DM unit = 1 ms delay across band", "\"downsamp <= {}\".format(snr_min_lofar, width_max_lofar)) else: # new source, apply all", "return except KeyError: # any CB is valid if cb", "== 'HADEC': # Get RA at the mid point of", "and/or new sources \"\"\" # set observation parameters utc_start =", "# read header, remove comment symbol header = trigger.split()[1:] self.logger.info(\"Received", "util.decode_parset(obs_config['parset']) # convert to dict and store parset = util.parse_parset(raw_parset)", ":param float dm_min: minimum DM (default: 0) :param float dm_max:", "'get_attr': self.get_attribute(command) else: self.logger.error(\"Unknown command received: {}\".format(command['command'])) def start_observation(self, obs_config,", "unknown DM thresh_new = {'src_type': None, 'src_name': None, 'dm_min': max(dmgal", "known)) # return if there are no clusters if ncluster", "to false self.observation_running = False # clear triggers self.amber_triggers =", "OSError as e: raise AMBERClusteringException(\"Cannot load source list: {}\".format(e)) return", "if pointing is None: self.logger.error(\"No pointing information available - cannot", "clustering itself does not # delay next run # known", "format='unix') datetimesource = self.obs_config['datetimesource'] dt = TSAMP.to(u.second).value chan_width = (BANDWIDTH", "# Load LOFAR trigger server settings LOFARTriggerQueueServer.register('get_queue') with open(self.config_file, 'r')", "HADEC is used if parset['task.directionReferenceFrame'].upper() == 'HADEC': # Get RA", "self.have_lofar = True except Exception as e: self.logger.error(\"Failed to connect", "Connect to the VOEvent generator on the master node \"\"\"", "as f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['lofar_trigger'] port = server_config['server_port'] key", "readable by astropy.time.Time :param str datetimesource: Field name with date", "defined for the mask = line below to work #", "failed at some point if self.connect_vo: try: self.vo_queue = self.voevent_connector()", "import ast import threading import multiprocessing as mp import numpy", "1000. # select known source DM if available if dm_src", "in self.lofar_trigger_sources: thresh_new['skip_lofar'] = not self.thresh_lofar['trigger_on_new_sources'] else: thresh_new['skip_lofar'] = False", "True except Exception as e: self.logger.error(\"Failed to connect to VOEvent", "# argmax also works if there is one trigger, so", "index keys = ['beam_id', 'integration_step', 'time', 'DM', 'SNR'] for key", "start processing for known and/or new sources \"\"\" # set", "dt = TSAMP.to(u.second).value chan_width = (BANDWIDTH / float(NCHAN)).to(u.MHz).value cent_freq =", "# set observation parameters utc_start = Time(self.obs_config['startpacket'] / TIME_UNIT, format='unix')", "on master node # decode the parset raw_parset = util.decode_parset(obs_config['parset'])", "process triggers: {}\".format(e)) continue # pick columns to feed to", "self.dm_min_global) width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster = self.thresh_lofar['max_cands_per_cluster'] # create mask", "sent # check if there are multiple triggers if ncluster", "flux, # Jy 'ra': pointing.ra.deg, # decimal deg 'dec': pointing.dec.deg,", "header: {}\".format(header)) # Check if all required params are present", "np.array(cluster_dm)[mask] cluster_time = np.array(cluster_time)[mask] cluster_downsamp = np.array(cluster_downsamp)[mask].astype(int) cluster_sb = np.array(cluster_sb)[mask].astype(int)", "server_config['server_auth'].encode() server = LOFARTriggerQueueServer(address=(MASTER, port), authkey=key) server.connect() return server.get_queue() def", "[] for i in range(ncluster): # send known source dm", "== 0: return # there are clusters, do IQUV triggering", ":param str src_name: Source name (default: None) :param float dmgal:", "sources if src_type is not None and src_name in self.lofar_trigger_sources:", "* BANDWIDTH.to(u.MHz).value dm_delay = 4.148808E3 * dm_to_send * (cent_freq**-2 -", "# decode the parset raw_parset = util.decode_parset(obs_config['parset']) # convert to", "dm_src, 'src_type': src_type, 'src_name': src_name, 'dm_min': max(dm_src - self.dm_range, self.dm_min_global),", "= {'dm': dm_to_send, 'dm_err': dm_err, 'width': width.to(u.ms).value, # ms 'snr':", "# dummy queue self.logger.info(\"LOFAR Trigger connection disabled, setting dummy queue\")", "triggers :param dict sys_params: System parameters (dt, delta_nu_MHz, nu_GHz) :param", "cluster_sb[mask][ind], 'ymw16': dmgal, 'semiMaj': 15, # arcmin, CB 'semiMin': 15,", "keys = ['beam_id', 'integration_step', 'time', 'DM', 'SNR'] for key in", "source = alias # check if source is a known", "_get_source(self): \"\"\" Try to get DM for a known source", "(re)load source list in case of changes self.source_list = self._load_source_list()", "for key in keys: try: self.hdr_mapping[key] = header.index(key) except ValueError:", "\"\"\" # set observation parameters utc_start = Time(self.obs_config['startpacket'] / TIME_UNIT,", "but header not found\") continue # remove headers from triggers", "Jy 'ra': pointing.ra.deg, # decimal deg 'dec': pointing.dec.deg, # decimal", "self.obs_config['beam'] not in allowed_cbs: return except KeyError: # any CB", "observation, in format readable by astropy.time.Time :param str datetimesource: Field", "\"\"\" Parse obs config and start listening for amber triggers", "to numpy array try: triggers = np.array(list(map(lambda val: val.split(), triggers)),", "# arcmin, CB 'name': name, 'src_name': src_name, 'datetimesource': datetimesource, 'utc':", "None: name = src_type else: name = 'candidate' # check", "process_command(self, command): \"\"\" Process command received from queue :param dict", "cluster_dm, cluster_time, cluster_downsamp, cluster_sb, _, ncand_per_cluster = \\ tools.get_triggers(triggers, dm_min=dm_min,", "* u.MHz + 0.5 * BANDWIDTH).to(u.GHz).value sys_params = {'dt': dt,", "false self.observation_running = False # clear triggers self.amber_triggers = []", "for the mask = line below to work # no", "cluster_snr[i], 'time': cluster_time[i], 'utc_start': utc_start} dada_triggers.append(dada_trigger) self.target_queue.put({'command': 'trigger', 'trigger': dada_triggers})", "ast import threading import multiprocessing as mp import numpy as", "* BANDWIDTH).to(u.GHz).value sys_params = {'dt': dt, 'delta_nu_MHz': chan_width, 'nu_GHz': cent_freq}", "self.logger.info(\"Only header received - Canceling processing\") continue # split strings", "'r') as f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['lofar_trigger'] port = server_config['server_port']", "parset try: source = self.obs_config['parset']['task.source.name'] except KeyError: self.logger.error(\"Cannot get source", "True except Exception as e: self.logger.error(\"Failed to connect to LOFAR", "# send known source dm if available if dm_src is", "a source name if src_type is not None: name =", "read AMBER triggers from queue and start processing for known", "triggers if np.any(mask): ncluster = np.sum(mask) self.logger.info(\"Found {} possible LOFAR", "util.get_ymw16(self.obs_config['parset'], self.obs_config['beam'], self.logger) # get known source dm and type", "self.logger.error(\"Failed to connect to LOFAR Trigger, setting dummy queue ({})\".format(e))", "cluster_dm[i] dada_trigger = {'stokes': 'IQUV', 'dm': dm_to_send, 'beam': cluster_sb[i], 'width':", "* (cent_freq**-2 - max_freq**-2) utc_arr = (utc_start + TimeDelta(cluster_time[mask][ind] -", "Load the observation parset :param dict obs_config: Observation config :return:", "dm_delay, format='sec')).isot # set a source name if src_type is", "(ncand_per_cluster <= max_cands_per_cluster) # check for any remaining triggers if", "self.thresh_lofar_override['snr_min'] width_max_lofar = self.thresh_lofar_override['width_max'] self.logger.warning(\"Setting LOFAR trigger thresholds: S/N >", "= LOFARTriggerQueueServer(address=(MASTER, port), authkey=key) server.connect() return server.get_queue() def _get_source(self): \"\"\"", "# set a source name if src_type is not None:", "self.dm_range, self.dm_min_global), 'dm_max': dm_src + self.dm_range, 'width_max': np.inf, 'snr_min': self.snr_min_global,", "deg 'cb': self.obs_config['beam'], 'sb': cluster_sb[mask][ind], 'ymw16': dmgal, 'semiMaj': 15, #", "= [] self.source_list = None self.lock = mp.Lock() # store", "same DM threshold as IQUV, but apply width and S/N", "LOFAR trigger if self.connect_lofar: try: self.lofar_queue = self.lofar_connector() self.logger.info(\"Connected to", "dm_src dm_err = 0. else: dm_to_send = cluster_dm[mask][ind] # set", "is running - ignoring\") else: with self.lock: self.amber_triggers.append(command['trigger']) elif command['command']", "# get source name from parset try: source = self.obs_config['parset']['task.source.name']", "self.threads['processing'] = threading.Thread(target=self._process_triggers) self.threads['processing'].start() self.logger.info(\"Observation started\") def stop_observation(self, *args, **kwargs):", "CB 'name': name, 'src_name': src_name, 'datetimesource': datetimesource, 'utc': utc_arr, 'tarr':", "Loader=yaml.SafeLoader) except OSError as e: raise AMBERClusteringException(\"Cannot load source list:", "read_beam=True, return_clustcounts=True, sb_filter=self.sb_filter, sb_filter_period_min=self.sb_filter_period_min, sb_filter_period_max=self.sb_filter_period_max, **sys_params) # select on width", "self.thresh_lofar['max_cands_per_cluster'] # create mask for given thresholds # also remove", "triggers self.amber_triggers = [] # parse parset obs_config['parset'] = self._load_parset(obs_config)", "except KeyError as e: self.logger.error(\"Cannot read parset ({})\".format(e)) return None", "float snr_min: mininum S/N (default: 8) :param str src_type: Source", "= Time(parset['task.startTime']) + .5 * float(parset['task.duration']) * u.s c1, c2", "node \"\"\" # Load VO server settings VOEventQueueServer.register('get_queue') with open(self.config_file,", "list with dict per category \"\"\" try: with open(self.source_file, 'r')", "and start processing for known and/or new sources \"\"\" #", "bool reload: reload service settings (default: True) \"\"\" # reload", "# Copy the triggers so class-wide list can receive new", "False # clear triggers self.amber_triggers = [] # clear header", "known source, else None \"\"\" # get source name from", "src_type = None for key in ['pulsars', 'frbs']: try: dm_src", "True) \"\"\" # reload config if reload: self.load_config() # clean", "on the master node \"\"\" # Load LOFAR trigger server", "= sys_params['nu_GHz'] * 1000. max_freq = cent_freq + .5 *", "Read raw config with open(master_config_file) as f: master_config = f.read().strip()", "continue # pick columns to feed to clustering algorithm triggers_for_clustering", "trigger if self.connect_lofar: try: self.lofar_queue = self.lofar_connector() self.logger.info(\"Connected to LOFAR", "else None \"\"\" # get source name from parset try:", "command: Command to process \"\"\" if command['command'] == 'trigger': if", "'width_max': self.thresh_iquv['width_max'], 'snr_min': self.thresh_iquv['snr_min'], 'pointing': pointing, 'dmgal': dmgal } #", "triggering (default: False) \"\"\" # cluster using IQUV thresholds #", "remove headers from triggers (i.e. any trigger starting with #)", "based on peak S/N and width snr = cluster_snr[mask][ind] width", "inf) :param float snr_min: mininum S/N (default: 8) :param str", "if src_type is not None: known = 'known' else: known", "pointing: Pointing for LOFAR triggering (default: None) :param bool skip_lofar:", "Get pointing of this CB from parset :return: pointing SkyCoord", "= self.obs_config['beam'] except KeyError as e: self.logger.error(\"Cannot read beam from", "split strings and convert to numpy array try: triggers =", "isinstance(allowed_cbs, float): allowed_cbs = [allowed_cbs] if self.obs_config['beam'] not in allowed_cbs:", "self._get_pointing() dmgal = util.get_ymw16(self.obs_config['parset'], self.obs_config['beam'], self.logger) # get known source", "= util.parse_parset(master_config) # extract obs parset and decode raw_parset =", "== 'pulsar' or skip_lofar: return # select LOFAR thresholds if", "master node # decode the parset raw_parset = util.decode_parset(obs_config['parset']) #", "of when LOFAR triggers were sent # and whether or", "'dm_min': max(dm_src - self.dm_range, self.dm_min_global), 'dm_max': dm_src + self.dm_range, 'width_max':", "to VOEvent Generator on master node\") self.have_vo = True except", "source triggering if src_type is not None: self.threads['trigger_known_source'] = threading.Thread(target=self._check_triggers,", "min S/N={snr_min}\".format(**thresh_src)) # set min and max DM for new", "self.amber_triggers = [] self.source_list = None self.lock = mp.Lock() #", "(self.obs_config['min_freq'] * u.MHz + 0.5 * BANDWIDTH).to(u.GHz).value sys_params = {'dt':", "from parset :return: pointing SkyCoord \"\"\" # read parset try:", "amber triggers on queue :param dict obs_config: Observation configuration :param", "{'stokes': 'IQUV', 'dm': dm_to_send, 'beam': cluster_sb[i], 'width': cluster_downsamp[i], 'snr': cluster_snr[i],", "Clustering import os from time import sleep import yaml import", "utc_arr, 'tarr': cluster_time[mask][ind], 'importance': 0.1} # add system parameters (dt,", "# source known, CB valid: set thresholds snr_min_lofar = self.thresh_lofar_override['snr_min']", "available - not sending VO trigger\") def _process_triggers(self): \"\"\" Read", "cluster snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar = dm_min width_max_lofar = self.thresh_lofar['width_max']", "timestamp = Time(parset['task.startTime']) + .5 * float(parset['task.duration']) * u.s c1,", "is valid if cb key is not present pass else:", ".5 * BANDWIDTH.to(u.MHz).value dm_delay = 4.148808E3 * dm_to_send * (cent_freq**-2", "remove triggers where number of raw candidates is too high", "to clustering algorithm triggers_for_clustering = triggers[:, (self.hdr_mapping['DM'], self.hdr_mapping['SNR'], self.hdr_mapping['time'], self.hdr_mapping['integration_step'],", "# try connecting to LOFAR trigger serverr if enabled #", "LOFAR trigger queue on master node \"\"\" super(AMBERClustering, self).__init__(*args, **kwargs)", "obs_config): \"\"\" Load the observation parset :param dict obs_config: Observation", "required params are present and create mapping to col index", "dm_min=0, dm_max=np.inf, dm_src=None, width_max=np.inf, snr_min=8, src_type=None, src_name=None, dmgal=0, pointing=None, skip_lofar=False):", "by astropy.time.Time :param str datetimesource: Field name with date and", "line below to work # no limit on candidates per", "else: # dummy queue self.logger.info(\"VO Generator connection disabled, setting dummy", "pointing, 'dmgal': dmgal } self.logger.info(\"Setting {src_name} trigger DM range to", "nothing here because the value is the same as for", "self.amber_triggers = [] # check for header (always, because it", "= None def voevent_connector(self): \"\"\" Connect to the VOEvent generator", "CB is valid if cb key is not present pass", "None) :param float dmgal: galactic maximum DM :param astropy.coordinates.SkyCoord pointing:", "break return dm_src, src_type, source def _check_triggers(self, triggers, sys_params, utc_start,", "source_list def process_command(self, command): \"\"\" Process command received from queue", "[] # check for header (always, because it is received", "try: triggers = np.array(list(map(lambda val: val.split(), triggers)), dtype=float) except Exception", "thresholds: S/N > {}, \" \"downsamp <= {}\".format(snr_min_lofar, width_max_lofar)) else:", "pass else: # replace source by alias so we can", "# new source, apply all LOFAR thresholds snr_min_lofar = self.thresh_lofar['snr_min']", "= util.decode_parset(master_config['parset']) parset = util.parse_parset(raw_parset) except Exception as e: self.logger.warning(", "Trigger system\") self.lofar_queue.put(lofar_trigger) if self.have_vo: self.logger.info(\"Sending same trigger to VOEvent", ":param bool connect_vo: Whether or not to connect to VOEvent", "width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster = self.thresh_lofar['max_cands_per_cluster'] # create mask for", "the master parset file master_config_file = os.path.join(obs_config['master_dir'], 'parset', 'darc_master.parset') try:", "<= max_cands_per_cluster) # check for any remaining triggers if np.any(mask):", "ms 'snr': snr, 'flux': flux, # Jy 'ra': pointing.ra.deg, #", "too high (this indicates RFI) mask = (cluster_snr >= snr_min_lofar)", "list: {}\".format(e)) return source_list def process_command(self, command): \"\"\" Process command", "same trigger to VOEvent system\") self.vo_queue.put(lofar_trigger) else: self.logger.error(\"No VOEvent Generator", "# clear config self.obs_config = None # clear threads for", "# first check aliases try: alias = self.source_list['aliases'][source] except KeyError:", "{} self.hdr_mapping = {} self.obs_config = None self.observation_running = False", "to VOEvent Generator, setting dummy queue ({})\".format(e)) self.vo_queue = self.dummy_queue", "Trigger IQUV / LOFAR / VOEvent system based on AMBER", "# Load VO server settings VOEventQueueServer.register('get_queue') with open(self.config_file, 'r') as", "LOFAR Trigger connection available - cannot trigger LOFAR\") # do", "float width_max: maximum width (default: inf) :param float snr_min: mininum", "Load LOFAR trigger server settings LOFARTriggerQueueServer.register('get_queue') with open(self.config_file, 'r') as", "self.connect_lofar: try: self.lofar_queue = self.lofar_connector() self.logger.info(\"Connected to LOFAR Trigger on", "so we can look it up in other lists self.logger.info(\"Using", "dm_delay = 4.148808E3 * dm_to_send * (cent_freq**-2 - max_freq**-2) utc_arr", "the observation parset :param dict obs_config: Observation config :return: parset", "trigger queue and on VOEvent queue \"\"\" def __init__(self, *args,", "# and whether or not a new trigger can be", "super(AMBERClustering, self).__init__(*args, **kwargs) self.connect_vo = connect_vo self.connect_lofar = connect_lofar self.dummy_queue", "category \"\"\" try: with open(self.source_file, 'r') as f: source_list =", "trigger else: # create the full trigger and put on", "CB valid: set thresholds snr_min_lofar = self.thresh_lofar_override['snr_min'] width_max_lofar = self.thresh_lofar_override['width_max']", "= np.array(cluster_dm)[mask] cluster_time = np.array(cluster_time)[mask] cluster_downsamp = np.array(cluster_downsamp)[mask].astype(int) cluster_sb =", "except Exception as e: self.logger.error(\"Failed to connect to VOEvent Generator,", "({})\".format(e)) beam = 0 # read beam coordinates from parset", "if command['command'] == 'trigger': if not self.observation_running: self.logger.error(\"Trigger(s) received but", "# set DM uncertainty to DM delay across pulse width", "args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_new) self.threads['trigger_new_source'].start() sleep(self.interval) self.logger.info(\"Observation finished\") def", "{}\".format(e)) continue # pick columns to feed to clustering algorithm", "port = server_config['server_port'] key = server_config['server_auth'].encode() server = VOEventQueueServer(address=(MASTER, port),", "we can look it up in other lists self.logger.info(\"Using alias", "if dm_src is not None: dm_to_send = dm_src dm_err =", "remove comment symbol header = trigger.split()[1:] self.logger.info(\"Received header: {}\".format(header)) #", "observation is running - ignoring\") else: with self.lock: self.amber_triggers.append(command['trigger']) elif", "self.have_lofar: self.logger.error(\"No LOFAR Trigger connection available - cannot trigger LOFAR\")", "self.connect_vo: try: self.vo_queue = self.voevent_connector() self.logger.info(\"Connected to VOEvent Generator on", "str src_type: Source type (pulsar, frb, None) :param str src_name:", "= False else: # dummy queue self.logger.info(\"LOFAR Trigger connection disabled,", "Trigger on master node\") self.have_lofar = True except Exception as", "= False # process triggers in thread self.threads['processing'] = threading.Thread(target=self._process_triggers)", "to connect to VOEvent queue on master node :param bool", "= width.to(u.ms).value # calculate arrival time at reference frequency =", "mininum S/N (default: 8) :param str src_type: Source type (pulsar,", "enabled # always do this in case a connection was", "None for key in ['pulsars', 'frbs']: try: dm_src = self.source_list[key][source]", "or not pointing information is available if pointing is None:", "known, CB valid: set thresholds snr_min_lofar = self.thresh_lofar_override['snr_min'] width_max_lofar =", "self.logger.error(\"Trigger(s) received but no observation is running - ignoring\") else:", "in triggers: if trigger.startswith('#'): # read header, remove comment symbol", "delay across band dm_err = width.to(u.ms).value # calculate arrival time", "cluster_time = np.array(cluster_time)[mask] cluster_downsamp = np.array(cluster_downsamp)[mask].astype(int) cluster_sb = np.array(cluster_sb)[mask].astype(int) ncand_per_cluster", "os from time import sleep import yaml import ast import", "sys_params = {'dt': dt, 'delta_nu_MHz': chan_width, 'nu_GHz': cent_freq} pointing =", "'src_name': src_name, 'dm_min': max(dm_src - self.dm_range, self.dm_min_global), 'dm_max': dm_src +", "those getting lost with self.lock: triggers = self.amber_triggers self.amber_triggers =", "def _load_parset(self, obs_config): \"\"\" Load the observation parset :param dict", "not None: # known source, use same DM threshold as", "node\") self.have_vo = True except Exception as e: self.logger.error(\"Failed to", "parameter cluster_snr, cluster_dm, cluster_time, cluster_downsamp, cluster_sb, _, ncand_per_cluster = \\", "== 'trigger': if not self.observation_running: self.logger.error(\"Trigger(s) received but no observation", "replace source by alias so we can look it up", "is already in config on master node # decode the", "= self.obs_config['parset']['task.source.name'] except KeyError: self.logger.error(\"Cannot get source name from parset,", "else: # dummy queue self.logger.info(\"LOFAR Trigger connection disabled, setting dummy", "connection disabled, setting dummy queue\") self.vo_queue = mp.Queue() self.have_vo =", "trigger in triggers: if trigger.startswith('#'): # read header, remove comment", "maximum DM :param astropy.coordinates.SkyCoord pointing: Pointing for LOFAR triggering (default:", "the value is the same as for IQUV # but", "now if not self.hdr_mapping: self.logger.error(\"First clusters received but header not", "def lofar_connector(self): \"\"\" Connect to the LOFAR triggering system on", "{}\".format(e)) return source_list def process_command(self, command): \"\"\" Process command received", "np.array(cluster_time)[mask] cluster_downsamp = np.array(cluster_downsamp)[mask].astype(int) cluster_sb = np.array(cluster_sb)[mask].astype(int) ncand_per_cluster = np.array(ncand_per_cluster)[mask].astype(int)", "= np.array(cluster_downsamp)[mask].astype(int) cluster_sb = np.array(cluster_sb)[mask].astype(int) ncand_per_cluster = np.array(ncand_per_cluster)[mask].astype(int) ncluster =", "information is available if pointing is None: self.logger.error(\"No pointing information", "dm_src is not None: dm_to_send = dm_src dm_err = 0.", "self.dummy_queue self.have_lofar = False else: # dummy queue self.logger.info(\"LOFAR Trigger", "({})\".format(e)) self.vo_queue = self.dummy_queue self.have_vo = False # try connecting", "= self.dummy_queue self.have_vo = False else: # dummy queue self.logger.info(\"VO", "dmgal = util.get_ymw16(self.obs_config['parset'], self.obs_config['beam'], self.logger) # get known source dm", "- Canceling processing\") continue # split strings and convert to", "any old triggers self.amber_triggers = [] # parse parset obs_config['parset']", "in source list # first check aliases try: alias =", "np.array(list(map(lambda val: val.split(), triggers)), dtype=float) except Exception as e: self.logger.error(\"Failed", "list # first check aliases try: alias = self.source_list['aliases'][source] except", "self.logger.info(\"Setting {src_name} trigger DM range to {dm_min} - {dm_max}, \"", "False def _load_source_list(self): \"\"\" Load the list with known source", "Exception as e: self.logger.error(\"Could not parse pointing for CB{:02d} ({})\".format(beam,", "the mid point of the observation timestamp = Time(parset['task.startTime']) +", "self.logger.error(\"Could not parse pointing for CB{:02d} ({})\".format(beam, e)) return None", "date and time :param float dm_min: minimum DM (default: 0)", "trigger thresholds: S/N > {}, \" \"downsamp <= {}\".format(snr_min_lofar, width_max_lofar))", "self.hdr_mapping: for trigger in triggers: if trigger.startswith('#'): # read header,", "(self.hdr_mapping['DM'], self.hdr_mapping['SNR'], self.hdr_mapping['time'], self.hdr_mapping['integration_step'], self.hdr_mapping['beam_id'])] # known source and new", "= self.obs_config['datetimesource'] dt = TSAMP.to(u.second).value chan_width = (BANDWIDTH / float(NCHAN)).to(u.MHz).value", "None: dm_to_send = dm_src else: dm_to_send = cluster_dm[i] dada_trigger =", "try: self.vo_queue = self.voevent_connector() self.logger.info(\"Connected to VOEvent Generator on master", "\"\"\" Read thresholds (DM, width, S/N) for clustering Continuously read", "TIME_UNIT, format='unix') datetimesource = self.obs_config['datetimesource'] dt = TSAMP.to(u.second).value chan_width =", "if all required params are present and create mapping to", "f: server_config = yaml.load(f, Loader=yaml.SafeLoader)['lofar_trigger'] port = server_config['server_port'] key =", "the server keeps track of when LOFAR triggers were sent", "= connect_lofar self.dummy_queue = mp.Queue() self.threads = {} self.hdr_mapping =", "in case a connection was available before, but failed at", "trigger.split()[1:] self.logger.info(\"Received header: {}\".format(header)) # Check if all required params", "beam = 0 # read beam coordinates from parset try:", "sb_filter=self.sb_filter, sb_filter_period_min=self.sb_filter_period_min, sb_filter_period_max=self.sb_filter_period_max, **sys_params) # select on width mask =", "return_clustcounts=True, sb_filter=self.sb_filter, sb_filter_period_min=self.sb_filter_period_min, sb_filter_period_max=self.sb_filter_period_max, **sys_params) # select on width mask", "'trigger': if not self.observation_running: self.logger.error(\"Trigger(s) received but no observation is", "clustering Continuously read AMBER triggers from queue and start processing", "as e: self.logger.warning( \"Failed to load parset from master config", "from parset, will not do known-source triggering\") return None, None,", "known pulsar or frb dm_src = None src_type = None", "known source (default: None) :param float width_max: maximum width (default:", "if there are no clusters if ncluster == 0: return", "src_type is not None: thresh_src = {'dm_src': dm_src, 'src_type': src_type,", "self.logger.error(\"No pointing information available - cannot trigger LOFAR\") # check", "for known and/or new sources \"\"\" # set observation parameters", "cluster_time, cluster_downsamp, cluster_sb, _, ncand_per_cluster = \\ tools.get_triggers(triggers, dm_min=dm_min, dm_max=dm_max,", "= False else: # dummy queue self.logger.info(\"VO Generator connection disabled,", "set config self.obs_config = obs_config self.observation_running = True # (re)load", "all required params are present and create mapping to col", "queue \"\"\" def __init__(self, *args, connect_vo=True, connect_lofar=True, **kwargs): \"\"\" :param", "import yaml import ast import threading import multiprocessing as mp", "= 4.148808E3 * dm_to_send * (cent_freq**-2 - max_freq**-2) utc_arr =", "VO queue lofar_trigger = {'dm': dm_to_send, 'dm_err': dm_err, 'width': width.to(u.ms).value,", "because the value is the same as for IQUV #", "= key[:-1] except KeyError: pass else: break return dm_src, src_type,", "or not a new trigger can be sent # check", "queue and on VOEvent queue \"\"\" def __init__(self, *args, connect_vo=True,", "extract obs parset and decode raw_parset = util.decode_parset(master_config['parset']) parset =", "= [] for i in range(ncluster): # send known source", "VOEvent Generator on master node\") self.have_vo = True except Exception", "alias # check if source is a known pulsar or", "should be enabled for new sources if src_type is not", "Exception as e: self.logger.error(\"Failed to connect to VOEvent Generator, setting", "master node \"\"\" # Load VO server settings VOEventQueueServer.register('get_queue') with", "or not to connect to VOEvent queue on master node", "thresh_src = {'dm_src': dm_src, 'src_type': src_type, 'src_name': src_name, 'dm_min': max(dm_src", "LOFAR \" \"triggering={skip_lofar}\".format(**thresh_new)) # main loop while self.observation_running: if self.amber_triggers:", "- not sending VO trigger\") def _process_triggers(self): \"\"\" Read thresholds", "sent # and whether or not a new trigger can", "are assumed to be more strict for every parameter cluster_snr,", "known source triggering if src_type is not None: self.threads['trigger_known_source'] =", "and type dm_src, src_type, src_name = self._get_source() if src_type is", "if we are connected to the server elif not self.have_lofar:", "triggers on remote LOFAR trigger queue and on VOEvent queue", "are connected to the server elif not self.have_lofar: self.logger.error(\"No LOFAR", "} # if known source, check whether or not LOFAR", "the observation timestamp = Time(parset['task.startTime']) + .5 * float(parset['task.duration']) *", "multiprocessing as mp import numpy as np from astropy.time import", "do known-source triggering\") return None, None, None # check if", "because it is received once for every amber instance) if", "connection available - cannot trigger LOFAR\") # do the trigger", "float dm_max: maximum DM (default: inf) :param float dm_src: DM", "is a known pulsar or frb dm_src = None src_type", "inf) :param float dm_src: DM of known source (default: None)", "{'dt': dt, 'delta_nu_MHz': chan_width, 'nu_GHz': cent_freq} pointing = self._get_pointing() dmgal", "thresholds (DM, width, S/N) for clustering Continuously read AMBER triggers", "& (cluster_dm >= dm_min_lofar) & \\ (cluster_downsamp <= width_max_lofar) &", "the LOFAR triggering system on the master node \"\"\" #", "cluster_downsamp, cluster_sb, _, ncand_per_cluster = \\ tools.get_triggers(triggers, dm_min=dm_min, dm_max=dm_max, sig_thresh=snr_min,", "yaml.load(f, Loader=yaml.SafeLoader)['lofar_trigger'] port = server_config['server_port'] key = server_config['server_auth'].encode() server =", "clusters header: {}\".format(key)) self.hdr_mapping = {} return # header should", "DM (default: inf) :param float dm_src: DM of known source", "trigger(s)\".format(ncluster)) # note: the server keeps track of when LOFAR", "# process triggers in thread self.threads['processing'] = threading.Thread(target=self._process_triggers) self.threads['processing'].start() self.logger.info(\"Observation", "self.thresh_lofar['width_max'] max_cands_per_cluster = self.thresh_lofar['max_cands_per_cluster'] # create mask for given thresholds", "for trigger in triggers if not trigger.startswith('#')] # triggers is", "RFI) mask = (cluster_snr >= snr_min_lofar) & (cluster_dm >= dm_min_lofar)", "({})\".format(beam, e)) return None # convert HA to RA if", "import numpy as np from astropy.time import Time, TimeDelta import", "disabled, setting dummy queue\") self.vo_queue = mp.Queue() self.have_vo = False", "dm_src, src_type, src_name = self._get_source() if src_type is not None:", "\"\"\" try: # encoded parset is already in config on", "try: alias = self.source_list['aliases'][source] except KeyError: # not found pass", "'src_name': None, 'dm_min': max(dmgal * self.thresh_iquv['dm_frac_min'], self.dm_min_global), 'dm_max': np.inf, 'width_max':", "= util.parse_parset(raw_parset) except KeyError: self.logger.info(\"Observation parset not found in input", "node\") self.have_lofar = True except Exception as e: self.logger.error(\"Failed to", "AMBERClusteringException(\"Cannot load source list: {}\".format(e)) return source_list def process_command(self, command):", "look it up in other lists self.logger.info(\"Using alias {} for", "so just run it always ind = np.argmax(cluster_snr[mask]) # estimate", "# not found pass else: # replace source by alias", "where number of raw candidates is too high (this indicates", "max_freq**-2) utc_arr = (utc_start + TimeDelta(cluster_time[mask][ind] - dm_delay, format='sec')).isot #", "key in keys: try: self.hdr_mapping[key] = header.index(key) except ValueError: self.logger.error(\"Key", "there are multiple triggers if ncluster > 1: self.logger.info(\"Multiple triggers", "available - cannot trigger LOFAR\") # do the trigger else:", "c2 = c2 * u.deg except Exception as e: self.logger.error(\"Could", "if src_type is not None and src_name in self.lofar_trigger_sources: thresh_new['skip_lofar']", "TSAMP, NCHAN, BANDWIDTH, MASTER, TIME_UNIT from darc.external import tools from", "self._load_parset(obs_config) # set config self.obs_config = obs_config self.observation_running = True", "argmax also works if there is one trigger, so just", "src_type = key[:-1] except KeyError: pass else: break return dm_src,", "frb, None) :param str src_name: Source name (default: None) :param", "convert HA to RA if HADEC is used if parset['task.directionReferenceFrame'].upper()", "in range(ncluster): # send known source dm if available if", "{} self.obs_config = None self.observation_running = False self.amber_triggers = []", "self.logger.error(\"Cannot read beam from parset, setting CB to 0 ({})\".format(e))", "list with known source DMs :return: source list with dict", "in format readable by astropy.time.Time :param str datetimesource: Field name", "= self.thresh_lofar['max_cands_per_cluster'] # create mask for given thresholds # also", "source list with dict per category \"\"\" try: with open(self.source_file,", "dm_src: DM of known source (default: None) :param float width_max:", "self.source_list = None self.lock = mp.Lock() # store when we", "yaml.load(f, Loader=yaml.SafeLoader) except OSError as e: raise AMBERClusteringException(\"Cannot load source", "ncand_per_cluster = np.array(ncand_per_cluster)[mask].astype(int) ncluster = len(cluster_snr) if src_type is not", "4.148808E3 * dm_to_send * (cent_freq**-2 - max_freq**-2) utc_arr = (utc_start", "process \"\"\" if command['command'] == 'trigger': if not self.observation_running: self.logger.error(\"Trigger(s)", "queue on master node \"\"\" super(AMBERClustering, self).__init__(*args, **kwargs) self.connect_vo =", "if self.amber_triggers: # Copy the triggers so class-wide list can", "= None self.lock = mp.Lock() # store when we are", "dummy queue\") self.vo_queue = mp.Queue() self.have_vo = False # connect", "Trigger connection disabled, setting dummy queue\") self.lofar_queue = mp.Queue() self.have_lofar", "= cluster_snr[mask][ind] width = TSAMP.to(u.ms) * cluster_downsamp[mask][ind] # astropy units", "needs to be defined for the mask = line below", "across band dm_err = width.to(u.ms).value # calculate arrival time at", "in config on master node # decode the parset raw_parset", "and new sources, and for IQUV vs LOFAR) 3. Put", "snr, 'flux': flux, # Jy 'ra': pointing.ra.deg, # decimal deg", "be defined for the mask = line below to work", "\" \"downsamp <= {}\".format(snr_min_lofar, width_max_lofar)) else: # new source, apply", "every amber instance) if not self.hdr_mapping: for trigger in triggers:", "chan_width, 'nu_GHz': cent_freq} pointing = self._get_pointing() dmgal = util.get_ymw16(self.obs_config['parset'], self.obs_config['beam'],", "on master node :param bool connect_lofar: Whether or not to", "LOFAR Trigger system\") self.lofar_queue.put(lofar_trigger) if self.have_vo: self.logger.info(\"Sending same trigger to", "parset not found in input config, looking for master parset\")", "'flux': flux, # Jy 'ra': pointing.ra.deg, # decimal deg 'dec':", "try: key = \"task.beamSet.0.compoundBeam.{}.phaseCenter\".format(beam) c1, c2 = ast.literal_eval(parset[key].replace('deg', '')) c1", "but it needs to be defined for the mask =", "'dm': dm_to_send, 'beam': cluster_sb[i], 'width': cluster_downsamp[i], 'snr': cluster_snr[i], 'time': cluster_time[i],", "np.inf, 'snr_min': self.snr_min_global, 'pointing': pointing, 'dmgal': dmgal } self.logger.info(\"Setting {src_name}", "from master config file {}, \" \"setting parset to None:", "# known source triggering if src_type is not None: self.threads['trigger_known_source']", "width_max cluster_snr = np.array(cluster_snr)[mask] cluster_dm = np.array(cluster_dm)[mask] cluster_time = np.array(cluster_time)[mask]", "set DM uncertainty to DM delay across pulse width #", "*args, **kwargs): \"\"\" Stop observation \"\"\" # set running to", "and create mapping to col index keys = ['beam_id', 'integration_step',", "is not None: self.threads['trigger_known_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params, utc_start, datetimesource),", "check if source is in source list # first check", "\"\"\" # cluster using IQUV thresholds # LOFAR thresholds are", "dada_triggers}) # skip LOFAR triggering for pulsars or if explicitly", "self.lock: triggers = self.amber_triggers self.amber_triggers = [] # check for", "the parset raw_parset = util.decode_parset(obs_config['parset']) # convert to dict and", "sources, and for IQUV vs LOFAR) 3. Put IQUV triggers", "= alias # check if source is a known pulsar", "galactic maximum DM :param astropy.coordinates.SkyCoord pointing: Pointing for LOFAR triggering", "self.hdr_mapping['integration_step'], self.hdr_mapping['beam_id'])] # known source and new source triggering, in", "= not self.thresh_lofar['trigger_on_new_sources'] else: thresh_new['skip_lofar'] = False self.logger.info(\"Setting new source", "to VOEvent system\") self.vo_queue.put(lofar_trigger) else: self.logger.error(\"No VOEvent Generator connection available", "to load parset from master config file {}, \" \"setting", "self.dummy_queue self.have_vo = False else: # dummy queue self.logger.info(\"VO Generator", "'beam': cluster_sb[i], 'width': cluster_downsamp[i], 'snr': cluster_snr[i], 'time': cluster_time[i], 'utc_start': utc_start}", "import sleep import yaml import ast import threading import multiprocessing", "# create the full trigger and put on VO queue", "not triggers: self.logger.info(\"Only header received - Canceling processing\") continue #", "* self.thresh_lofar['dm_frac_min'], self.dm_min_global) width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster = self.thresh_lofar['max_cands_per_cluster'] #", "= SkyCoord(c1, c2) return pointing def _load_parset(self, obs_config): \"\"\" Load", "not do known-source triggering\") return None, None, None # check", "mask = (cluster_snr >= snr_min_lofar) & (cluster_dm >= dm_min_lofar) &", "= VOEventQueueServer(address=(MASTER, port), authkey=key) server.connect() return server.get_queue() def lofar_connector(self): \"\"\"", "= {} self.obs_config = None self.observation_running = False self.amber_triggers =", "Raw triggers :param dict sys_params: System parameters (dt, delta_nu_MHz, nu_GHz)", "u from astropy.coordinates import SkyCoord from darc import DARCBase, VOEventQueueServer,", "# read parset try: parset = self.obs_config['parset'] except KeyError as", "range(ncluster): # send known source dm if available if dm_src", "some point if self.connect_vo: try: self.vo_queue = self.voevent_connector() self.logger.info(\"Connected to", "TSAMP.to(u.ms) * cluster_downsamp[mask][ind] # astropy units only knows mJy, but", "cent_freq = (self.obs_config['min_freq'] * u.MHz + 0.5 * BANDWIDTH).to(u.GHz).value sys_params", "= False def _load_source_list(self): \"\"\" Load the list with known", "\"\"\" Process command received from queue :param dict command: Command", "snr_min=8, src_type=None, src_name=None, dmgal=0, pointing=None, skip_lofar=False): \"\"\" Cluster triggers and", "finished\") def _get_pointing(self): \"\"\" Get pointing of this CB from", "triggers on output queue 4. Put LOFAR triggers on remote", "if self.connect_lofar: try: self.lofar_queue = self.lofar_connector() self.logger.info(\"Connected to LOFAR Trigger", "source known, CB valid: set thresholds snr_min_lofar = self.thresh_lofar_override['snr_min'] width_max_lofar", "= None # clear threads for key, thread in self.threads.items():", "(DM, width, S/N) for clustering Continuously read AMBER triggers from", "Load the parset from the master parset file master_config_file =", "pointing information is available if pointing is None: self.logger.error(\"No pointing", "pointing of this CB from parset :return: pointing SkyCoord \"\"\"", ":param dict obs_config: Observation configuration :param bool reload: reload service", "= cent_freq + .5 * BANDWIDTH.to(u.MHz).value dm_delay = 4.148808E3 *", "\"\"\" :param bool connect_vo: Whether or not to connect to", "dada_triggers = [] for i in range(ncluster): # send known", "main loop while self.observation_running: if self.amber_triggers: # Copy the triggers", "= [] # check for header (always, because it is", "src_type, src_name = self._get_source() if src_type is not None: thresh_src", "used if parset['task.directionReferenceFrame'].upper() == 'HADEC': # Get RA at the", "possible LOFAR trigger(s)\".format(ncluster)) # note: the server keeps track of", "is received once for every amber instance) if not self.hdr_mapping:", "when we are allowed to do IQUV / LOFAR triggering", "None # clear threads for key, thread in self.threads.items(): if", "obs_config: Observation config :return: parset as dict \"\"\" try: #", "format readable by astropy.time.Time :param str datetimesource: Field name with", "other lists self.logger.info(\"Using alias {} for source {}\".format(alias, source)) source", "not None: thread.join() self.threads[key] = None def voevent_connector(self): \"\"\" Connect", "e: self.logger.error(\"Could not parse pointing for CB{:02d} ({})\".format(beam, e)) return", "process triggers in thread self.threads['processing'] = threading.Thread(target=self._process_triggers) self.threads['processing'].start() self.logger.info(\"Observation started\")", "node # decode the parset raw_parset = util.decode_parset(obs_config['parset']) # convert", "start_observation(self, obs_config, reload=True): \"\"\" Parse obs config and start listening", "delta_nu_MHz, nu_GHz) :param str utc_start: start time of observation, in", "source)) source = alias # check if source is a", "# return if there are no clusters if ncluster ==", "name (default: None) :param float dmgal: galactic maximum DM :param", "\"\"\" # set running to false self.observation_running = False #", "more strict for every parameter cluster_snr, cluster_dm, cluster_time, cluster_downsamp, cluster_sb,", "None) :param float width_max: maximum width (default: inf) :param float", "== 'get_attr': self.get_attribute(command) else: self.logger.error(\"Unknown command received: {}\".format(command['command'])) def start_observation(self,", "received but no observation is running - ignoring\") else: with", "# decimal deg 'cb': self.obs_config['beam'], 'sb': cluster_sb[mask][ind], 'ymw16': dmgal, 'semiMaj':", "it up in other lists self.logger.info(\"Using alias {} for source", "try: # Read raw config with open(master_config_file) as f: master_config", "once for every amber instance) if not self.hdr_mapping: for trigger", "dm_max: maximum DM (default: inf) :param float dm_src: DM of", "triggers where number of raw candidates is too high (this", "(MHz)) lofar_trigger.update(sys_params) self.logger.info(\"Sending LOFAR trigger to LOFAR Trigger system\") self.lofar_queue.put(lofar_trigger)", "= self.thresh_lofar_override['width_max'] self.logger.warning(\"Setting LOFAR trigger thresholds: S/N > {}, \"", ":param float dmgal: galactic maximum DM :param astropy.coordinates.SkyCoord pointing: Pointing", "width (default: inf) :param float snr_min: mininum S/N (default: 8)", "new sources, and for IQUV vs LOFAR) 3. Put IQUV", "1000. max_freq = cent_freq + .5 * BANDWIDTH.to(u.MHz).value dm_delay =", "if src_type is not None: self.threads['trigger_known_source'] = threading.Thread(target=self._check_triggers, args=(triggers_for_clustering, sys_params,", "raw candidates is too high (this indicates RFI) mask =", "header not found\") continue # remove headers from triggers (i.e.", "({})\".format(e)) self.vo_queue = self.dummy_queue self.have_vo = False else: # dummy", "= yaml.load(f, Loader=yaml.SafeLoader)['voevent_generator'] port = server_config['server_port'] key = server_config['server_auth'].encode() server", "val.split(), triggers)), dtype=float) except Exception as e: self.logger.error(\"Failed to process", "name, 'src_name': src_name, 'datetimesource': datetimesource, 'utc': utc_arr, 'tarr': cluster_time[mask][ind], 'importance':", "astropy.coordinates import SkyCoord from darc import DARCBase, VOEventQueueServer, LOFARTriggerQueueServer from", "(always, because it is received once for every amber instance)", "np from astropy.time import Time, TimeDelta import astropy.units as u", "known source DMs :return: source list with dict per category", "in allowed_cbs: return except KeyError: # any CB is valid", "parset :return: pointing SkyCoord \"\"\" # read parset try: parset", "queue :param dict command: Command to process \"\"\" if command['command']", "cent_freq = sys_params['nu_GHz'] * 1000. max_freq = cent_freq + .5", "pointing information available - cannot trigger LOFAR\") # check if", "{'dm_src': dm_src, 'src_type': src_type, 'src_name': src_name, 'dm_min': max(dm_src - self.dm_range,", "thresholds snr_min_lofar = self.thresh_lofar['snr_min'] dm_min_lofar = max(dmgal * self.thresh_lofar['dm_frac_min'], self.dm_min_global)", "as e: raise AMBERClusteringException(\"Cannot load source list: {}\".format(e)) return source_list", "width # Apertif has roughly 1 DM unit = 1", "mp.Queue() self.have_lofar = False def _load_source_list(self): \"\"\" Load the list", "self.logger.info(\"LOFAR Trigger connection disabled, setting dummy queue\") self.lofar_queue = mp.Queue()", "generator on the master node \"\"\" # Load VO server", "is not None: dm_to_send = dm_src else: dm_to_send = cluster_dm[i]", "cluster using IQUV thresholds # LOFAR thresholds are assumed to", "header.index(key) except ValueError: self.logger.error(\"Key missing from clusters header: {}\".format(key)) self.hdr_mapping", "= cluster_dm[mask][ind] # set DM uncertainty to DM delay across", "(pulsar, frb, None) :param str src_name: Source name (default: None)", "numpy as np from astropy.time import Time, TimeDelta import astropy.units", "'DM', 'SNR'] for key in keys: try: self.hdr_mapping[key] = header.index(key)", "'pulsar' or skip_lofar: return # select LOFAR thresholds if src_type", "queue 4. Put LOFAR triggers on remote LOFAR trigger queue", "except OSError as e: raise AMBERClusteringException(\"Cannot load source list: {}\".format(e))", "= self.source_list[key][source] src_type = key[:-1] except KeyError: pass else: break", "to do IQUV / LOFAR triggering self.time_iquv = Time.now() #", "System parameters (dt, delta_nu_MHz, nu_GHz) :param str utc_start: start time", "= max(dmgal * self.thresh_lofar['dm_frac_min'], self.dm_min_global) width_max_lofar = self.thresh_lofar['width_max'] max_cands_per_cluster =", "if cb key is not present pass else: # source", "at some point if self.connect_lofar: try: self.lofar_queue = self.lofar_connector() self.logger.info(\"Connected", "units only knows mJy, but the VOEvent Generator expects Jy", "try: parset = self.obs_config['parset'] except KeyError as e: self.logger.error(\"Cannot read", "does not # delay next run # known source triggering", "clear header self.hdr_mapping = {} # clear config self.obs_config =", "on output queue 4. Put LOFAR triggers on remote LOFAR", "available if dm_src is not None: dm_to_send = dm_src else:", "= self.obs_config['parset'] except KeyError as e: self.logger.error(\"Cannot read parset ({})\".format(e))", "VOEvent queue \"\"\" def __init__(self, *args, connect_vo=True, connect_lofar=True, **kwargs): \"\"\"", "time :param float dm_min: minimum DM (default: 0) :param float", "self.lofar_trigger_sources: # check CB number try: allowed_cbs = self.thresh_lofar_override['cb'] if", "'time', 'DM', 'SNR'] for key in keys: try: self.hdr_mapping[key] =", "self.logger.error(\"Unknown command received: {}\".format(command['command'])) def start_observation(self, obs_config, reload=True): \"\"\" Parse", "config on master node # decode the parset raw_parset =", "utc_arr = (utc_start + TimeDelta(cluster_time[mask][ind] - dm_delay, format='sec')).isot # set", "self.have_vo = False else: # dummy queue self.logger.info(\"VO Generator connection", "src_name, 'datetimesource': datetimesource, 'utc': utc_arr, 'tarr': cluster_time[mask][ind], 'importance': 0.1} #", "triggering for pulsars or if explicitly disabled if src_type ==", "to process triggers: {}\".format(e)) continue # pick columns to feed", "read beam from parset, setting CB to 0 ({})\".format(e)) beam", "# convert to dict and store parset = util.parse_parset(raw_parset) except", "> {}, \" \"downsamp <= {}\".format(snr_min_lofar, width_max_lofar)) else: # new", "return # select LOFAR thresholds if src_type is not None:", "\"\"\" Get pointing of this CB from parset :return: pointing", "args=(triggers_for_clustering, sys_params, utc_start, datetimesource), kwargs=thresh_src) self.threads['trigger_known_source'].start() # new source triggering", "False # connect to LOFAR trigger if self.connect_lofar: try: self.lofar_queue", "key = \"task.beamSet.0.compoundBeam.{}.phaseCenter\".format(beam) c1, c2 = ast.literal_eval(parset[key].replace('deg', '')) c1 =", "dict command: Command to process \"\"\" if command['command'] == 'trigger':", "apply width and S/N thresholds # DM_min effectively does nothing" ]
[ "[super_admin_user, group_admin_user, full_user, view_only_user]: DBSession().add( TornadoStorage.user.create_social_auth(u, u.username, \"google-oauth2\") ) with", "skyportal.tests import api from baselayer.tools.test_frontend import verify_server_availability if __name__ ==", "source_info[\"id\"], \"time_format\": \"iso\", \"time_scale\": \"utc\", \"instrument_id\": instrument1_id, \"observed_at\": phot_data.observed_at.tolist(), \"mag\":", "eagle has landed\"], }, ] (basedir / \"static/thumbnails\").mkdir(parents=True, exist_ok=True) for", "source_info[\"id\"], \"observed_at\": str(datetime.datetime(2014, 10, 24)), \"instrument_id\": 1, \"wavelengths\": df.wavelength.tolist(), \"fluxes\":", "= f\"http://localhost:{cfg['ports.app']}\" print() print(f\"Waiting for server to appear at {server_url}...\")", "= assert_post( \"groups\", data={ \"name\": \"Stream A\", \"group_admins\": [ super_admin_user.username,", ") server_url = f\"http://localhost:{cfg['ports.app']}\" print() print(f\"Waiting for server to appear", "data[\"data\"][\"id\"] for u in [view_only_user, full_user]: data = assert_post( f\"groups/{group_id}/users/{u.username}\",", "Optical Telescope\", \"nickname\": \"NOT\", \"lat\": 28.75, \"lon\": 17.88, \"elevation\": 1870,", "\"spectrum\", data={ \"source_id\": source_info[\"id\"], \"observed_at\": str(datetime.datetime(2014, 10, 24)), \"instrument_id\": 1,", "dummy instruments\"): data = assert_post( \"telescope\", data={ \"name\": \"Palomar 1.5m\",", "assert_post( \"instrument\", data={ \"name\": \"ALFOSC\", \"type\": \"both\", \"band\": \"optical\", \"telescope_id\":", "data[\"data\"][\"id\"] data = assert_post( \"instrument\", data={ \"name\": \"P60 Camera\", \"type\":", "import base64 from pathlib import Path import shutil import pandas", "df.wavelength.tolist(), \"fluxes\": df.flux.tolist(), }, ) for ttype in [\"new\", \"ref\",", "= source_info.pop(\"comments\") data = assert_post(\"sources\", data=source_info) assert data[\"data\"][\"id\"] == source_info[\"id\"]", "ttype, }, ) source = Source.query.get(source_info[\"id\"]) source.add_linked_thumbnails() finally: if not", "ttype in [\"new\", \"ref\", \"sub\"]: fname = f'{source_info[\"id\"]}_{ttype}.png' fpath =", "call to {endpoint} failed with status {status}: {data[\"message\"]}' ) return", "[group_id], \"comments\": [\"Frogs in the pond\", \"The eagle has landed\"],", ") return data with status(\"Launching web app & executing API", "not response_status == 200 and data[\"status\"] == \"success\": raise RuntimeError(", "= assert_post( \"telescope\", data={ \"name\": \"Palomar 1.5m\", \"nickname\": \"P60\", \"lat\":", "from skyportal.model_util import setup_permissions, create_token from skyportal.tests import api from", "instrument1_id, \"observed_at\": phot_data.observed_at.tolist(), \"mag\": phot_data.mag.tolist(), \"e_mag\": phot_data.e_mag.tolist(), \"lim_mag\": phot_data.lim_mag.tolist(), \"filter\":", "token\"): token = create_token( [ \"Manage groups\", \"Manage sources\", \"Upload", "instrument1_id = data[\"data\"][\"id\"] data = assert_post( \"telescope\", data={ \"name\": \"Nordic", "{ \"id\": \"14gqr\", \"ra\": 353.36647, \"dec\": 33.646149, \"redshift\": 0.063, \"group_ids\":", "df.flux.tolist(), }, ) for ttype in [\"new\", \"ref\", \"sub\"]: fname", "cfg = load_env() basedir = Path(os.path.dirname(__file__)) / \"..\" with status(f\"Connecting", "assert_post(endpoint, data): response_status, data = api(\"POST\", endpoint, data, token) if", "2.56, \"group_ids\": [group_id], }, ) telescope2_id = data[\"data\"][\"id\"] data =", "assert_post( \"groups\", data={ \"name\": \"Stream A\", \"group_admins\": [ super_admin_user.username, group_admin_user.username,", "and data[\"status\"] == \"success\": raise RuntimeError( f'API call to {endpoint}", "verify_server_availability(server_url) print(\"App running - continuing with API calls\") with status(\"Creating", "print() print(f\"Waiting for server to appear at {server_url}...\") try: verify_server_availability(server_url)", "status(f\"Connecting to database {cfg['database']['database']}\"): init_db(**cfg[\"database\"]) with status(\"Dropping all tables\"): drop_tables()", "\"nickname\": \"NOT\", \"lat\": 28.75, \"lon\": 17.88, \"elevation\": 1870, \"diameter\": 2.56,", "}, ) spec_file = os.path.join( os.path.dirname(os.path.dirname(__file__)), \"skyportal\", \"tests\", \"data\", \"spec.csv\",", "\"telescope_id\": telescope2_id, }, ) with status(\"Creating dummy sources\"): SOURCES =", "raise RuntimeError( f'API call to {endpoint} failed with status {status}:", "\"spec.csv\", ) spec_data = pd.read_csv(spec_file) for i, df in spec_data.groupby(\"instrument_id\"):", "drop_tables from social_tornado.models import TornadoStorage from skyportal.models import init_db, Base,", "full_user, view_only_user] ) for u in [super_admin_user, group_admin_user, full_user, view_only_user]:", "endpoint, data, token) if not response_status == 200 and data[\"status\"]", "adding users\"): data = assert_post( \"groups\", data={ \"name\": \"Stream A\",", "data={\"admin\": False} ) with status(\"Creating dummy instruments\"): data = assert_post(", "data={ \"name\": \"Nordic Optical Telescope\", \"nickname\": \"NOT\", \"lat\": 28.75, \"lon\":", "[ \"No source at transient location to R>26 in LRIS", "phot_data.e_mag.tolist(), \"lim_mag\": phot_data.lim_mag.tolist(), \"filter\": phot_data[\"filter\"].tolist(), }, ) spec_file = os.path.join(", "\"nickname\": \"P60\", \"lat\": 33.3633675, \"lon\": -116.8361345, \"elevation\": 1870, \"diameter\": 1.5,", "{status}: {data[\"message\"]}' ) return data with status(\"Launching web app &", "import requests from baselayer.app.env import load_env from baselayer.app.model_util import status,", "/ \"static/thumbnails\").mkdir(parents=True, exist_ok=True) for source_info in SOURCES: comments = source_info.pop(\"comments\")", ") spec_data = pd.read_csv(spec_file) for i, df in spec_data.groupby(\"instrument_id\"): data", "location to R>26 in LRIS imaging\", \"Strong calcium lines have", "f'{source_info[\"id\"]}_{ttype}.png' fpath = basedir / f\"skyportal/tests/data/{fname}\" thumbnail_data = base64.b64encode( open(os.path.abspath(fpath),", "with status(\"Creating tables\"): create_tables() for model in Base.metadata.tables: print(\" -\",", "source = Source.query.get(source_info[\"id\"]) source.add_linked_thumbnails() finally: if not app_already_running: print(\"Terminating web", "TornadoStorage from skyportal.models import init_db, Base, DBSession, Source, User from", "data = assert_post( f\"groups/{group_id}/users/{u.username}\", data={\"admin\": False} ) with status(\"Creating dummy", "\"group_admins\": [ super_admin_user.username, group_admin_user.username, ], }, ) group_id = data[\"data\"][\"id\"]", "calcium lines have emerged.\", ], }, { \"id\": \"16fil\", \"ra\":", "}, ) group_id = data[\"data\"][\"id\"] for u in [view_only_user, full_user]:", "source_info[\"id\"], \"data\": thumbnail_data, \"ttype\": ttype, }, ) source = Source.query.get(source_info[\"id\"])", "assert_post( \"comment\", data={\"source_id\": source_info[\"id\"], \"text\": comment}, ) phot_file = basedir", "u.username, \"google-oauth2\") ) with status(\"Creating token\"): token = create_token( [", "base64 from pathlib import Path import shutil import pandas as", "source_info.pop(\"comments\") data = assert_post(\"sources\", data=source_info) assert data[\"data\"][\"id\"] == source_info[\"id\"] for", "pd.read_csv(phot_file) data = assert_post( \"photometry\", data={ \"source_id\": source_info[\"id\"], \"time_format\": \"iso\",", "dummy users\"): super_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) group_admin_user", "data = assert_post(\"sources\", data=source_info) assert data[\"data\"][\"id\"] == source_info[\"id\"] for comment", "social_tornado.models import TornadoStorage from skyportal.models import init_db, Base, DBSession, Source,", "\"telescope\", data={ \"name\": \"Nordic Optical Telescope\", \"nickname\": \"NOT\", \"lat\": 28.75,", "\"text\": comment}, ) phot_file = basedir / \"skyportal/tests/data/phot.csv\" phot_data =", "users\", ], super_admin_user.id, \"load_demo_data token\", ) def assert_post(endpoint, data): response_status,", "super_admin_user.username, group_admin_user.username, ], }, ) group_id = data[\"data\"][\"id\"] for u", "\"telescope_id\": telescope1_id, }, ) instrument1_id = data[\"data\"][\"id\"] data = assert_post(", "data={ \"source_id\": source_info[\"id\"], \"data\": thumbnail_data, \"ttype\": ttype, }, ) source", "import Path import shutil import pandas as pd import signal", "10, 24)), \"instrument_id\": 1, \"wavelengths\": df.wavelength.tolist(), \"fluxes\": df.flux.tolist(), }, )", "signal import requests from baselayer.app.env import load_env from baselayer.app.model_util import", "data={\"source_id\": source_info[\"id\"], \"text\": comment}, ) phot_file = basedir / \"skyportal/tests/data/phot.csv\"", "\"iso\", \"time_scale\": \"utc\", \"instrument_id\": instrument1_id, \"observed_at\": phot_data.observed_at.tolist(), \"mag\": phot_data.mag.tolist(), \"e_mag\":", "app_already_running = True except requests.ConnectionError: app_already_running = False web_client =", "\"telescope\", data={ \"name\": \"Palomar 1.5m\", \"nickname\": \"P60\", \"lat\": 33.3633675, \"lon\":", "group_admin_user, full_user, view_only_user] ) for u in [super_admin_user, group_admin_user, full_user,", "\"run\"], cwd=basedir, preexec_fn=os.setsid ) server_url = f\"http://localhost:{cfg['ports.app']}\" print() print(f\"Waiting for", "LRIS imaging\", \"Strong calcium lines have emerged.\", ], }, {", "= assert_post( f\"groups/{group_id}/users/{u.username}\", data={\"admin\": False} ) with status(\"Creating dummy instruments\"):", "api(\"POST\", endpoint, data, token) if not response_status == 200 and", "\"diameter\": 1.5, \"group_ids\": [group_id], }, ) telescope1_id = data[\"data\"][\"id\"] data", "\"group_ids\": [group_id], \"comments\": [\"Frogs in the pond\", \"The eagle has", "datetime import os import subprocess import base64 from pathlib import", "[view_only_user, full_user]: data = assert_post( f\"groups/{group_id}/users/{u.username}\", data={\"admin\": False} ) with", "API calls\") with status(\"Creating dummy group & adding users\"): data", "\"name\": \"ALFOSC\", \"type\": \"both\", \"band\": \"optical\", \"telescope_id\": telescope2_id, }, )", "0.063, \"group_ids\": [group_id], \"comments\": [ \"No source at transient location", "False} ) with status(\"Creating dummy instruments\"): data = assert_post( \"telescope\",", "data={ \"name\": \"Stream A\", \"group_admins\": [ super_admin_user.username, group_admin_user.username, ], },", "dummy sources\"): SOURCES = [ { \"id\": \"14gqr\", \"ra\": 353.36647,", "i, df in spec_data.groupby(\"instrument_id\"): data = assert_post( \"spectrum\", data={ \"source_id\":", "\"redshift\": 0.0, \"group_ids\": [group_id], \"comments\": [\"Frogs in the pond\", \"The", "\"observed_at\": phot_data.observed_at.tolist(), \"mag\": phot_data.mag.tolist(), \"e_mag\": phot_data.e_mag.tolist(), \"lim_mag\": phot_data.lim_mag.tolist(), \"filter\": phot_data[\"filter\"].tolist(),", "try: response_status, data = api(\"GET\", \"sysinfo\", token=token) app_already_running = True", "from baselayer.tools.test_frontend import verify_server_availability if __name__ == \"__main__\": \"\"\"Insert test", "-116.8361345, \"elevation\": 1870, \"diameter\": 1.5, \"group_ids\": [group_id], }, ) telescope1_id", "from social_tornado.models import TornadoStorage from skyportal.models import init_db, Base, DBSession,", "token=token) app_already_running = True except requests.ConnectionError: app_already_running = False web_client", "import os import subprocess import base64 from pathlib import Path", "def assert_post(endpoint, data): response_status, data = api(\"POST\", endpoint, data, token)", "Base, DBSession, Source, User from skyportal.model_util import setup_permissions, create_token from", "= User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) group_admin_user = User( username=\"<EMAIL>\",", "DBSession, Source, User from skyportal.model_util import setup_permissions, create_token from skyportal.tests", "= True except requests.ConnectionError: app_already_running = False web_client = subprocess.Popen(", "super_admin_user.id, \"load_demo_data token\", ) def assert_post(endpoint, data): response_status, data =", "with status(\"Launching web app & executing API calls\"): try: response_status,", "calls\"): try: response_status, data = api(\"GET\", \"sysinfo\", token=token) app_already_running =", "\"id\": \"16fil\", \"ra\": 322.718872, \"dec\": 27.574113, \"redshift\": 0.0, \"group_ids\": [group_id],", "skyportal.models import init_db, Base, DBSession, Source, User from skyportal.model_util import", "\"data\": thumbnail_data, \"ttype\": ttype, }, ) source = Source.query.get(source_info[\"id\"]) source.add_linked_thumbnails()", "== \"success\": raise RuntimeError( f'API call to {endpoint} failed with", "base64.b64encode( open(os.path.abspath(fpath), \"rb\").read() ) data = assert_post( \"thumbnail\", data={ \"source_id\":", "data={ \"name\": \"Palomar 1.5m\", \"nickname\": \"P60\", \"lat\": 33.3633675, \"lon\": -116.8361345,", "= User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) full_user = User(username=\"<EMAIL>\", role_ids=[\"Full", "at {server_url}...\") try: verify_server_availability(server_url) print(\"App running - continuing with API", "[group_id], }, ) telescope2_id = data[\"data\"][\"id\"] data = assert_post( \"instrument\",", "source_info[\"id\"] for comment in comments: data = assert_post( \"comment\", data={\"source_id\":", "dummy group & adding users\"): data = assert_post( \"groups\", data={", "\"Strong calcium lines have emerged.\", ], }, { \"id\": \"16fil\",", ") phot_file = basedir / \"skyportal/tests/data/phot.csv\" phot_data = pd.read_csv(phot_file) data", "TornadoStorage.user.create_social_auth(u, u.username, \"google-oauth2\") ) with status(\"Creating token\"): token = create_token(", "import load_env from baselayer.app.model_util import status, create_tables, drop_tables from social_tornado.models", "cwd=basedir, preexec_fn=os.setsid ) server_url = f\"http://localhost:{cfg['ports.app']}\" print() print(f\"Waiting for server", "to database {cfg['database']['database']}\"): init_db(**cfg[\"database\"]) with status(\"Dropping all tables\"): drop_tables() with", "with API calls\") with status(\"Creating dummy group & adding users\"):", "= data[\"data\"][\"id\"] data = assert_post( \"instrument\", data={ \"name\": \"P60 Camera\",", "\"elevation\": 1870, \"diameter\": 2.56, \"group_ids\": [group_id], }, ) telescope2_id =", "\"__main__\": \"\"\"Insert test data\"\"\" env, cfg = load_env() basedir =", "}, ) source = Source.query.get(source_info[\"id\"]) source.add_linked_thumbnails() finally: if not app_already_running:", "data\", \"Comment\", \"Manage users\", ], super_admin_user.id, \"load_demo_data token\", ) def", "\"name\": \"Palomar 1.5m\", \"nickname\": \"P60\", \"lat\": 33.3633675, \"lon\": -116.8361345, \"elevation\":", "setup_permissions, create_token from skyportal.tests import api from baselayer.tools.test_frontend import verify_server_availability", "\"filter\": phot_data[\"filter\"].tolist(), }, ) spec_file = os.path.join( os.path.dirname(os.path.dirname(__file__)), \"skyportal\", \"tests\",", "\"thumbnail\", data={ \"source_id\": source_info[\"id\"], \"data\": thumbnail_data, \"ttype\": ttype, }, )", "imaging\", \"Strong calcium lines have emerged.\", ], }, { \"id\":", "33.3633675, \"lon\": -116.8361345, \"elevation\": 1870, \"diameter\": 1.5, \"group_ids\": [group_id], },", "phot_data = pd.read_csv(phot_file) data = assert_post( \"photometry\", data={ \"source_id\": source_info[\"id\"],", "}, ] (basedir / \"static/thumbnails\").mkdir(parents=True, exist_ok=True) for source_info in SOURCES:", "= data[\"data\"][\"id\"] data = assert_post( \"instrument\", data={ \"name\": \"ALFOSC\", \"type\":", "\"P60\", \"lat\": 33.3633675, \"lon\": -116.8361345, \"elevation\": 1870, \"diameter\": 1.5, \"group_ids\":", "group_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) full_user = User(username=\"<EMAIL>\",", "preexec_fn=os.setsid ) server_url = f\"http://localhost:{cfg['ports.app']}\" print() print(f\"Waiting for server to", "\"NOT\", \"lat\": 28.75, \"lon\": 17.88, \"elevation\": 1870, \"diameter\": 2.56, \"group_ids\":", "\"lat\": 28.75, \"lon\": 17.88, \"elevation\": 1870, \"diameter\": 2.56, \"group_ids\": [group_id],", "for source_info in SOURCES: comments = source_info.pop(\"comments\") data = assert_post(\"sources\",", "= os.path.join( os.path.dirname(os.path.dirname(__file__)), \"skyportal\", \"tests\", \"data\", \"spec.csv\", ) spec_data =", "\"Stream A\", \"group_admins\": [ super_admin_user.username, group_admin_user.username, ], }, ) group_id", "import signal import requests from baselayer.app.env import load_env from baselayer.app.model_util", "username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) full_user = User(username=\"<EMAIL>\", role_ids=[\"Full user\"]) view_only_user", "verify_server_availability if __name__ == \"__main__\": \"\"\"Insert test data\"\"\" env, cfg", "user\"]) view_only_user = User( username=\"<EMAIL>\", role_ids=[\"View only\"] ) DBSession().add_all( [super_admin_user,", "{data[\"message\"]}' ) return data with status(\"Launching web app & executing", "\"lon\": -116.8361345, \"elevation\": 1870, \"diameter\": 1.5, \"group_ids\": [group_id], }, )", "\"ref\", \"sub\"]: fname = f'{source_info[\"id\"]}_{ttype}.png' fpath = basedir / f\"skyportal/tests/data/{fname}\"", "\"\"\"Insert test data\"\"\" env, cfg = load_env() basedir = Path(os.path.dirname(__file__))", "assert_post(\"sources\", data=source_info) assert data[\"data\"][\"id\"] == source_info[\"id\"] for comment in comments:", "status {status}: {data[\"message\"]}' ) return data with status(\"Launching web app", "\"optical\", \"telescope_id\": telescope1_id, }, ) instrument1_id = data[\"data\"][\"id\"] data =", "drop_tables() with status(\"Creating tables\"): create_tables() for model in Base.metadata.tables: print(\"", "if not response_status == 200 and data[\"status\"] == \"success\": raise", "\"band\": \"optical\", \"telescope_id\": telescope1_id, }, ) instrument1_id = data[\"data\"][\"id\"] data", "username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) group_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super admin\"]", "subprocess.Popen( [\"make\", \"run\"], cwd=basedir, preexec_fn=os.setsid ) server_url = f\"http://localhost:{cfg['ports.app']}\" print()", "data[\"status\"] == \"success\": raise RuntimeError( f'API call to {endpoint} failed", "f\"skyportal/tests/data/{fname}\" thumbnail_data = base64.b64encode( open(os.path.abspath(fpath), \"rb\").read() ) data = assert_post(", "view_only_user] ) for u in [super_admin_user, group_admin_user, full_user, view_only_user]: DBSession().add(", "\"source_id\": source_info[\"id\"], \"data\": thumbnail_data, \"ttype\": ttype, }, ) source =", "= False web_client = subprocess.Popen( [\"make\", \"run\"], cwd=basedir, preexec_fn=os.setsid )", "\"optical\", \"telescope_id\": telescope2_id, }, ) with status(\"Creating dummy sources\"): SOURCES", "\"group_ids\": [group_id], \"comments\": [ \"No source at transient location to", "thumbnail_data = base64.b64encode( open(os.path.abspath(fpath), \"rb\").read() ) data = assert_post( \"thumbnail\",", "\"e_mag\": phot_data.e_mag.tolist(), \"lim_mag\": phot_data.lim_mag.tolist(), \"filter\": phot_data[\"filter\"].tolist(), }, ) spec_file =", "\"P60 Camera\", \"type\": \"phot\", \"band\": \"optical\", \"telescope_id\": telescope1_id, }, )", "\"The eagle has landed\"], }, ] (basedir / \"static/thumbnails\").mkdir(parents=True, exist_ok=True)", "assert_post( \"telescope\", data={ \"name\": \"Palomar 1.5m\", \"nickname\": \"P60\", \"lat\": 33.3633675,", ") for ttype in [\"new\", \"ref\", \"sub\"]: fname = f'{source_info[\"id\"]}_{ttype}.png'", "= assert_post( \"photometry\", data={ \"source_id\": source_info[\"id\"], \"time_format\": \"iso\", \"time_scale\": \"utc\",", "phot_data.observed_at.tolist(), \"mag\": phot_data.mag.tolist(), \"e_mag\": phot_data.e_mag.tolist(), \"lim_mag\": phot_data.lim_mag.tolist(), \"filter\": phot_data[\"filter\"].tolist(), },", "data\"\"\" env, cfg = load_env() basedir = Path(os.path.dirname(__file__)) / \"..\"", "], }, ) group_id = data[\"data\"][\"id\"] for u in [view_only_user,", "admin\"] ) full_user = User(username=\"<EMAIL>\", role_ids=[\"Full user\"]) view_only_user = User(", "= assert_post( \"comment\", data={\"source_id\": source_info[\"id\"], \"text\": comment}, ) phot_file =", "\"group_ids\": [group_id], }, ) telescope2_id = data[\"data\"][\"id\"] data = assert_post(", "for ttype in [\"new\", \"ref\", \"sub\"]: fname = f'{source_info[\"id\"]}_{ttype}.png' fpath", "failed with status {status}: {data[\"message\"]}' ) return data with status(\"Launching", "for comment in comments: data = assert_post( \"comment\", data={\"source_id\": source_info[\"id\"],", "comments: data = assert_post( \"comment\", data={\"source_id\": source_info[\"id\"], \"text\": comment}, )", "= assert_post( \"spectrum\", data={ \"source_id\": source_info[\"id\"], \"observed_at\": str(datetime.datetime(2014, 10, 24)),", "web_client = subprocess.Popen( [\"make\", \"run\"], cwd=basedir, preexec_fn=os.setsid ) server_url =", "\"ttype\": ttype, }, ) source = Source.query.get(source_info[\"id\"]) source.add_linked_thumbnails() finally: if", ") with status(\"Creating dummy instruments\"): data = assert_post( \"telescope\", data={", "\"elevation\": 1870, \"diameter\": 1.5, \"group_ids\": [group_id], }, ) telescope1_id =", ") group_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) full_user =", "from skyportal.tests import api from baselayer.tools.test_frontend import verify_server_availability if __name__", "[\"new\", \"ref\", \"sub\"]: fname = f'{source_info[\"id\"]}_{ttype}.png' fpath = basedir /", "token) if not response_status == 200 and data[\"status\"] == \"success\":", "data={ \"source_id\": source_info[\"id\"], \"observed_at\": str(datetime.datetime(2014, 10, 24)), \"instrument_id\": 1, \"wavelengths\":", "0.0, \"group_ids\": [group_id], \"comments\": [\"Frogs in the pond\", \"The eagle", "], super_admin_user.id, \"load_demo_data token\", ) def assert_post(endpoint, data): response_status, data", "all tables\"): drop_tables() with status(\"Creating tables\"): create_tables() for model in", "Source.query.get(source_info[\"id\"]) source.add_linked_thumbnails() finally: if not app_already_running: print(\"Terminating web app\") os.killpg(os.getpgid(web_client.pid),", "in [super_admin_user, group_admin_user, full_user, view_only_user]: DBSession().add( TornadoStorage.user.create_social_auth(u, u.username, \"google-oauth2\") )", "assert_post( \"thumbnail\", data={ \"source_id\": source_info[\"id\"], \"data\": thumbnail_data, \"ttype\": ttype, },", "[super_admin_user, group_admin_user, full_user, view_only_user] ) for u in [super_admin_user, group_admin_user,", "= pd.read_csv(spec_file) for i, df in spec_data.groupby(\"instrument_id\"): data = assert_post(", "role_ids=[\"Full user\"]) view_only_user = User( username=\"<EMAIL>\", role_ids=[\"View only\"] ) DBSession().add_all(", "api from baselayer.tools.test_frontend import verify_server_availability if __name__ == \"__main__\": \"\"\"Insert", "fpath = basedir / f\"skyportal/tests/data/{fname}\" thumbnail_data = base64.b64encode( open(os.path.abspath(fpath), \"rb\").read()", "phot_data.mag.tolist(), \"e_mag\": phot_data.e_mag.tolist(), \"lim_mag\": phot_data.lim_mag.tolist(), \"filter\": phot_data[\"filter\"].tolist(), }, ) spec_file", "telescope1_id = data[\"data\"][\"id\"] data = assert_post( \"instrument\", data={ \"name\": \"P60", "os import subprocess import base64 from pathlib import Path import", "open(os.path.abspath(fpath), \"rb\").read() ) data = assert_post( \"thumbnail\", data={ \"source_id\": source_info[\"id\"],", "import subprocess import base64 from pathlib import Path import shutil", "33.646149, \"redshift\": 0.063, \"group_ids\": [group_id], \"comments\": [ \"No source at", "\"dec\": 27.574113, \"redshift\": 0.0, \"group_ids\": [group_id], \"comments\": [\"Frogs in the", "__name__ == \"__main__\": \"\"\"Insert test data\"\"\" env, cfg = load_env()", "\"comments\": [ \"No source at transient location to R>26 in", "executing API calls\"): try: response_status, data = api(\"GET\", \"sysinfo\", token=token)", "data = api(\"GET\", \"sysinfo\", token=token) app_already_running = True except requests.ConnectionError:", "return data with status(\"Launching web app & executing API calls\"):", "model) with status(f\"Creating permissions\"): setup_permissions() with status(f\"Creating dummy users\"): super_admin_user", "with status(\"Creating dummy instruments\"): data = assert_post( \"telescope\", data={ \"name\":", "str(datetime.datetime(2014, 10, 24)), \"instrument_id\": 1, \"wavelengths\": df.wavelength.tolist(), \"fluxes\": df.flux.tolist(), },", "admin\"] ) group_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) full_user", "spec_data.groupby(\"instrument_id\"): data = assert_post( \"spectrum\", data={ \"source_id\": source_info[\"id\"], \"observed_at\": str(datetime.datetime(2014,", "status, create_tables, drop_tables from social_tornado.models import TornadoStorage from skyportal.models import", "A\", \"group_admins\": [ super_admin_user.username, group_admin_user.username, ], }, ) group_id =", "print(\" -\", model) with status(f\"Creating permissions\"): setup_permissions() with status(f\"Creating dummy", "if __name__ == \"__main__\": \"\"\"Insert test data\"\"\" env, cfg =", "\"lon\": 17.88, \"elevation\": 1870, \"diameter\": 2.56, \"group_ids\": [group_id], }, )", "assert_post( f\"groups/{group_id}/users/{u.username}\", data={\"admin\": False} ) with status(\"Creating dummy instruments\"): data", "False web_client = subprocess.Popen( [\"make\", \"run\"], cwd=basedir, preexec_fn=os.setsid ) server_url", "except requests.ConnectionError: app_already_running = False web_client = subprocess.Popen( [\"make\", \"run\"],", "\"ALFOSC\", \"type\": \"both\", \"band\": \"optical\", \"telescope_id\": telescope2_id, }, ) with", "os.path.join( os.path.dirname(os.path.dirname(__file__)), \"skyportal\", \"tests\", \"data\", \"spec.csv\", ) spec_data = pd.read_csv(spec_file)", "status(\"Creating dummy group & adding users\"): data = assert_post( \"groups\",", "comments = source_info.pop(\"comments\") data = assert_post(\"sources\", data=source_info) assert data[\"data\"][\"id\"] ==", "have emerged.\", ], }, { \"id\": \"16fil\", \"ra\": 322.718872, \"dec\":", "SOURCES = [ { \"id\": \"14gqr\", \"ra\": 353.36647, \"dec\": 33.646149,", "load_env() basedir = Path(os.path.dirname(__file__)) / \"..\" with status(f\"Connecting to database", "1.5, \"group_ids\": [group_id], }, ) telescope1_id = data[\"data\"][\"id\"] data =", "\"lat\": 33.3633675, \"lon\": -116.8361345, \"elevation\": 1870, \"diameter\": 1.5, \"group_ids\": [group_id],", "\"static/thumbnails\").mkdir(parents=True, exist_ok=True) for source_info in SOURCES: comments = source_info.pop(\"comments\") data", "& executing API calls\"): try: response_status, data = api(\"GET\", \"sysinfo\",", "\"success\": raise RuntimeError( f'API call to {endpoint} failed with status", ") def assert_post(endpoint, data): response_status, data = api(\"POST\", endpoint, data,", "Base.metadata.tables: print(\" -\", model) with status(f\"Creating permissions\"): setup_permissions() with status(f\"Creating", "load_env from baselayer.app.model_util import status, create_tables, drop_tables from social_tornado.models import", "= assert_post(\"sources\", data=source_info) assert data[\"data\"][\"id\"] == source_info[\"id\"] for comment in", ") telescope1_id = data[\"data\"][\"id\"] data = assert_post( \"instrument\", data={ \"name\":", "\"skyportal/tests/data/phot.csv\" phot_data = pd.read_csv(phot_file) data = assert_post( \"photometry\", data={ \"source_id\":", "Telescope\", \"nickname\": \"NOT\", \"lat\": 28.75, \"lon\": 17.88, \"elevation\": 1870, \"diameter\":", "= data[\"data\"][\"id\"] data = assert_post( \"telescope\", data={ \"name\": \"Nordic Optical", "f\"groups/{group_id}/users/{u.username}\", data={\"admin\": False} ) with status(\"Creating dummy instruments\"): data =", "comment}, ) phot_file = basedir / \"skyportal/tests/data/phot.csv\" phot_data = pd.read_csv(phot_file)", "data = assert_post( \"instrument\", data={ \"name\": \"ALFOSC\", \"type\": \"both\", \"band\":", "import status, create_tables, drop_tables from social_tornado.models import TornadoStorage from skyportal.models", "u in [super_admin_user, group_admin_user, full_user, view_only_user]: DBSession().add( TornadoStorage.user.create_social_auth(u, u.username, \"google-oauth2\")", "group_admin_user, full_user, view_only_user]: DBSession().add( TornadoStorage.user.create_social_auth(u, u.username, \"google-oauth2\") ) with status(\"Creating", "\"photometry\", data={ \"source_id\": source_info[\"id\"], \"time_format\": \"iso\", \"time_scale\": \"utc\", \"instrument_id\": instrument1_id,", "}, ) for ttype in [\"new\", \"ref\", \"sub\"]: fname =", "phot_data[\"filter\"].tolist(), }, ) spec_file = os.path.join( os.path.dirname(os.path.dirname(__file__)), \"skyportal\", \"tests\", \"data\",", "status(\"Dropping all tables\"): drop_tables() with status(\"Creating tables\"): create_tables() for model", "= create_token( [ \"Manage groups\", \"Manage sources\", \"Upload data\", \"Comment\",", "in Base.metadata.tables: print(\" -\", model) with status(f\"Creating permissions\"): setup_permissions() with", "User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) group_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super", "baselayer.app.model_util import status, create_tables, drop_tables from social_tornado.models import TornadoStorage from", "data = assert_post( \"spectrum\", data={ \"source_id\": source_info[\"id\"], \"observed_at\": str(datetime.datetime(2014, 10,", "= api(\"GET\", \"sysinfo\", token=token) app_already_running = True except requests.ConnectionError: app_already_running", "17.88, \"elevation\": 1870, \"diameter\": 2.56, \"group_ids\": [group_id], }, ) telescope2_id", "data = assert_post( \"instrument\", data={ \"name\": \"P60 Camera\", \"type\": \"phot\",", "data): response_status, data = api(\"POST\", endpoint, data, token) if not", "only\"] ) DBSession().add_all( [super_admin_user, group_admin_user, full_user, view_only_user] ) for u", "/ \"skyportal/tests/data/phot.csv\" phot_data = pd.read_csv(phot_file) data = assert_post( \"photometry\", data={", "to {endpoint} failed with status {status}: {data[\"message\"]}' ) return data", "status(\"Creating dummy sources\"): SOURCES = [ { \"id\": \"14gqr\", \"ra\":", "/ \"..\" with status(f\"Connecting to database {cfg['database']['database']}\"): init_db(**cfg[\"database\"]) with status(\"Dropping", "= load_env() basedir = Path(os.path.dirname(__file__)) / \"..\" with status(f\"Connecting to", "basedir = Path(os.path.dirname(__file__)) / \"..\" with status(f\"Connecting to database {cfg['database']['database']}\"):", "database {cfg['database']['database']}\"): init_db(**cfg[\"database\"]) with status(\"Dropping all tables\"): drop_tables() with status(\"Creating", "status(f\"Creating dummy users\"): super_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] )", "\"group_ids\": [group_id], }, ) telescope1_id = data[\"data\"][\"id\"] data = assert_post(", "comment in comments: data = assert_post( \"comment\", data={\"source_id\": source_info[\"id\"], \"text\":", "telescope1_id, }, ) instrument1_id = data[\"data\"][\"id\"] data = assert_post( \"telescope\",", "\"mag\": phot_data.mag.tolist(), \"e_mag\": phot_data.e_mag.tolist(), \"lim_mag\": phot_data.lim_mag.tolist(), \"filter\": phot_data[\"filter\"].tolist(), }, )", "Camera\", \"type\": \"phot\", \"band\": \"optical\", \"telescope_id\": telescope1_id, }, ) instrument1_id", "with status(f\"Connecting to database {cfg['database']['database']}\"): init_db(**cfg[\"database\"]) with status(\"Dropping all tables\"):", "\"Manage groups\", \"Manage sources\", \"Upload data\", \"Comment\", \"Manage users\", ],", "init_db(**cfg[\"database\"]) with status(\"Dropping all tables\"): drop_tables() with status(\"Creating tables\"): create_tables()", "\"sysinfo\", token=token) app_already_running = True except requests.ConnectionError: app_already_running = False", "import pandas as pd import signal import requests from baselayer.app.env", "response_status, data = api(\"POST\", endpoint, data, token) if not response_status", "[\"Frogs in the pond\", \"The eagle has landed\"], }, ]", "= basedir / \"skyportal/tests/data/phot.csv\" phot_data = pd.read_csv(phot_file) data = assert_post(", "= User(username=\"<EMAIL>\", role_ids=[\"Full user\"]) view_only_user = User( username=\"<EMAIL>\", role_ids=[\"View only\"]", "running - continuing with API calls\") with status(\"Creating dummy group", "{ \"id\": \"16fil\", \"ra\": 322.718872, \"dec\": 27.574113, \"redshift\": 0.0, \"group_ids\":", "in the pond\", \"The eagle has landed\"], }, ] (basedir", "sources\"): SOURCES = [ { \"id\": \"14gqr\", \"ra\": 353.36647, \"dec\":", "data = assert_post( \"groups\", data={ \"name\": \"Stream A\", \"group_admins\": [", "spec_file = os.path.join( os.path.dirname(os.path.dirname(__file__)), \"skyportal\", \"tests\", \"data\", \"spec.csv\", ) spec_data", "data, token) if not response_status == 200 and data[\"status\"] ==", "init_db, Base, DBSession, Source, User from skyportal.model_util import setup_permissions, create_token", "full_user, view_only_user]: DBSession().add( TornadoStorage.user.create_social_auth(u, u.username, \"google-oauth2\") ) with status(\"Creating token\"):", "\"No source at transient location to R>26 in LRIS imaging\",", "source_info in SOURCES: comments = source_info.pop(\"comments\") data = assert_post(\"sources\", data=source_info)", "RuntimeError( f'API call to {endpoint} failed with status {status}: {data[\"message\"]}'", "baselayer.tools.test_frontend import verify_server_availability if __name__ == \"__main__\": \"\"\"Insert test data\"\"\"", "(basedir / \"static/thumbnails\").mkdir(parents=True, exist_ok=True) for source_info in SOURCES: comments =", ") source = Source.query.get(source_info[\"id\"]) source.add_linked_thumbnails() finally: if not app_already_running: print(\"Terminating", "with status(f\"Creating dummy users\"): super_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super admin\"]", "\"comments\": [\"Frogs in the pond\", \"The eagle has landed\"], },", "True except requests.ConnectionError: app_already_running = False web_client = subprocess.Popen( [\"make\",", "\"data\", \"spec.csv\", ) spec_data = pd.read_csv(spec_file) for i, df in", "status(f\"Creating permissions\"): setup_permissions() with status(f\"Creating dummy users\"): super_admin_user = User(", "= assert_post( \"instrument\", data={ \"name\": \"P60 Camera\", \"type\": \"phot\", \"band\":", "view_only_user = User( username=\"<EMAIL>\", role_ids=[\"View only\"] ) DBSession().add_all( [super_admin_user, group_admin_user,", "for u in [view_only_user, full_user]: data = assert_post( f\"groups/{group_id}/users/{u.username}\", data={\"admin\":", "\"band\": \"optical\", \"telescope_id\": telescope2_id, }, ) with status(\"Creating dummy sources\"):", "assert_post( \"photometry\", data={ \"source_id\": source_info[\"id\"], \"time_format\": \"iso\", \"time_scale\": \"utc\", \"instrument_id\":", "phot_file = basedir / \"skyportal/tests/data/phot.csv\" phot_data = pd.read_csv(phot_file) data =", "{endpoint} failed with status {status}: {data[\"message\"]}' ) return data with", "import api from baselayer.tools.test_frontend import verify_server_availability if __name__ == \"__main__\":", "}, ) instrument1_id = data[\"data\"][\"id\"] data = assert_post( \"telescope\", data={", "1, \"wavelengths\": df.wavelength.tolist(), \"fluxes\": df.flux.tolist(), }, ) for ttype in", ") with status(\"Creating dummy sources\"): SOURCES = [ { \"id\":", "\"rb\").read() ) data = assert_post( \"thumbnail\", data={ \"source_id\": source_info[\"id\"], \"data\":", "data = api(\"POST\", endpoint, data, token) if not response_status ==", "import setup_permissions, create_token from skyportal.tests import api from baselayer.tools.test_frontend import", "data = assert_post( \"photometry\", data={ \"source_id\": source_info[\"id\"], \"time_format\": \"iso\", \"time_scale\":", "= User( username=\"<EMAIL>\", role_ids=[\"View only\"] ) DBSession().add_all( [super_admin_user, group_admin_user, full_user,", "User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) full_user = User(username=\"<EMAIL>\", role_ids=[\"Full user\"])", "pond\", \"The eagle has landed\"], }, ] (basedir / \"static/thumbnails\").mkdir(parents=True,", "[group_id], \"comments\": [ \"No source at transient location to R>26", "\"instrument_id\": 1, \"wavelengths\": df.wavelength.tolist(), \"fluxes\": df.flux.tolist(), }, ) for ttype", "import datetime import os import subprocess import base64 from pathlib", "\"name\": \"P60 Camera\", \"type\": \"phot\", \"band\": \"optical\", \"telescope_id\": telescope1_id, },", "\"name\": \"Stream A\", \"group_admins\": [ super_admin_user.username, group_admin_user.username, ], }, )", "\"Comment\", \"Manage users\", ], super_admin_user.id, \"load_demo_data token\", ) def assert_post(endpoint,", "\"comment\", data={\"source_id\": source_info[\"id\"], \"text\": comment}, ) phot_file = basedir /", "= base64.b64encode( open(os.path.abspath(fpath), \"rb\").read() ) data = assert_post( \"thumbnail\", data={", "data with status(\"Launching web app & executing API calls\"): try:", "thumbnail_data, \"ttype\": ttype, }, ) source = Source.query.get(source_info[\"id\"]) source.add_linked_thumbnails() finally:", ") spec_file = os.path.join( os.path.dirname(os.path.dirname(__file__)), \"skyportal\", \"tests\", \"data\", \"spec.csv\", )", "import verify_server_availability if __name__ == \"__main__\": \"\"\"Insert test data\"\"\" env,", "/ f\"skyportal/tests/data/{fname}\" thumbnail_data = base64.b64encode( open(os.path.abspath(fpath), \"rb\").read() ) data =", "data = assert_post( \"comment\", data={\"source_id\": source_info[\"id\"], \"text\": comment}, ) phot_file", "Source, User from skyportal.model_util import setup_permissions, create_token from skyportal.tests import", "pandas as pd import signal import requests from baselayer.app.env import", "baselayer.app.env import load_env from baselayer.app.model_util import status, create_tables, drop_tables from", "setup_permissions() with status(f\"Creating dummy users\"): super_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super", "data={ \"name\": \"P60 Camera\", \"type\": \"phot\", \"band\": \"optical\", \"telescope_id\": telescope1_id,", "\"fluxes\": df.flux.tolist(), }, ) for ttype in [\"new\", \"ref\", \"sub\"]:", "= Path(os.path.dirname(__file__)) / \"..\" with status(f\"Connecting to database {cfg['database']['database']}\"): init_db(**cfg[\"database\"])", "322.718872, \"dec\": 27.574113, \"redshift\": 0.0, \"group_ids\": [group_id], \"comments\": [\"Frogs in", "os.path.dirname(os.path.dirname(__file__)), \"skyportal\", \"tests\", \"data\", \"spec.csv\", ) spec_data = pd.read_csv(spec_file) for", ") for u in [super_admin_user, group_admin_user, full_user, view_only_user]: DBSession().add( TornadoStorage.user.create_social_auth(u,", "status(\"Creating token\"): token = create_token( [ \"Manage groups\", \"Manage sources\",", "as pd import signal import requests from baselayer.app.env import load_env", "\"name\": \"Nordic Optical Telescope\", \"nickname\": \"NOT\", \"lat\": 28.75, \"lon\": 17.88,", "assert data[\"data\"][\"id\"] == source_info[\"id\"] for comment in comments: data =", "\"groups\", data={ \"name\": \"Stream A\", \"group_admins\": [ super_admin_user.username, group_admin_user.username, ],", "= pd.read_csv(phot_file) data = assert_post( \"photometry\", data={ \"source_id\": source_info[\"id\"], \"time_format\":", "\"sub\"]: fname = f'{source_info[\"id\"]}_{ttype}.png' fpath = basedir / f\"skyportal/tests/data/{fname}\" thumbnail_data", "= subprocess.Popen( [\"make\", \"run\"], cwd=basedir, preexec_fn=os.setsid ) server_url = f\"http://localhost:{cfg['ports.app']}\"", "tables\"): create_tables() for model in Base.metadata.tables: print(\" -\", model) with", "\"source_id\": source_info[\"id\"], \"observed_at\": str(datetime.datetime(2014, 10, 24)), \"instrument_id\": 1, \"wavelengths\": df.wavelength.tolist(),", "source.add_linked_thumbnails() finally: if not app_already_running: print(\"Terminating web app\") os.killpg(os.getpgid(web_client.pid), signal.SIGTERM)", "\"source_id\": source_info[\"id\"], \"time_format\": \"iso\", \"time_scale\": \"utc\", \"instrument_id\": instrument1_id, \"observed_at\": phot_data.observed_at.tolist(),", "try: verify_server_availability(server_url) print(\"App running - continuing with API calls\") with", "basedir / f\"skyportal/tests/data/{fname}\" thumbnail_data = base64.b64encode( open(os.path.abspath(fpath), \"rb\").read() ) data", "u in [view_only_user, full_user]: data = assert_post( f\"groups/{group_id}/users/{u.username}\", data={\"admin\": False}", "assert_post( \"instrument\", data={ \"name\": \"P60 Camera\", \"type\": \"phot\", \"band\": \"optical\",", "in LRIS imaging\", \"Strong calcium lines have emerged.\", ], },", "f'API call to {endpoint} failed with status {status}: {data[\"message\"]}' )", "emerged.\", ], }, { \"id\": \"16fil\", \"ra\": 322.718872, \"dec\": 27.574113,", "web app & executing API calls\"): try: response_status, data =", "data = assert_post( \"telescope\", data={ \"name\": \"Nordic Optical Telescope\", \"nickname\":", "sources\", \"Upload data\", \"Comment\", \"Manage users\", ], super_admin_user.id, \"load_demo_data token\",", "at transient location to R>26 in LRIS imaging\", \"Strong calcium", "has landed\"], }, ] (basedir / \"static/thumbnails\").mkdir(parents=True, exist_ok=True) for source_info", "transient location to R>26 in LRIS imaging\", \"Strong calcium lines", "landed\"], }, ] (basedir / \"static/thumbnails\").mkdir(parents=True, exist_ok=True) for source_info in", "User from skyportal.model_util import setup_permissions, create_token from skyportal.tests import api", "\"time_scale\": \"utc\", \"instrument_id\": instrument1_id, \"observed_at\": phot_data.observed_at.tolist(), \"mag\": phot_data.mag.tolist(), \"e_mag\": phot_data.e_mag.tolist(),", "lines have emerged.\", ], }, { \"id\": \"16fil\", \"ra\": 322.718872,", "\"tests\", \"data\", \"spec.csv\", ) spec_data = pd.read_csv(spec_file) for i, df", "= [ { \"id\": \"14gqr\", \"ra\": 353.36647, \"dec\": 33.646149, \"redshift\":", ") full_user = User(username=\"<EMAIL>\", role_ids=[\"Full user\"]) view_only_user = User( username=\"<EMAIL>\",", "data={ \"source_id\": source_info[\"id\"], \"time_format\": \"iso\", \"time_scale\": \"utc\", \"instrument_id\": instrument1_id, \"observed_at\":", "[ { \"id\": \"14gqr\", \"ra\": 353.36647, \"dec\": 33.646149, \"redshift\": 0.063,", "role_ids=[\"Super admin\"] ) full_user = User(username=\"<EMAIL>\", role_ids=[\"Full user\"]) view_only_user =", "source_info[\"id\"], \"text\": comment}, ) phot_file = basedir / \"skyportal/tests/data/phot.csv\" phot_data", "\"dec\": 33.646149, \"redshift\": 0.063, \"group_ids\": [group_id], \"comments\": [ \"No source", "pd.read_csv(spec_file) for i, df in spec_data.groupby(\"instrument_id\"): data = assert_post( \"spectrum\",", "test data\"\"\" env, cfg = load_env() basedir = Path(os.path.dirname(__file__)) /", "R>26 in LRIS imaging\", \"Strong calcium lines have emerged.\", ],", "= f'{source_info[\"id\"]}_{ttype}.png' fpath = basedir / f\"skyportal/tests/data/{fname}\" thumbnail_data = base64.b64encode(", "token = create_token( [ \"Manage groups\", \"Manage sources\", \"Upload data\",", "df in spec_data.groupby(\"instrument_id\"): data = assert_post( \"spectrum\", data={ \"source_id\": source_info[\"id\"],", ") DBSession().add_all( [super_admin_user, group_admin_user, full_user, view_only_user] ) for u in", "status(\"Creating dummy instruments\"): data = assert_post( \"telescope\", data={ \"name\": \"Palomar", "from skyportal.models import init_db, Base, DBSession, Source, User from skyportal.model_util", "to appear at {server_url}...\") try: verify_server_availability(server_url) print(\"App running - continuing", "\"redshift\": 0.063, \"group_ids\": [group_id], \"comments\": [ \"No source at transient", "continuing with API calls\") with status(\"Creating dummy group & adding", "in spec_data.groupby(\"instrument_id\"): data = assert_post( \"spectrum\", data={ \"source_id\": source_info[\"id\"], \"observed_at\":", "in comments: data = assert_post( \"comment\", data={\"source_id\": source_info[\"id\"], \"text\": comment},", "telescope2_id, }, ) with status(\"Creating dummy sources\"): SOURCES = [", "\"lim_mag\": phot_data.lim_mag.tolist(), \"filter\": phot_data[\"filter\"].tolist(), }, ) spec_file = os.path.join( os.path.dirname(os.path.dirname(__file__)),", "instruments\"): data = assert_post( \"telescope\", data={ \"name\": \"Palomar 1.5m\", \"nickname\":", "data[\"data\"][\"id\"] data = assert_post( \"instrument\", data={ \"name\": \"ALFOSC\", \"type\": \"both\",", "\"skyportal\", \"tests\", \"data\", \"spec.csv\", ) spec_data = pd.read_csv(spec_file) for i,", "data = assert_post( \"telescope\", data={ \"name\": \"Palomar 1.5m\", \"nickname\": \"P60\",", "status(\"Creating tables\"): create_tables() for model in Base.metadata.tables: print(\" -\", model)", "\"diameter\": 2.56, \"group_ids\": [group_id], }, ) telescope2_id = data[\"data\"][\"id\"] data", ") telescope2_id = data[\"data\"][\"id\"] data = assert_post( \"instrument\", data={ \"name\":", "the pond\", \"The eagle has landed\"], }, ] (basedir /", "1870, \"diameter\": 2.56, \"group_ids\": [group_id], }, ) telescope2_id = data[\"data\"][\"id\"]", "in [view_only_user, full_user]: data = assert_post( f\"groups/{group_id}/users/{u.username}\", data={\"admin\": False} )", "\"id\": \"14gqr\", \"ra\": 353.36647, \"dec\": 33.646149, \"redshift\": 0.063, \"group_ids\": [group_id],", "view_only_user]: DBSession().add( TornadoStorage.user.create_social_auth(u, u.username, \"google-oauth2\") ) with status(\"Creating token\"): token", "\"instrument_id\": instrument1_id, \"observed_at\": phot_data.observed_at.tolist(), \"mag\": phot_data.mag.tolist(), \"e_mag\": phot_data.e_mag.tolist(), \"lim_mag\": phot_data.lim_mag.tolist(),", "User( username=\"<EMAIL>\", role_ids=[\"View only\"] ) DBSession().add_all( [super_admin_user, group_admin_user, full_user, view_only_user]", "}, { \"id\": \"16fil\", \"ra\": 322.718872, \"dec\": 27.574113, \"redshift\": 0.0,", "create_tables() for model in Base.metadata.tables: print(\" -\", model) with status(f\"Creating", "subprocess import base64 from pathlib import Path import shutil import", "Path(os.path.dirname(__file__)) / \"..\" with status(f\"Connecting to database {cfg['database']['database']}\"): init_db(**cfg[\"database\"]) with", "in SOURCES: comments = source_info.pop(\"comments\") data = assert_post(\"sources\", data=source_info) assert", "requests.ConnectionError: app_already_running = False web_client = subprocess.Popen( [\"make\", \"run\"], cwd=basedir,", "token\", ) def assert_post(endpoint, data): response_status, data = api(\"POST\", endpoint,", "[ \"Manage groups\", \"Manage sources\", \"Upload data\", \"Comment\", \"Manage users\",", "with status(\"Creating token\"): token = create_token( [ \"Manage groups\", \"Manage", "users\"): data = assert_post( \"groups\", data={ \"name\": \"Stream A\", \"group_admins\":", ") group_id = data[\"data\"][\"id\"] for u in [view_only_user, full_user]: data", ") instrument1_id = data[\"data\"][\"id\"] data = assert_post( \"telescope\", data={ \"name\":", "group_id = data[\"data\"][\"id\"] for u in [view_only_user, full_user]: data =", "model in Base.metadata.tables: print(\" -\", model) with status(f\"Creating permissions\"): setup_permissions()", "full_user = User(username=\"<EMAIL>\", role_ids=[\"Full user\"]) view_only_user = User( username=\"<EMAIL>\", role_ids=[\"View", ") data = assert_post( \"thumbnail\", data={ \"source_id\": source_info[\"id\"], \"data\": thumbnail_data,", "spec_data = pd.read_csv(spec_file) for i, df in spec_data.groupby(\"instrument_id\"): data =", "telescope2_id = data[\"data\"][\"id\"] data = assert_post( \"instrument\", data={ \"name\": \"ALFOSC\",", "\"16fil\", \"ra\": 322.718872, \"dec\": 27.574113, \"redshift\": 0.0, \"group_ids\": [group_id], \"comments\":", "= assert_post( \"instrument\", data={ \"name\": \"ALFOSC\", \"type\": \"both\", \"band\": \"optical\",", "\"Manage users\", ], super_admin_user.id, \"load_demo_data token\", ) def assert_post(endpoint, data):", "API calls\"): try: response_status, data = api(\"GET\", \"sysinfo\", token=token) app_already_running", "{server_url}...\") try: verify_server_availability(server_url) print(\"App running - continuing with API calls\")", "\"14gqr\", \"ra\": 353.36647, \"dec\": 33.646149, \"redshift\": 0.063, \"group_ids\": [group_id], \"comments\":", "server to appear at {server_url}...\") try: verify_server_availability(server_url) print(\"App running -", "api(\"GET\", \"sysinfo\", token=token) app_already_running = True except requests.ConnectionError: app_already_running =", "tables\"): drop_tables() with status(\"Creating tables\"): create_tables() for model in Base.metadata.tables:", "User(username=\"<EMAIL>\", role_ids=[\"Full user\"]) view_only_user = User( username=\"<EMAIL>\", role_ids=[\"View only\"] )", "data = assert_post( \"thumbnail\", data={ \"source_id\": source_info[\"id\"], \"data\": thumbnail_data, \"ttype\":", "response_status == 200 and data[\"status\"] == \"success\": raise RuntimeError( f'API", "f\"http://localhost:{cfg['ports.app']}\" print() print(f\"Waiting for server to appear at {server_url}...\") try:", "data={ \"name\": \"ALFOSC\", \"type\": \"both\", \"band\": \"optical\", \"telescope_id\": telescope2_id, },", "env, cfg = load_env() basedir = Path(os.path.dirname(__file__)) / \"..\" with", "full_user]: data = assert_post( f\"groups/{group_id}/users/{u.username}\", data={\"admin\": False} ) with status(\"Creating", "username=\"<EMAIL>\", role_ids=[\"View only\"] ) DBSession().add_all( [super_admin_user, group_admin_user, full_user, view_only_user] )", "from baselayer.app.model_util import status, create_tables, drop_tables from social_tornado.models import TornadoStorage", "from baselayer.app.env import load_env from baselayer.app.model_util import status, create_tables, drop_tables", "[group_id], }, ) telescope1_id = data[\"data\"][\"id\"] data = assert_post( \"instrument\",", "data=source_info) assert data[\"data\"][\"id\"] == source_info[\"id\"] for comment in comments: data", "assert_post( \"spectrum\", data={ \"source_id\": source_info[\"id\"], \"observed_at\": str(datetime.datetime(2014, 10, 24)), \"instrument_id\":", "fname = f'{source_info[\"id\"]}_{ttype}.png' fpath = basedir / f\"skyportal/tests/data/{fname}\" thumbnail_data =", "\"Manage sources\", \"Upload data\", \"Comment\", \"Manage users\", ], super_admin_user.id, \"load_demo_data", "server_url = f\"http://localhost:{cfg['ports.app']}\" print() print(f\"Waiting for server to appear at", "\"phot\", \"band\": \"optical\", \"telescope_id\": telescope1_id, }, ) instrument1_id = data[\"data\"][\"id\"]", "], }, { \"id\": \"16fil\", \"ra\": 322.718872, \"dec\": 27.574113, \"redshift\":", "basedir / \"skyportal/tests/data/phot.csv\" phot_data = pd.read_csv(phot_file) data = assert_post( \"photometry\",", "shutil import pandas as pd import signal import requests from", "{cfg['database']['database']}\"): init_db(**cfg[\"database\"]) with status(\"Dropping all tables\"): drop_tables() with status(\"Creating tables\"):", "== \"__main__\": \"\"\"Insert test data\"\"\" env, cfg = load_env() basedir", "create_tables, drop_tables from social_tornado.models import TornadoStorage from skyportal.models import init_db,", "= data[\"data\"][\"id\"] for u in [view_only_user, full_user]: data = assert_post(", "users\"): super_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) group_admin_user =", "data[\"data\"][\"id\"] data = assert_post( \"telescope\", data={ \"name\": \"Nordic Optical Telescope\",", "\"..\" with status(f\"Connecting to database {cfg['database']['database']}\"): init_db(**cfg[\"database\"]) with status(\"Dropping all", "DBSession().add_all( [super_admin_user, group_admin_user, full_user, view_only_user] ) for u in [super_admin_user,", "exist_ok=True) for source_info in SOURCES: comments = source_info.pop(\"comments\") data =", "= api(\"POST\", endpoint, data, token) if not response_status == 200", "SOURCES: comments = source_info.pop(\"comments\") data = assert_post(\"sources\", data=source_info) assert data[\"data\"][\"id\"]", "[\"make\", \"run\"], cwd=basedir, preexec_fn=os.setsid ) server_url = f\"http://localhost:{cfg['ports.app']}\" print() print(f\"Waiting", "- continuing with API calls\") with status(\"Creating dummy group &", "import init_db, Base, DBSession, Source, User from skyportal.model_util import setup_permissions,", "appear at {server_url}...\") try: verify_server_availability(server_url) print(\"App running - continuing with", "calls\") with status(\"Creating dummy group & adding users\"): data =", "with status {status}: {data[\"message\"]}' ) return data with status(\"Launching web", "\"time_format\": \"iso\", \"time_scale\": \"utc\", \"instrument_id\": instrument1_id, \"observed_at\": phot_data.observed_at.tolist(), \"mag\": phot_data.mag.tolist(),", "with status(f\"Creating permissions\"): setup_permissions() with status(f\"Creating dummy users\"): super_admin_user =", "& adding users\"): data = assert_post( \"groups\", data={ \"name\": \"Stream", "skyportal.model_util import setup_permissions, create_token from skyportal.tests import api from baselayer.tools.test_frontend", "\"google-oauth2\") ) with status(\"Creating token\"): token = create_token( [ \"Manage", "pd import signal import requests from baselayer.app.env import load_env from", "[ super_admin_user.username, group_admin_user.username, ], }, ) group_id = data[\"data\"][\"id\"] for", "\"load_demo_data token\", ) def assert_post(endpoint, data): response_status, data = api(\"POST\",", "27.574113, \"redshift\": 0.0, \"group_ids\": [group_id], \"comments\": [\"Frogs in the pond\",", "role_ids=[\"Super admin\"] ) group_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] )", "Path import shutil import pandas as pd import signal import", "}, ) telescope1_id = data[\"data\"][\"id\"] data = assert_post( \"instrument\", data={", "\"Palomar 1.5m\", \"nickname\": \"P60\", \"lat\": 33.3633675, \"lon\": -116.8361345, \"elevation\": 1870,", "with status(\"Creating dummy sources\"): SOURCES = [ { \"id\": \"14gqr\",", "permissions\"): setup_permissions() with status(f\"Creating dummy users\"): super_admin_user = User( username=\"<EMAIL>\",", "app_already_running = False web_client = subprocess.Popen( [\"make\", \"run\"], cwd=basedir, preexec_fn=os.setsid", "to R>26 in LRIS imaging\", \"Strong calcium lines have emerged.\",", "group & adding users\"): data = assert_post( \"groups\", data={ \"name\":", "with status(\"Dropping all tables\"): drop_tables() with status(\"Creating tables\"): create_tables() for", "24)), \"instrument_id\": 1, \"wavelengths\": df.wavelength.tolist(), \"fluxes\": df.flux.tolist(), }, ) for", "= assert_post( \"telescope\", data={ \"name\": \"Nordic Optical Telescope\", \"nickname\": \"NOT\",", "= basedir / f\"skyportal/tests/data/{fname}\" thumbnail_data = base64.b64encode( open(os.path.abspath(fpath), \"rb\").read() )", "1870, \"diameter\": 1.5, \"group_ids\": [group_id], }, ) telescope1_id = data[\"data\"][\"id\"]", "create_token from skyportal.tests import api from baselayer.tools.test_frontend import verify_server_availability if", "-\", model) with status(f\"Creating permissions\"): setup_permissions() with status(f\"Creating dummy users\"):", "\"wavelengths\": df.wavelength.tolist(), \"fluxes\": df.flux.tolist(), }, ) for ttype in [\"new\",", "pathlib import Path import shutil import pandas as pd import", "200 and data[\"status\"] == \"success\": raise RuntimeError( f'API call to", "app & executing API calls\"): try: response_status, data = api(\"GET\",", "import shutil import pandas as pd import signal import requests", "\"instrument\", data={ \"name\": \"P60 Camera\", \"type\": \"phot\", \"band\": \"optical\", \"telescope_id\":", "with status(\"Creating dummy group & adding users\"): data = assert_post(", "import TornadoStorage from skyportal.models import init_db, Base, DBSession, Source, User", "data[\"data\"][\"id\"] == source_info[\"id\"] for comment in comments: data = assert_post(", "== source_info[\"id\"] for comment in comments: data = assert_post( \"comment\",", "from pathlib import Path import shutil import pandas as pd", "in [\"new\", \"ref\", \"sub\"]: fname = f'{source_info[\"id\"]}_{ttype}.png' fpath = basedir", "role_ids=[\"View only\"] ) DBSession().add_all( [super_admin_user, group_admin_user, full_user, view_only_user] ) for", "\"type\": \"phot\", \"band\": \"optical\", \"telescope_id\": telescope1_id, }, ) instrument1_id =", "\"instrument\", data={ \"name\": \"ALFOSC\", \"type\": \"both\", \"band\": \"optical\", \"telescope_id\": telescope2_id,", "\"both\", \"band\": \"optical\", \"telescope_id\": telescope2_id, }, ) with status(\"Creating dummy", "DBSession().add( TornadoStorage.user.create_social_auth(u, u.username, \"google-oauth2\") ) with status(\"Creating token\"): token =", "status(\"Launching web app & executing API calls\"): try: response_status, data", "= Source.query.get(source_info[\"id\"]) source.add_linked_thumbnails() finally: if not app_already_running: print(\"Terminating web app\")", "}, ) with status(\"Creating dummy sources\"): SOURCES = [ {", "= assert_post( \"thumbnail\", data={ \"source_id\": source_info[\"id\"], \"data\": thumbnail_data, \"ttype\": ttype,", "\"ra\": 322.718872, \"dec\": 27.574113, \"redshift\": 0.0, \"group_ids\": [group_id], \"comments\": [\"Frogs", "print(\"App running - continuing with API calls\") with status(\"Creating dummy", "353.36647, \"dec\": 33.646149, \"redshift\": 0.063, \"group_ids\": [group_id], \"comments\": [ \"No", "groups\", \"Manage sources\", \"Upload data\", \"Comment\", \"Manage users\", ], super_admin_user.id,", "for i, df in spec_data.groupby(\"instrument_id\"): data = assert_post( \"spectrum\", data={", "] (basedir / \"static/thumbnails\").mkdir(parents=True, exist_ok=True) for source_info in SOURCES: comments", "for model in Base.metadata.tables: print(\" -\", model) with status(f\"Creating permissions\"):", "for u in [super_admin_user, group_admin_user, full_user, view_only_user]: DBSession().add( TornadoStorage.user.create_social_auth(u, u.username,", ") with status(\"Creating token\"): token = create_token( [ \"Manage groups\",", "source at transient location to R>26 in LRIS imaging\", \"Strong", "\"utc\", \"instrument_id\": instrument1_id, \"observed_at\": phot_data.observed_at.tolist(), \"mag\": phot_data.mag.tolist(), \"e_mag\": phot_data.e_mag.tolist(), \"lim_mag\":", "== 200 and data[\"status\"] == \"success\": raise RuntimeError( f'API call", "requests from baselayer.app.env import load_env from baselayer.app.model_util import status, create_tables,", "\"ra\": 353.36647, \"dec\": 33.646149, \"redshift\": 0.063, \"group_ids\": [group_id], \"comments\": [", "\"Upload data\", \"Comment\", \"Manage users\", ], super_admin_user.id, \"load_demo_data token\", )", "28.75, \"lon\": 17.88, \"elevation\": 1870, \"diameter\": 2.56, \"group_ids\": [group_id], },", "create_token( [ \"Manage groups\", \"Manage sources\", \"Upload data\", \"Comment\", \"Manage", "super_admin_user = User( username=\"<EMAIL>\", role_ids=[\"Super admin\"] ) group_admin_user = User(", "for server to appear at {server_url}...\") try: verify_server_availability(server_url) print(\"App running", "print(f\"Waiting for server to appear at {server_url}...\") try: verify_server_availability(server_url) print(\"App", "1.5m\", \"nickname\": \"P60\", \"lat\": 33.3633675, \"lon\": -116.8361345, \"elevation\": 1870, \"diameter\":", "}, ) telescope2_id = data[\"data\"][\"id\"] data = assert_post( \"instrument\", data={", "\"Nordic Optical Telescope\", \"nickname\": \"NOT\", \"lat\": 28.75, \"lon\": 17.88, \"elevation\":", "phot_data.lim_mag.tolist(), \"filter\": phot_data[\"filter\"].tolist(), }, ) spec_file = os.path.join( os.path.dirname(os.path.dirname(__file__)), \"skyportal\",", "assert_post( \"telescope\", data={ \"name\": \"Nordic Optical Telescope\", \"nickname\": \"NOT\", \"lat\":", "\"type\": \"both\", \"band\": \"optical\", \"telescope_id\": telescope2_id, }, ) with status(\"Creating", "response_status, data = api(\"GET\", \"sysinfo\", token=token) app_already_running = True except", "\"observed_at\": str(datetime.datetime(2014, 10, 24)), \"instrument_id\": 1, \"wavelengths\": df.wavelength.tolist(), \"fluxes\": df.flux.tolist(),", "group_admin_user.username, ], }, ) group_id = data[\"data\"][\"id\"] for u in" ]
[ "NoAlertPresentException: self.logger.error(\"XSS failed\") if self.visible: time.sleep(10) driver.cleanup() return def verify(self):", "Copyright 2013 University of Maryland. All rights reserved. # Use", "return def exploit(self): driver = self.create_selenium_driver() driver.get(\"http://localhost/cuteflow/pages/showmaillist.php?sortby=\\\"><script>alert(\\\"XSS\\\");</script><p+\\\"\") self.logger.info(\"XSS link visited\")", "University of Maryland. All rights reserved. # Use of this", "import NoAlertPresentException import framework class Exploit (framework.Exploit): attributes = {'Name'", "cross site scripting attack.\", 'References' : [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']], 'Target' : \"CuteFlow", "import os import time from selenium.common.exceptions import NoAlertPresentException import framework", "self.logger.info(\"XSS link visited\") try: driver.get_alert() self.logger.info(\"XSS popup comfirmed\") self.verified =", "self.create_selenium_driver() driver.get(\"http://localhost/cuteflow/pages/showmaillist.php?sortby=\\\"><script>alert(\\\"XSS\\\");</script><p+\\\"\") self.logger.info(\"XSS link visited\") try: driver.get_alert() self.logger.info(\"XSS popup comfirmed\")", "False return def exploit(self): driver = self.create_selenium_driver() driver.get(\"http://localhost/cuteflow/pages/showmaillist.php?sortby=\\\"><script>alert(\\\"XSS\\\");</script><p+\\\"\") self.logger.info(\"XSS link", "that can be found in the LICENSE.TXT file. import sys", "# license that can be found in the LICENSE.TXT file.", "# Use of this source code is governed by a", "visited\") try: driver.get_alert() self.logger.info(\"XSS popup comfirmed\") self.verified = True except", "link visited\") try: driver.get_alert() self.logger.info(\"XSS popup comfirmed\") self.verified = True", "= self.create_selenium_driver() driver.get(\"http://localhost/cuteflow/pages/showmaillist.php?sortby=\\\"><script>alert(\\\"XSS\\\");</script><p+\\\"\") self.logger.info(\"XSS link visited\") try: driver.get_alert() self.logger.info(\"XSS popup", "import time from selenium.common.exceptions import NoAlertPresentException import framework class Exploit", "of Maryland. All rights reserved. # Use of this source", "attributes = {'Name' : \"CUTEFLOW_0024\", 'Description' : \"CuteFlow v2.11.2 cross", "LICENSE.TXT file. import sys import os import time from selenium.common.exceptions", "can be found in the LICENSE.TXT file. import sys import", "framework class Exploit (framework.Exploit): attributes = {'Name' : \"CUTEFLOW_0024\", 'Description'", "= True except NoAlertPresentException: self.logger.error(\"XSS failed\") if self.visible: time.sleep(10) driver.cleanup()", "(framework.Exploit): attributes = {'Name' : \"CUTEFLOW_0024\", 'Description' : \"CuteFlow v2.11.2", "failed\") if self.visible: time.sleep(10) driver.cleanup() return def verify(self): return self.verified", "2013 University of Maryland. All rights reserved. # Use of", "reserved. # Use of this source code is governed by", "site scripting attack.\", 'References' : [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']], 'Target' : \"CuteFlow 2.11.2\",", "True except NoAlertPresentException: self.logger.error(\"XSS failed\") if self.visible: time.sleep(10) driver.cleanup() return", ": [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']], 'Target' : \"CuteFlow 2.11.2\", 'TargetLicense' : '', 'VulWikiPage'", "os import time from selenium.common.exceptions import NoAlertPresentException import framework class", ": \"CuteFlow v2.11.2 cross site scripting attack.\", 'References' : [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']],", "visible=False): framework.Exploit.__init__(self, visible) self.verified = False return def exploit(self): driver", "from selenium.common.exceptions import NoAlertPresentException import framework class Exploit (framework.Exploit): attributes", "'Target' : \"CuteFlow 2.11.2\", 'TargetLicense' : '', 'VulWikiPage' : \"\",", "'XSS' } def __init__(self, visible=False): framework.Exploit.__init__(self, visible) self.verified = False", "BSD-style # license that can be found in the LICENSE.TXT", "sys import os import time from selenium.common.exceptions import NoAlertPresentException import", "'References' : [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']], 'Target' : \"CuteFlow 2.11.2\", 'TargetLicense' : '',", "self.verified = False return def exploit(self): driver = self.create_selenium_driver() driver.get(\"http://localhost/cuteflow/pages/showmaillist.php?sortby=\\\"><script>alert(\\\"XSS\\\");</script><p+\\\"\")", "import sys import os import time from selenium.common.exceptions import NoAlertPresentException", "selenium.common.exceptions import NoAlertPresentException import framework class Exploit (framework.Exploit): attributes =", "'TargetLicense' : '', 'VulWikiPage' : \"\", 'Type' : 'XSS' }", "Use of this source code is governed by a BSD-style", "__init__(self, visible=False): framework.Exploit.__init__(self, visible) self.verified = False return def exploit(self):", "# Copyright 2013 University of Maryland. All rights reserved. #", "= {'Name' : \"CUTEFLOW_0024\", 'Description' : \"CuteFlow v2.11.2 cross site", "All rights reserved. # Use of this source code is", "license that can be found in the LICENSE.TXT file. import", "found in the LICENSE.TXT file. import sys import os import", "comfirmed\") self.verified = True except NoAlertPresentException: self.logger.error(\"XSS failed\") if self.visible:", ": \"CuteFlow 2.11.2\", 'TargetLicense' : '', 'VulWikiPage' : \"\", 'Type'", "def exploit(self): driver = self.create_selenium_driver() driver.get(\"http://localhost/cuteflow/pages/showmaillist.php?sortby=\\\"><script>alert(\\\"XSS\\\");</script><p+\\\"\") self.logger.info(\"XSS link visited\") try:", "\"\", 'Type' : 'XSS' } def __init__(self, visible=False): framework.Exploit.__init__(self, visible)", "\"CUTEFLOW_0024\", 'Description' : \"CuteFlow v2.11.2 cross site scripting attack.\", 'References'", "Exploit (framework.Exploit): attributes = {'Name' : \"CUTEFLOW_0024\", 'Description' : \"CuteFlow", ": \"\", 'Type' : 'XSS' } def __init__(self, visible=False): framework.Exploit.__init__(self,", "NoAlertPresentException import framework class Exploit (framework.Exploit): attributes = {'Name' :", "attack.\", 'References' : [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']], 'Target' : \"CuteFlow 2.11.2\", 'TargetLicense' :", "= False return def exploit(self): driver = self.create_selenium_driver() driver.get(\"http://localhost/cuteflow/pages/showmaillist.php?sortby=\\\"><script>alert(\\\"XSS\\\");</script><p+\\\"\") self.logger.info(\"XSS", "'VulWikiPage' : \"\", 'Type' : 'XSS' } def __init__(self, visible=False):", "'', 'VulWikiPage' : \"\", 'Type' : 'XSS' } def __init__(self,", "self.logger.info(\"XSS popup comfirmed\") self.verified = True except NoAlertPresentException: self.logger.error(\"XSS failed\")", "in the LICENSE.TXT file. import sys import os import time", "exploit(self): driver = self.create_selenium_driver() driver.get(\"http://localhost/cuteflow/pages/showmaillist.php?sortby=\\\"><script>alert(\\\"XSS\\\");</script><p+\\\"\") self.logger.info(\"XSS link visited\") try: driver.get_alert()", "self.verified = True except NoAlertPresentException: self.logger.error(\"XSS failed\") if self.visible: time.sleep(10)", "class Exploit (framework.Exploit): attributes = {'Name' : \"CUTEFLOW_0024\", 'Description' :", "code is governed by a BSD-style # license that can", "is governed by a BSD-style # license that can be", "driver = self.create_selenium_driver() driver.get(\"http://localhost/cuteflow/pages/showmaillist.php?sortby=\\\"><script>alert(\\\"XSS\\\");</script><p+\\\"\") self.logger.info(\"XSS link visited\") try: driver.get_alert() self.logger.info(\"XSS", "self.logger.error(\"XSS failed\") if self.visible: time.sleep(10) driver.cleanup() return def verify(self): return", "rights reserved. # Use of this source code is governed", "def __init__(self, visible=False): framework.Exploit.__init__(self, visible) self.verified = False return def", ": '', 'VulWikiPage' : \"\", 'Type' : 'XSS' } def", "governed by a BSD-style # license that can be found", "be found in the LICENSE.TXT file. import sys import os", "driver.get_alert() self.logger.info(\"XSS popup comfirmed\") self.verified = True except NoAlertPresentException: self.logger.error(\"XSS", "this source code is governed by a BSD-style # license", "\"CuteFlow v2.11.2 cross site scripting attack.\", 'References' : [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']], 'Target'", "try: driver.get_alert() self.logger.info(\"XSS popup comfirmed\") self.verified = True except NoAlertPresentException:", "driver.get(\"http://localhost/cuteflow/pages/showmaillist.php?sortby=\\\"><script>alert(\\\"XSS\\\");</script><p+\\\"\") self.logger.info(\"XSS link visited\") try: driver.get_alert() self.logger.info(\"XSS popup comfirmed\") self.verified", "v2.11.2 cross site scripting attack.\", 'References' : [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']], 'Target' :", "file. import sys import os import time from selenium.common.exceptions import", "\"CuteFlow 2.11.2\", 'TargetLicense' : '', 'VulWikiPage' : \"\", 'Type' :", "{'Name' : \"CUTEFLOW_0024\", 'Description' : \"CuteFlow v2.11.2 cross site scripting", "source code is governed by a BSD-style # license that", "framework.Exploit.__init__(self, visible) self.verified = False return def exploit(self): driver =", "[['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']], 'Target' : \"CuteFlow 2.11.2\", 'TargetLicense' : '', 'VulWikiPage' :", "a BSD-style # license that can be found in the", "time from selenium.common.exceptions import NoAlertPresentException import framework class Exploit (framework.Exploit):", ": \"CUTEFLOW_0024\", 'Description' : \"CuteFlow v2.11.2 cross site scripting attack.\",", "} def __init__(self, visible=False): framework.Exploit.__init__(self, visible) self.verified = False return", "of this source code is governed by a BSD-style #", "popup comfirmed\") self.verified = True except NoAlertPresentException: self.logger.error(\"XSS failed\") if", "visible) self.verified = False return def exploit(self): driver = self.create_selenium_driver()", "import framework class Exploit (framework.Exploit): attributes = {'Name' : \"CUTEFLOW_0024\",", "'Type' : 'XSS' } def __init__(self, visible=False): framework.Exploit.__init__(self, visible) self.verified", "scripting attack.\", 'References' : [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']], 'Target' : \"CuteFlow 2.11.2\", 'TargetLicense'", "except NoAlertPresentException: self.logger.error(\"XSS failed\") if self.visible: time.sleep(10) driver.cleanup() return def", "Maryland. All rights reserved. # Use of this source code", "by a BSD-style # license that can be found in", "'Description' : \"CuteFlow v2.11.2 cross site scripting attack.\", 'References' :", "the LICENSE.TXT file. import sys import os import time from", "2.11.2\", 'TargetLicense' : '', 'VulWikiPage' : \"\", 'Type' : 'XSS'", ": 'XSS' } def __init__(self, visible=False): framework.Exploit.__init__(self, visible) self.verified =" ]
[ "a new inline button to open the desired URL on", "the entire keyboard will be reconfigured to be usable only", "users that are @mentioned in the text of the message", "keyboard button to request the user's location on click. ``resize``,", "resize=resize, single_use=single_use, selective=selective) @classmethod def request_poll(cls, text, *, force_quiz=False, resize=None,", "was pressed. \"\"\" if not data: data = text.encode('utf-8') elif", "text. Args: resize (`bool`): If present, the entire keyboard will", "the user clicks this button, a confirmation box will be", "single_use=single_use, selective=selective) @staticmethod def clear(): \"\"\" Clears all keyboard buttons", "markup. When used, no other button should be present or", "isinstance(button, ( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl, types.InputKeyboardButtonUrlAuth )) @staticmethod def inline(text,", "new keyboard button with the given text. Args: resize (`bool`):", "... import utils class Button: \"\"\" .. note:: This class", "bytes, consider saving the real data in a database and", "isinstance(data, (bytes, bytearray, memoryview)): data = str(data).encode('utf-8') if len(data) >", "with the username of your bot followed by the query", "shown to the user asking whether they want to login", "ignored. \"\"\" return types.ReplyKeyboardHide() @staticmethod def force_reply(): \"\"\" Forces a", "`events.CallbackQuery <telethon.events.callbackquery.CallbackQuery>` will trigger with the same data that the", "`data` should be either `bytes` or `str`. Note that the", "poll to be a quiz or not. Otherwise, the user", "``Button(...)`` but instead use methods line `Button.inline(...) <inline>` etc. You", "142 characters. If more characters are given, Telegram will cut", "login to the specified domain. \"\"\" return types.InputKeyboardButtonUrlAuth( text=text, url=url", "the user typing and sending exactly the same text on", "markup (replaces the user keyboard). You can also configure the", "fwd_text (`str`): The new text to show in the button", "@staticmethod def clear(): \"\"\" Clears all keyboard buttons after sending", "If more than 64 bytes are passed as data, ``ValueError``", "do create one, the poll will be sent. \"\"\" return", "shown to the user (messages contain the buttons, not the", "this argument. If you want to use a different bot", "a poll. If `force_quiz` is `False`, the user will be", "the currently opened chat. Otherwise, the user will have to", "bot, and if confirmed a message with geo media will", "129. \"\"\" def __init__(self, button, *, resize, single_use, selective): self.button", "it hides itself. selective (`bool`): If present, the entire keyboard", "geo media will be sent. \"\"\" return cls(types.KeyboardButtonRequestGeoLocation(text), resize=resize, single_use=single_use,", "poll will be sent. \"\"\" return cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz), resize=resize, single_use=single_use,", "`bot` via `@BotFather <https://t.me/BotFather>`_ using the ``/setdomain`` command. For more", "*, force_quiz=False, resize=None, single_use=None, selective=None): \"\"\" Creates a new keyboard", "the message). You can use `text`, `request_location`, `request_phone` and `request_poll`", "a new inline button to switch to inline query. If", "cannot use ID or username for this argument. If you", "present or it will be ignored. \"\"\" return types.ReplyKeyboardHide() @staticmethod", "Helper class to allow defining ``reply_markup`` when sending a message", "to open the desired URL on click. If no `url`", "button contained, so that you can determine which button was", "in the text of the message or to the sender", "The bot that requires this authorization. By default, this is", "this button, a confirmation box will be shown to the", "set the `url` to be on the same domain as", "different dialog to make the query. When the user clicks", "be shown only to specific users. It will target users", "for this argument. If you want to use a different", "button, a confirmation box will be shown to the user", "reconfigured to be resized and be smaller if there are", "a quiz, there will be only one answer that is", "a reply to the message with this markup. If used,", "user typing and sending exactly the same text on their", "cannot be retracted. Otherwise, users can vote and retract the", "single_use, selective): self.button = button self.resize = resize self.single_use =", "return types.InputKeyboardButtonUrlAuth( text=text, url=url or text, bot=utils.get_input_user(bot or types.InputUserSelf()), request_write_access=write_access,", "no other button should be present or it will be", "chat is selected, their input field will be filled with", "be shown to the user asking whether they want to", "to. When the user clicks this button, a text message", "the inline query will directly be set under the currently", "keyboard will be shown only to specific users. It will", "sent. \"\"\" return cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz), resize=resize, single_use=single_use, selective=selective) @staticmethod def", "screen letting the user create a poll will be shown,", "either `bytes` or `str`. Note that the given `data` must", "memoryview)): data = str(data).encode('utf-8') if len(data) > 64: raise ValueError('Too", "If no `url` is specified, it will default to `text`.", "and the pol might be multiple choice. ``resize``, ``single_use`` and", "\"\"\" Creates a new inline button with some payload data", "= resize self.single_use = single_use self.selective = selective @staticmethod def", "resize=resize, single_use=single_use, selective=selective) @classmethod def request_location(cls, text, *, resize=None, single_use=None,", "users. It will target users that are @mentioned in the", "now, you cannot use ID or username for this argument.", "is used to **define** reply markups, e.g. when sending a", "will be the same. When the user clicks this button,", "def auth(text, url=None, *, bot=None, write_access=False, fwd_text=None): \"\"\" Creates a", "smaller if there are not many buttons. single_use (`bool`): If", "button with the given text. Args: resize (`bool`): If present,", "from ... import utils class Button: \"\"\" .. note:: This", "select a different dialog to make the query. When the", "or not. Otherwise, the user will be forced to create", "or equal to 64 bytes. If more than 64 bytes", "selective): self.button = button self.resize = resize self.single_use = single_use", "= text.encode('utf-8') elif not isinstance(data, (bytes, bytearray, memoryview)): data =", "`text`. When the user clicks this button, a confirmation box", "to allow defining ``reply_markup`` when sending a message with inline", "will target users that are @mentioned in the text of", "forwarded. By default, the button text will be the same.", "and ``selective`` are documented in `text`. When the user clicks", "media will be sent. \"\"\" return cls(types.KeyboardButtonRequestGeoLocation(text), resize=resize, single_use=single_use, selective=selective)", "of the message you reply to. When the user clicks", "the user clicked this button directly. When the user clicks", "they want to share their phone with the bot, and", "clicks this button, a screen letting the user create a", "or it will be ignored. \"\"\" return types.ReplyKeyboardHide() @staticmethod def", "the two type of buttons together, and it will error", "Telegram will cut the text to 128 characters and add", "types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl, types.InputKeyboardButtonUrlAuth )) @staticmethod def inline(text, data=None): \"\"\" Creates", "want to refer to that class instead. Helper class to", "buttons may be at most 142 characters. If more characters", "\"\"\" return isinstance(button, ( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl, types.InputKeyboardButtonUrlAuth )) @staticmethod", "url=None): \"\"\" Creates a new inline button to open the", "you try to do so. The text for all buttons", "to the user asking whether they want to login to", "be \"selective\". The keyboard will be shown only to specific", "the one shown to the user (messages contain the buttons,", "the desired URL on click. If no `url` is given,", "create a reply markup (replaces the user keyboard). You can", "You should set the `url` to be on the same", "`url` to be on the same domain as the one", "the entire keyboard will be reconfigured to be resized and", "a text message with the same text as the button", "users can vote and retract the vote, and the pol", "types.InputUserSelf()), request_write_access=write_access, fwd_text=fwd_text ) @classmethod def text(cls, text, *, resize=None,", "text to be used when making the inline query. If", "resize=None, single_use=None, selective=None): \"\"\" Creates a new keyboard button with", "the button contained, so that you can determine which button", "message). You can use `text`, `request_location`, `request_phone` and `request_poll` together", "text on their own. \"\"\" return cls(types.KeyboardButton(text), resize=resize, single_use=single_use, selective=selective)", "default (read-only access). fwd_text (`str`): The new text to show", "forced to create a quiz when creating the poll. If", "so you might want to refer to that class instead.", "write access is required or not. This is `False` by", "keyboard button to request the user's phone on click. ``resize``,", "data') return types.KeyboardButtonCallback(text, data) @staticmethod def switch_inline(text, query='', same_peer=False): \"\"\"", "consider saving the real data in a database and a", "queries. \"\"\" return types.KeyboardButtonSwitchInline(text, query, same_peer) @staticmethod def url(text, url=None):", "a confirmation box will be shown to the user asking", "pressed. \"\"\" if not data: data = text.encode('utf-8') elif not", "be the default text to be used when making the", "given, the `text` will be used as said URL instead.", "By default, the button text will be the same. When", "text, *, force_quiz=False, resize=None, single_use=None, selective=None): \"\"\" Creates a new", "The text for all buttons may be at most 142", "is selected, their input field will be filled with the", "resized and be smaller if there are not many buttons.", "be reconfigured to be usable only once before it hides", "trusted, and once confirmed the URL will open in their", "do so. The text for all buttons may be at", "database and a reference to that data inside the button.", "will be allowed to choose whether they want their poll", "dialog to make the query. When the user clicks this", "switch to inline query. If `query` is given, it will", "button, a screen letting the user create a poll will", "sending a message with this markup. When used, no other", "type of buttons together, and it will error if you", "a new inline button to authorize the user at the", "will be sent, and can be handled with `events.NewMessage <telethon.events.newmessage.NewMessage>`.", "the username of your bot followed by the query text,", "there will be only one answer that is valid, and", "When the user clicks this button, a confirmation box will", "than the one currently logged in, you must manually use", "be the same. When the user clicks this button, a", "access `Message.buttons <telethon.tl.custom.message.Message.buttons>` they are actually `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`, so you", "the user's location on click. ``resize``, ``single_use`` and ``selective`` are", "in it. If `data` is omitted, the given `text` will", "markup. If used, no other button should be present or", "the given `data` must be less or equal to 64", "button text will be the same. When the user clicks", "instead use methods line `Button.inline(...) <inline>` etc. You can use", "a poll will be shown, and if they do create", "\"\"\" return types.InputKeyboardButtonUrlAuth( text=text, url=url or text, bot=utils.get_input_user(bot or types.InputUserSelf()),", "username of your bot followed by the query text, ready", "request_phone(cls, text, *, resize=None, single_use=None, selective=None): \"\"\" Creates a new", "create a quiz when creating the poll. If a poll", "be sent. \"\"\" return cls(types.KeyboardButtonRequestGeoLocation(text), resize=resize, single_use=single_use, selective=selective) @classmethod def", "with these. The latest message with a reply markup will", "as the 129. \"\"\" def __init__(self, button, *, resize, single_use,", "is the bot that is currently logged in (itself), although", "(under the message). You can use `text`, `request_location`, `request_phone` and", "most 142 characters. If more characters are given, Telegram will", "cls(types.KeyboardButtonRequestGeoLocation(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_phone(cls, text, *, resize=None,", "whether they want to share their location with the bot,", "if the button belongs to an inline keyboard. \"\"\" return", "to do so. The text for all buttons may be", "single_use=single_use, selective=selective) @classmethod def request_phone(cls, text, *, resize=None, single_use=None, selective=None):", "str(data).encode('utf-8') if len(data) > 64: raise ValueError('Too many bytes for", "given `text` will be used as `data`. In any case", "with `events.NewMessage <telethon.events.newmessage.NewMessage>`. You cannot distinguish between a button press", "return cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz), resize=resize, single_use=single_use, selective=selective) @staticmethod def clear(): \"\"\"", "not many buttons. single_use (`bool`): If present, the entire keyboard", "actually `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`, so you might want to refer to", "cut the text to 128 characters and add the ellipsis", "the button belongs to an inline keyboard. \"\"\" return isinstance(button,", "= str(data).encode('utf-8') if len(data) > 64: raise ValueError('Too many bytes", "a chat is selected, their input field will be filled", "message with the same text as the button will be", "will default to `text`. Args: bot (`hints.EntityLike`): The bot that", "the user asking whether they want to share their phone", "this markup. If used, no other button should be present", "inline button to open the desired URL on click. If", "user clicked this button directly. When the user clicks this", "open in their device. \"\"\" return types.KeyboardButtonUrl(text, url or text)", "user asking whether they want to open the displayed URL", "data that the button contained, so that you can determine", "press and the user typing and sending exactly the same", "text, ready to make inline queries. \"\"\" return types.KeyboardButtonSwitchInline(text, query,", "must manually use `client.get_input_entity() <telethon.client.users.UserMethods.get_input_entity>`. write_access (`bool`): Whether write access", "keyboard will be reconfigured to be usable only once before", "typing and sending exactly the same text on their own.", "and sending exactly the same text on their own. \"\"\"", "`Button.inline(...) <inline>` etc. You can use `inline`, `switch_inline`, `url` and", "together, and it will error if you try to do", "the `url` to be on the same domain as the", "shown, and if they do create one, the poll will", "or types.InputUserSelf()), request_write_access=write_access, fwd_text=fwd_text ) @classmethod def text(cls, text, *,", "that you can determine which button was pressed. \"\"\" if", "information about letting the user login via Telegram to a", "user's phone on click. ``resize``, ``single_use`` and ``selective`` are documented", "user will be forced to create a quiz when creating", "by the query text, ready to make inline queries. \"\"\"", "to create button instances instead making them yourself (i.e. don't", "a new keyboard button with the given text. Args: resize", "query='', same_peer=False): \"\"\" Creates a new inline button to switch", "so. The text for all buttons may be at most", "the message or to the sender of the message you", "When the user clicks this button, a text message with", "to request the user to create a poll. If `force_quiz`", "the same. When the user clicks this button, a confirmation", "single_use self.selective = selective @staticmethod def _is_inline(button): \"\"\" Returns `True`", "answer that is valid, and the votes cannot be retracted.", "and the votes cannot be retracted. Otherwise, users can vote", "and if confirmed a message with geo media will be", "will have to select a different dialog to make the", "be sent. \"\"\" return cls(types.KeyboardButtonRequestPhone(text), resize=resize, single_use=single_use, selective=selective) @classmethod def", "to create a poll. If `force_quiz` is `False`, the user", "inline queries. \"\"\" return types.KeyboardButtonSwitchInline(text, query, same_peer) @staticmethod def url(text,", "will be sent. \"\"\" return cls(types.KeyboardButtonRequestGeoLocation(text), resize=resize, single_use=single_use, selective=selective) @classmethod", "the user create a poll will be shown, and if", "**define** reply markups, e.g. when sending a message or replying", "`url` is given, the `text` will be used as said", "<https://t.me/BotFather>`_ using the ``/setdomain`` command. For more information about letting", "specified domain. \"\"\" return types.InputKeyboardButtonUrlAuth( text=text, url=url or text, bot=utils.get_input_user(bot", "be ignored. \"\"\" return types.ReplyKeyboardHide() @staticmethod def force_reply(): \"\"\" Forces", "force_quiz=False, resize=None, single_use=None, selective=None): \"\"\" Creates a new keyboard button", "will be reconfigured to be resized and be smaller if", "events. When you access `Message.buttons <telethon.tl.custom.message.Message.buttons>` they are actually `MessageButton", "mix the two type of buttons together, and it will", "keyboard. \"\"\" return isinstance(button, ( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl, types.InputKeyboardButtonUrlAuth ))", "instances instead making them yourself (i.e. don't do ``Button(...)`` but", "you reply to. When the user clicks this button, a", "valid, and the votes cannot be retracted. Otherwise, users can", "> 64: raise ValueError('Too many bytes for the data') return", "resize (`bool`): If present, the entire keyboard will be reconfigured", "this button, a screen letting the user create a poll", "instead. Helper class to allow defining ``reply_markup`` when sending a", "You should make use of the defined class methods to", "@classmethod def text(cls, text, *, resize=None, single_use=None, selective=None): \"\"\" Creates", "``resize``, ``single_use`` and ``selective`` are documented in `text`. When the", "`text`. When the user clicks this button, a screen letting", "cannot distinguish between a button press and the user typing", "the text to 128 characters and add the ellipsis (…)", "to 128 characters and add the ellipsis (…) character as", "to create a reply markup (replaces the user keyboard). You", "before it hides itself. selective (`bool`): If present, the entire", "to a certain domain, see https://core.telegram.org/widgets/login. If no `url` is", "chat itself). You **cannot** mix the two type of buttons", "is given, the `text` will be used as said URL", "see https://core.telegram.org/widgets/login. If no `url` is specified, it will default", "user create a poll will be shown, and if they", "text to 128 characters and add the ellipsis (…) character", "inline keyboard. \"\"\" return isinstance(button, ( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl, types.InputKeyboardButtonUrlAuth", "Otherwise, the user will have to select a different dialog", "location with the bot, and if confirmed a message with", "create a poll. If `force_quiz` is `False`, the user will", "used to **define** reply markups, e.g. when sending a message", "given `data` must be less or equal to 64 bytes.", "data: data = text.encode('utf-8') elif not isinstance(data, (bytes, bytearray, memoryview)):", "add the ellipsis (…) character as the 129. \"\"\" def", "text as the button will be sent, and can be", "in `text`. When the user clicks this button, a screen", "a message with this markup. When used, no other button", "= single_use self.selective = selective @staticmethod def _is_inline(button): \"\"\" Returns", "types.KeyboardButtonSwitchInline(text, query, same_peer) @staticmethod def url(text, url=None): \"\"\" Creates a", "button self.resize = resize self.single_use = single_use self.selective = selective", "@classmethod def request_phone(cls, text, *, resize=None, single_use=None, selective=None): \"\"\" Creates", "self.selective = selective @staticmethod def _is_inline(button): \"\"\" Returns `True` if", "be used as `data`. In any case `data` should be", "data in a database and a reference to that data", "will be forced to create a quiz when creating the", "methods to create button instances instead making them yourself (i.e.", "query text, ready to make inline queries. \"\"\" return types.KeyboardButtonSwitchInline(text,", "yourself (i.e. don't do ``Button(...)`` but instead use methods line", "@mentioned in the text of the message or to the", "or replying to events. When you access `Message.buttons <telethon.tl.custom.message.Message.buttons>` they", "same domain as the one configured for the desired `bot`", "def clear(): \"\"\" Clears all keyboard buttons after sending a", "<reponame>HosseyNJF/Telethon from .. import types from ... import utils class", "bytes. If more than 64 bytes are passed as data,", "the button will be sent, and can be handled with", "= button self.resize = resize self.single_use = single_use self.selective =", "with this markup. If used, no other button should be", "types.InputKeyboardButtonUrlAuth( text=text, url=url or text, bot=utils.get_input_user(bot or types.InputUserSelf()), request_write_access=write_access, fwd_text=fwd_text", "user at the given URL. You should set the `url`", "be usable only once before it hides itself. selective (`bool`):", "cls(types.KeyboardButton(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_location(cls, text, *, resize=None,", "the reply with these. The latest message with a reply", "etc. You can use `inline`, `switch_inline`, `url` and `auth` together", "single_use=None, selective=None): \"\"\" Creates a new keyboard button with the", "`bytes` or `str`. Note that the given `data` must be", "as said URL instead. You cannot detect that the user", "to 64 bytes. If more than 64 bytes are passed", "that the button contained, so that you can determine which", "this button directly. When the user clicks this button, a", "same. When the user clicks this button, a confirmation box", "url=url or text, bot=utils.get_input_user(bot or types.InputUserSelf()), request_write_access=write_access, fwd_text=fwd_text ) @classmethod", "new keyboard button to request the user to create a", "URL on click. If no `url` is given, the `text`", "def inline(text, data=None): \"\"\" Creates a new inline button with", "@classmethod def request_poll(cls, text, *, force_quiz=False, resize=None, single_use=None, selective=None): \"\"\"", "quiz=force_quiz), resize=resize, single_use=single_use, selective=selective) @staticmethod def clear(): \"\"\" Clears all", "or text, bot=utils.get_input_user(bot or types.InputUserSelf()), request_write_access=write_access, fwd_text=fwd_text ) @classmethod def", "to the specified domain. \"\"\" return types.InputKeyboardButtonUrlAuth( text=text, url=url or", "return cls(types.KeyboardButton(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_location(cls, text, *,", "if you try to do so. The text for all", "they are actually `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`, so you might want to", "characters are given, Telegram will cut the text to 128", "in, you must manually use `client.get_input_entity() <telethon.client.users.UserMethods.get_input_entity>`. write_access (`bool`): Whether", "= selective @staticmethod def _is_inline(button): \"\"\" Returns `True` if the", "some payload data in it. If `data` is omitted, the", "in their device. \"\"\" return types.KeyboardButtonUrl(text, url or text) @staticmethod", "return cls(types.KeyboardButtonRequestPhone(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_poll(cls, text, *,", "the user keyboard). You can also configure the aspect of", "If you need to store more than 64 bytes, consider", "to store more than 64 bytes, consider saving the real", "together to create a reply markup (replaces the user keyboard).", "to that data inside the button. When the user clicks", "will be filled with the username of your bot followed", "user's location on click. ``resize``, ``single_use`` and ``selective`` are documented", "replying to events. When you access `Message.buttons <telethon.tl.custom.message.Message.buttons>` they are", "be only one answer that is valid, and the votes", "button if the message is forwarded. By default, the button", "their phone with the bot, and if confirmed a message", "\"\"\" Forces a reply to the message with this markup.", "the same text on their own. \"\"\" return cls(types.KeyboardButton(text), resize=resize,", "given, Telegram will cut the text to 128 characters and", "via Telegram to a certain domain, see https://core.telegram.org/widgets/login. If no", "with the bot, and if confirmed a message with geo", "(itself), although you may pass a different input peer. ..", "def text(cls, text, *, resize=None, single_use=None, selective=None): \"\"\" Creates a", "query, same_peer) @staticmethod def url(text, url=None): \"\"\" Creates a new", "request the user's phone on click. ``resize``, ``single_use`` and ``selective``", "inline button to authorize the user at the given URL.", "be less or equal to 64 bytes. If more than", "data) @staticmethod def switch_inline(text, query='', same_peer=False): \"\"\" Creates a new", "request_poll(cls, text, *, force_quiz=False, resize=None, single_use=None, selective=None): \"\"\" Creates a", "Button: \"\"\" .. note:: This class is used to **define**", "def url(text, url=None): \"\"\" Creates a new inline button to", "click. If no `url` is given, the `text` will be", "the given URL. You should set the `url` to be", "keyboard will be reconfigured to be \"selective\". The keyboard will", "button will be sent, and can be handled with `events.NewMessage", "request_location(cls, text, *, resize=None, single_use=None, selective=None): \"\"\" Creates a new", "(`str`): The new text to show in the button if", "whether they want their poll to be a quiz or", "keyboard will be reconfigured to be resized and be smaller", "contact media will be sent. \"\"\" return cls(types.KeyboardButtonRequestPhone(text), resize=resize, single_use=single_use,", "more characters are given, Telegram will cut the text to", "self.single_use = single_use self.selective = selective @staticmethod def _is_inline(button): \"\"\"", "their own. \"\"\" return cls(types.KeyboardButton(text), resize=resize, single_use=single_use, selective=selective) @classmethod def", "the message is forwarded. By default, the button text will", "want their poll to be a quiz or not. Otherwise,", "said URL instead. You cannot detect that the user clicked", "quiz when creating the poll. If a poll is a", "quiz, there will be only one answer that is valid,", "elif not isinstance(data, (bytes, bytearray, memoryview)): data = str(data).encode('utf-8') if", "box will be shown to the user asking whether they", "The new text to show in the button if the", "less or equal to 64 bytes. If more than 64", "len(data) > 64: raise ValueError('Too many bytes for the data')", "the ``/setdomain`` command. For more information about letting the user", "user asking whether they want to login to the specified", "create a poll will be shown, and if they do", "use of the defined class methods to create button instances", "will be used as said URL instead. You cannot detect", "the user asking whether they want to login to the", "itself. selective (`bool`): If present, the entire keyboard will be", "class instead. Helper class to allow defining ``reply_markup`` when sending", "clicks this button, after a chat is selected, their input", "fwd_text=fwd_text ) @classmethod def text(cls, text, *, resize=None, single_use=None, selective=None):", "create button instances instead making them yourself (i.e. don't do", "directly. When the user clicks this button, a confirmation box", "new keyboard button to request the user's location on click.", "given, it will be the default text to be used", "and once confirmed the URL will open in their device.", "the real data in a database and a reference to", "a message with geo media will be sent. \"\"\" return", "is valid, and the votes cannot be retracted. Otherwise, users", "it will default to `text`. Args: bot (`hints.EntityLike`): The bot", "You can use `inline`, `switch_inline`, `url` and `auth` together to", "try to do so. The text for all buttons may", "argument. If you want to use a different bot than", "will be sent. \"\"\" return cls(types.KeyboardButtonRequestPhone(text), resize=resize, single_use=single_use, selective=selective) @classmethod", "user clicks this button, a confirmation box will be shown", "sending a message or replying to events. When you access", "on click. If no `url` is given, the `text` will", "via `@BotFather <https://t.me/BotFather>`_ using the ``/setdomain`` command. For more information", "request_write_access=write_access, fwd_text=fwd_text ) @classmethod def text(cls, text, *, resize=None, single_use=None,", "shown to the user asking whether they want to share", "message with a reply markup will be the one shown", "the user asking whether they want to share their location", "a quiz when creating the poll. If a poll is", "(`bool`): Whether write access is required or not. This is", "this button, a text message with the same text as", "the aspect of the reply with these. The latest message", "\"\"\" return cls(types.KeyboardButtonRequestGeoLocation(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_phone(cls, text,", "force_reply(): \"\"\" Forces a reply to the message with this", "using the ``/setdomain`` command. For more information about letting the", "button with some payload data in it. If `data` is", "new text to show in the button if the message", "True`` the inline query will directly be set under the", "used, no other button should be present or it will", "whether they want to login to the specified domain. \"\"\"", "buttons. single_use (`bool`): If present, the entire keyboard will be", "buttons (under the message). You can use `text`, `request_location`, `request_phone`", "the pol might be multiple choice. ``resize``, ``single_use`` and ``selective``", "be set under the currently opened chat. Otherwise, the user", "of the defined class methods to create button instances instead", "can vote and retract the vote, and the pol might", "inline button with some payload data in it. If `data`", "\"\"\" Creates a new inline button to switch to inline", "(bytes, bytearray, memoryview)): data = str(data).encode('utf-8') if len(data) > 64:", "confirmed the URL will open in their device. \"\"\" return", "they want to share their location with the bot, and", "are actually `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`, so you might want to refer", "Otherwise, users can vote and retract the vote, and the", "raised. If you need to store more than 64 bytes,", "this is the bot that is currently logged in (itself),", "`request_poll` together to create a reply markup (replaces the user", "\"\"\" if not data: data = text.encode('utf-8') elif not isinstance(data,", "a different bot than the one currently logged in, you", "to events. When you access `Message.buttons <telethon.tl.custom.message.Message.buttons>` they are actually", "types.KeyboardButtonUrl(text, url or text) @staticmethod def auth(text, url=None, *, bot=None,", "https://core.telegram.org/widgets/login. If no `url` is specified, it will default to", "single_use=None, selective=None): \"\"\" Creates a new keyboard button to request", "instead. You cannot detect that the user clicked this button", "new inline button to switch to inline query. If `query`", "than 64 bytes, consider saving the real data in a", "present, the entire keyboard will be reconfigured to be resized", "phone with the bot, and if confirmed a message with", "usable only once before it hides itself. selective (`bool`): If", "data inside the button. When the user clicks this button,", "button to request the user's phone on click. ``resize``, ``single_use``", "with the bot, and if confirmed a message with contact", "specified, it will default to `text`. Args: bot (`hints.EntityLike`): The", "user keyboard). You can also configure the aspect of the", "desired `bot` via `@BotFather <https://t.me/BotFather>`_ using the ``/setdomain`` command. For", "must be less or equal to 64 bytes. If more", "message you reply to. When the user clicks this button,", "the query. When the user clicks this button, after a", "their location with the bot, and if confirmed a message", "the ellipsis (…) character as the 129. \"\"\" def __init__(self,", "selective @staticmethod def _is_inline(button): \"\"\" Returns `True` if the button", "\"\"\" Creates a new keyboard button with the given text.", "to choose whether they want their poll to be a", "sending a message with inline or keyboard buttons. You should", "will be sent. \"\"\" return cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz), resize=resize, single_use=single_use, selective=selective)", "this button, after a chat is selected, their input field", "The latest message with a reply markup will be the", "allowed to choose whether they want their poll to be", "return types.KeyboardButtonSwitchInline(text, query, same_peer) @staticmethod def url(text, url=None): \"\"\" Creates", "message with contact media will be sent. \"\"\" return cls(types.KeyboardButtonRequestPhone(text),", "so that you can determine which button was pressed. \"\"\"", "user asking whether they want to share their phone with", "keyboard buttons. You should make use of the defined class", "Forces a reply to the message with this markup. If", "`True` if the button belongs to an inline keyboard. \"\"\"", "will be reconfigured to be usable only once before it", "This is `False` by default (read-only access). fwd_text (`str`): The", "all keyboard buttons after sending a message with this markup.", "data = text.encode('utf-8') elif not isinstance(data, (bytes, bytearray, memoryview)): data", "new inline button to open the desired URL on click.", "write_access=False, fwd_text=None): \"\"\" Creates a new inline button to authorize", "*, resize=None, single_use=None, selective=None): \"\"\" Creates a new keyboard button", "on click. ``resize``, ``single_use`` and ``selective`` are documented in `text`.", "Creates a new inline button to open the desired URL", "the 129. \"\"\" def __init__(self, button, *, resize, single_use, selective):", "keyboard). You can also configure the aspect of the reply", "use ID or username for this argument. If you want", "votes cannot be retracted. Otherwise, users can vote and retract", "might be multiple choice. ``resize``, ``single_use`` and ``selective`` are documented", "need to store more than 64 bytes, consider saving the", "asking whether they want to login to the specified domain.", "will be the default text to be used when making", "types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl, types.InputKeyboardButtonUrlAuth )) @staticmethod def inline(text, data=None): \"\"\"", "as data, ``ValueError`` is raised. If you need to store", "reply markup will be the one shown to the user", "a reference to that data inside the button. When the", "is specified, it will default to `text`. Args: bot (`hints.EntityLike`):", "resize=None, single_use=None, selective=None): \"\"\" Creates a new keyboard button to", "in `text`. When the user clicks this button, a confirmation", "this markup. When used, no other button should be present", "domain. \"\"\" return types.InputKeyboardButtonUrlAuth( text=text, url=url or text, bot=utils.get_input_user(bot or", "domain, see https://core.telegram.org/widgets/login. If no `url` is specified, it will", "\"\"\" return cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz), resize=resize, single_use=single_use, selective=selective) @staticmethod def clear():", "the chat itself). You **cannot** mix the two type of", "currently logged in, you must manually use `client.get_input_entity() <telethon.client.users.UserMethods.get_input_entity>`. write_access", "requires this authorization. By default, this is the bot that", "button to request the user's location on click. ``resize``, ``single_use``", "do ``Button(...)`` but instead use methods line `Button.inline(...) <inline>` etc.", "button instances instead making them yourself (i.e. don't do ``Button(...)``", "bytearray, memoryview)): data = str(data).encode('utf-8') if len(data) > 64: raise", "user asking whether they want to share their location with", "and `auth` together to create inline buttons (under the message).", "selected, their input field will be filled with the username", "want to use a different bot than the one currently", "can use `text`, `request_location`, `request_phone` and `request_poll` together to create", "single_use=single_use, selective=selective) @classmethod def request_location(cls, text, *, resize=None, single_use=None, selective=None):", "128 characters and add the ellipsis (…) character as the", "write_access (`bool`): Whether write access is required or not. This", "or to the sender of the message you reply to.", "field will be filled with the username of your bot", "URL will open in their device. \"\"\" return types.KeyboardButtonUrl(text, url", "poll is a quiz, there will be only one answer", "bot (`hints.EntityLike`): The bot that requires this authorization. By default,", "omitted, the given `text` will be used as `data`. In", "\"\"\" Returns `True` if the button belongs to an inline", "can be handled with `events.NewMessage <telethon.events.newmessage.NewMessage>`. You cannot distinguish between", "sent. \"\"\" return cls(types.KeyboardButtonRequestGeoLocation(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_phone(cls,", "a new keyboard button to request the user's phone on", "use `text`, `request_location`, `request_phone` and `request_poll` together to create a", "cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz), resize=resize, single_use=single_use, selective=selective) @staticmethod def clear(): \"\"\" Clears", "that requires this authorization. By default, this is the bot", "that are @mentioned in the text of the message or", "the same text as the button will be sent, and", "the entire keyboard will be reconfigured to be \"selective\". The", "and it will error if you try to do so.", "more information about letting the user login via Telegram to", "aspect of the reply with these. The latest message with", "switch_inline(text, query='', same_peer=False): \"\"\" Creates a new inline button to", "same text on their own. \"\"\" return cls(types.KeyboardButton(text), resize=resize, single_use=single_use,", "the same domain as the one configured for the desired", "peer. .. note:: For now, you cannot use ID or", "to inline query. If `query` is given, it will be", "\"\"\" return types.ReplyKeyboardHide() @staticmethod def force_reply(): \"\"\" Forces a reply", "fwd_text=None): \"\"\" Creates a new inline button to authorize the", "username for this argument. If you want to use a", "will be shown, and if they do create one, the", "will error if you try to do so. The text", "different input peer. .. note:: For now, you cannot use", "a message with inline or keyboard buttons. You should make", "poll will be shown, and if they do create one,", "this button, `events.CallbackQuery <telethon.events.callbackquery.CallbackQuery>` will trigger with the same data", "be either `bytes` or `str`. Note that the given `data`", "they want to login to the specified domain. \"\"\" return", "poll. If a poll is a quiz, there will be", "the button text will be the same. When the user", "types.KeyboardButtonUrl, types.InputKeyboardButtonUrlAuth )) @staticmethod def inline(text, data=None): \"\"\" Creates a", "given URL. You should set the `url` to be on", "default text to be used when making the inline query.", "<inline>` etc. You can use `inline`, `switch_inline`, `url` and `auth`", "button directly. When the user clicks this button, a confirmation", "many bytes for the data') return types.KeyboardButtonCallback(text, data) @staticmethod def", "`text` will be used as said URL instead. You cannot", "will open in their device. \"\"\" return types.KeyboardButtonUrl(text, url or", "same_peer) @staticmethod def url(text, url=None): \"\"\" Creates a new inline", "the bot, and if confirmed a message with contact media", "making the inline query. If ``same_peer is True`` the inline", "\"\"\" Creates a new keyboard button to request the user", "`auth` together to create inline buttons (under the message). You", "more than 64 bytes, consider saving the real data in", "`text` will be used as `data`. In any case `data`", "same text as the button will be sent, and can", "to refer to that class instead. Helper class to allow", "64: raise ValueError('Too many bytes for the data') return types.KeyboardButtonCallback(text,", "on their own. \"\"\" return cls(types.KeyboardButton(text), resize=resize, single_use=single_use, selective=selective) @classmethod", "text=text, url=url or text, bot=utils.get_input_user(bot or types.InputUserSelf()), request_write_access=write_access, fwd_text=fwd_text )", "raise ValueError('Too many bytes for the data') return types.KeyboardButtonCallback(text, data)", "utils class Button: \"\"\" .. note:: This class is used", "`Message.buttons <telethon.tl.custom.message.Message.buttons>` they are actually `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`, so you might", "If ``same_peer is True`` the inline query will directly be", "def request_poll(cls, text, *, force_quiz=False, resize=None, single_use=None, selective=None): \"\"\" Creates", "desired URL on click. If no `url` is given, the", "default, the button text will be the same. When the", "other button should be present or it will be ignored.", "you might want to refer to that class instead. Helper", "class Button: \"\"\" .. note:: This class is used to", "to **define** reply markups, e.g. when sending a message or", "inside the button. When the user clicks this button, `events.CallbackQuery", "clicks this button, a text message with the same text", "be sent, and can be handled with `events.NewMessage <telethon.events.newmessage.NewMessage>`. You", "Creates a new keyboard button to request the user's location", "a new keyboard button to request the user's location on", "selective=selective) @classmethod def request_phone(cls, text, *, resize=None, single_use=None, selective=None): \"\"\"", "user (messages contain the buttons, not the chat itself). You", "text, *, resize=None, single_use=None, selective=None): \"\"\" Creates a new keyboard", "them yourself (i.e. don't do ``Button(...)`` but instead use methods", "used when making the inline query. If ``same_peer is True``", "if not data: data = text.encode('utf-8') elif not isinstance(data, (bytes,", "all buttons may be at most 142 characters. If more", "be smaller if there are not many buttons. single_use (`bool`):", "to request the user's phone on click. ``resize``, ``single_use`` and", "to select a different dialog to make the query. When", "if confirmed a message with geo media will be sent.", "to an inline keyboard. \"\"\" return isinstance(button, ( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline,", "<telethon.events.newmessage.NewMessage>`. You cannot distinguish between a button press and the", "inline query will directly be set under the currently opened", "media will be sent. \"\"\" return cls(types.KeyboardButtonRequestPhone(text), resize=resize, single_use=single_use, selective=selective)", "making them yourself (i.e. don't do ``Button(...)`` but instead use", "but instead use methods line `Button.inline(...) <inline>` etc. You can", ".. note:: This class is used to **define** reply markups,", "message with this markup. If used, no other button should", "passed as data, ``ValueError`` is raised. If you need to", "about letting the user login via Telegram to a certain", "the specified domain. \"\"\" return types.InputKeyboardButtonUrlAuth( text=text, url=url or text,", "more than 64 bytes are passed as data, ``ValueError`` is", "that class instead. Helper class to allow defining ``reply_markup`` when", "button. When the user clicks this button, `events.CallbackQuery <telethon.events.callbackquery.CallbackQuery>` will", "asking whether they want to share their phone with the", "only one answer that is valid, and the votes cannot", "after sending a message with this markup. When used, no", "same_peer=False): \"\"\" Creates a new inline button to switch to", "\"\"\" Creates a new inline button to authorize the user", "to authorize the user at the given URL. You should", "``ValueError`` is raised. If you need to store more than", "one answer that is valid, and the votes cannot be", "bot=None, write_access=False, fwd_text=None): \"\"\" Creates a new inline button to", "is `False`, the user will be allowed to choose whether", "By default, this is the bot that is currently logged", "filled with the username of your bot followed by the", "bot followed by the query text, ready to make inline", "reconfigured to be usable only once before it hides itself.", "`events.NewMessage <telethon.events.newmessage.NewMessage>`. You cannot distinguish between a button press and", "the votes cannot be retracted. Otherwise, users can vote and", "they do create one, the poll will be sent. \"\"\"", "sender of the message you reply to. When the user", "def request_phone(cls, text, *, resize=None, single_use=None, selective=None): \"\"\" Creates a", "\"\"\" return cls(types.KeyboardButtonRequestPhone(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_poll(cls, text,", "import types from ... import utils class Button: \"\"\" ..", "is trusted, and once confirmed the URL will open in", "a screen letting the user create a poll will be", "will be only one answer that is valid, and the", "the domain is trusted, and once confirmed the URL will", "( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl, types.InputKeyboardButtonUrlAuth )) @staticmethod def inline(text, data=None):", "URL instead. You cannot detect that the user clicked this", "their input field will be filled with the username of", "you cannot use ID or username for this argument. If", "a reply markup (replaces the user keyboard). You can also", "whether they want to share their phone with the bot,", "message with this markup. When used, no other button should", "single_use=single_use, selective=selective) @classmethod def request_poll(cls, text, *, force_quiz=False, resize=None, single_use=None,", "or username for this argument. If you want to use", "it will error if you try to do so. The", "determine which button was pressed. \"\"\" if not data: data", "cannot detect that the user clicked this button directly. When", "shown only to specific users. It will target users that", "choice. ``resize``, ``single_use`` and ``selective`` are documented in `text`. When", ".. import types from ... import utils class Button: \"\"\"", "If no `url` is given, the `text` will be used", "<telethon.client.users.UserMethods.get_input_entity>`. write_access (`bool`): Whether write access is required or not.", "is required or not. This is `False` by default (read-only", "confirmation box will be shown to the user asking whether", "When you access `Message.buttons <telethon.tl.custom.message.Message.buttons>` they are actually `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`,", "`inline`, `switch_inline`, `url` and `auth` together to create inline buttons", "be the one shown to the user (messages contain the", "of buttons together, and it will error if you try", "as the one configured for the desired `bot` via `@BotFather", "not. This is `False` by default (read-only access). fwd_text (`str`):", "It will target users that are @mentioned in the text", "character as the 129. \"\"\" def __init__(self, button, *, resize,", "entire keyboard will be reconfigured to be \"selective\". The keyboard", "that is valid, and the votes cannot be retracted. Otherwise,", "the defined class methods to create button instances instead making", "reply markups, e.g. when sending a message or replying to", "Otherwise, the user will be forced to create a quiz", "is a quiz, there will be only one answer that", "are given, Telegram will cut the text to 128 characters", "letting the user login via Telegram to a certain domain,", "\"\"\" return types.KeyboardButtonSwitchInline(text, query, same_peer) @staticmethod def url(text, url=None): \"\"\"", "and if they do create one, the poll will be", "methods line `Button.inline(...) <inline>` etc. You can use `inline`, `switch_inline`,", "to switch to inline query. If `query` is given, it", "a poll is a quiz, there will be only one", "specific users. It will target users that are @mentioned in", "`data` is omitted, the given `text` will be used as", "pass a different input peer. .. note:: For now, you", "query will directly be set under the currently opened chat.", "followed by the query text, ready to make inline queries.", "URL. You should set the `url` to be on the", "resize self.single_use = single_use self.selective = selective @staticmethod def _is_inline(button):", "asking whether they want to open the displayed URL unless", "@staticmethod def inline(text, data=None): \"\"\" Creates a new inline button", "sent, and can be handled with `events.NewMessage <telethon.events.newmessage.NewMessage>`. You cannot", "\"\"\" .. note:: This class is used to **define** reply", "belongs to an inline keyboard. \"\"\" return isinstance(button, ( types.KeyboardButtonCallback,", "retract the vote, and the pol might be multiple choice.", "a new keyboard button to request the user to create", "the buttons, not the chat itself). You **cannot** mix the", "defined class methods to create button instances instead making them", "user login via Telegram to a certain domain, see https://core.telegram.org/widgets/login.", "domain as the one configured for the desired `bot` via", "For more information about letting the user login via Telegram", "message or to the sender of the message you reply", "clicks this button, `events.CallbackQuery <telethon.events.callbackquery.CallbackQuery>` will trigger with the same", "to the user (messages contain the buttons, not the chat", "@staticmethod def _is_inline(button): \"\"\" Returns `True` if the button belongs", "be filled with the username of your bot followed by", "distinguish between a button press and the user typing and", "between a button press and the user typing and sending", "`text`. Args: bot (`hints.EntityLike`): The bot that requires this authorization.", "that data inside the button. When the user clicks this", "instead making them yourself (i.e. don't do ``Button(...)`` but instead", "a different input peer. .. note:: For now, you cannot", "sending exactly the same text on their own. \"\"\" return", "multiple choice. ``resize``, ``single_use`` and ``selective`` are documented in `text`.", "@classmethod def request_location(cls, text, *, resize=None, single_use=None, selective=None): \"\"\" Creates", "and `request_poll` together to create a reply markup (replaces the", "message is forwarded. By default, the button text will be", "self.button = button self.resize = resize self.single_use = single_use self.selective", "chat. Otherwise, the user will have to select a different", "be present or it will be ignored. \"\"\" return types.ReplyKeyboardForceReply()", "the user at the given URL. You should set the", "should set the `url` to be on the same domain", "return isinstance(button, ( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl, types.InputKeyboardButtonUrlAuth )) @staticmethod def", "the user (messages contain the buttons, not the chat itself).", "to share their phone with the bot, and if confirmed", "no `url` is given, the `text` will be used as", "button, after a chat is selected, their input field will", "and retract the vote, and the pol might be multiple", "If more characters are given, Telegram will cut the text", "be at most 142 characters. If more characters are given,", "a different dialog to make the query. When the user", "when sending a message or replying to events. When you", "are not many buttons. single_use (`bool`): If present, the entire", "only to specific users. It will target users that are", "with the same text as the button will be sent,", "be a quiz or not. Otherwise, the user will be", "user clicks this button, a screen letting the user create", "be present or it will be ignored. \"\"\" return types.ReplyKeyboardHide()", "saving the real data in a database and a reference", "to create inline buttons (under the message). You can use", "`data`. In any case `data` should be either `bytes` or", "inline or keyboard buttons. You should make use of the", "text) @staticmethod def auth(text, url=None, *, bot=None, write_access=False, fwd_text=None): \"\"\"", "one currently logged in, you must manually use `client.get_input_entity() <telethon.client.users.UserMethods.get_input_entity>`.", "Args: resize (`bool`): If present, the entire keyboard will be", "query. When the user clicks this button, after a chat", "if confirmed a message with contact media will be sent.", "reconfigured to be \"selective\". The keyboard will be shown only", "button, a text message with the same text as the", "which button was pressed. \"\"\" if not data: data =", "confirmed a message with contact media will be sent. \"\"\"", "(messages contain the buttons, not the chat itself). You **cannot**", "button to request the user to create a poll. If", "the poll. If a poll is a quiz, there will", "phone on click. ``resize``, ``single_use`` and ``selective`` are documented in", "quiz or not. Otherwise, the user will be forced to", "are documented in `text`. When the user clicks this button,", "`MessageButton <telethon.tl.custom.messagebutton.MessageButton>`, so you might want to refer to that", "use methods line `Button.inline(...) <inline>` etc. You can use `inline`,", "_is_inline(button): \"\"\" Returns `True` if the button belongs to an", "`request_phone` and `request_poll` together to create a reply markup (replaces", "a button press and the user typing and sending exactly", "e.g. when sending a message or replying to events. When", "message with geo media will be sent. \"\"\" return cls(types.KeyboardButtonRequestGeoLocation(text),", "and be smaller if there are not many buttons. single_use", "the user clicks this button, a text message with the", "to the user asking whether they want to open the", "markups, e.g. when sending a message or replying to events.", "that the user clicked this button directly. When the user", "that is currently logged in (itself), although you may pass", "ellipsis (…) character as the 129. \"\"\" def __init__(self, button,", "have to select a different dialog to make the query.", "be used as said URL instead. You cannot detect that", "displayed URL unless the domain is trusted, and once confirmed", "\"\"\" def __init__(self, button, *, resize, single_use, selective): self.button =", "`url` is specified, it will default to `text`. Args: bot", "to `text`. Args: bot (`hints.EntityLike`): The bot that requires this", "to make inline queries. \"\"\" return types.KeyboardButtonSwitchInline(text, query, same_peer) @staticmethod", "you must manually use `client.get_input_entity() <telethon.client.users.UserMethods.get_input_entity>`. write_access (`bool`): Whether write", "required or not. This is `False` by default (read-only access).", "the user to create a poll. If `force_quiz` is `False`,", "will be shown only to specific users. It will target", "will be ignored. \"\"\" return types.ReplyKeyboardHide() @staticmethod def force_reply(): \"\"\"", "are passed as data, ``ValueError`` is raised. If you need", "import utils class Button: \"\"\" .. note:: This class is", "at most 142 characters. If more characters are given, Telegram", "click. ``resize``, ``single_use`` and ``selective`` are documented in `text`. When", ") @classmethod def text(cls, text, *, resize=None, single_use=None, selective=None): \"\"\"", "button was pressed. \"\"\" if not data: data = text.encode('utf-8')", "real data in a database and a reference to that", "authorize the user at the given URL. You should set", "with the same data that the button contained, so that", "access is required or not. This is `False` by default", "keyboard button to request the user to create a poll.", "is raised. If you need to store more than 64", "the data') return types.KeyboardButtonCallback(text, data) @staticmethod def switch_inline(text, query='', same_peer=False):", "self.resize = resize self.single_use = single_use self.selective = selective @staticmethod", "is forwarded. By default, the button text will be the", "``single_use`` and ``selective`` are documented in `text`. When the user", "new keyboard button to request the user's phone on click.", "*, bot=None, write_access=False, fwd_text=None): \"\"\" Creates a new inline button", "the one currently logged in, you must manually use `client.get_input_entity()", "the sender of the message you reply to. When the", "reply to. When the user clicks this button, a text", "message or replying to events. When you access `Message.buttons <telethon.tl.custom.message.Message.buttons>`", "class methods to create button instances instead making them yourself", "with the given text. Args: resize (`bool`): If present, the", "entire keyboard will be reconfigured to be resized and be", "Creates a new inline button to authorize the user at", "documented in `text`. When the user clicks this button, a", "default, this is the bot that is currently logged in", "one, the poll will be sent. \"\"\" return cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz),", "url=None, *, bot=None, write_access=False, fwd_text=None): \"\"\" Creates a new inline", "to the sender of the message you reply to. When", "create inline buttons (under the message). You can use `text`,", "currently logged in (itself), although you may pass a different", "If present, the entire keyboard will be reconfigured to be", "if the message is forwarded. By default, the button text", "and the user typing and sending exactly the same text", "access). fwd_text (`str`): The new text to show in the", "latest message with a reply markup will be the one", "user to create a poll. If `force_quiz` is `False`, the", "create one, the poll will be sent. \"\"\" return cls(types.KeyboardButtonRequestPoll(text,", "__init__(self, button, *, resize, single_use, selective): self.button = button self.resize", "def _is_inline(button): \"\"\" Returns `True` if the button belongs to", "<telethon.events.callbackquery.CallbackQuery>` will trigger with the same data that the button", "ready to make inline queries. \"\"\" return types.KeyboardButtonSwitchInline(text, query, same_peer)", "(`hints.EntityLike`): The bot that requires this authorization. By default, this", "When the user clicks this button, after a chat is", "bot than the one currently logged in, you must manually", "text to show in the button if the message is", "Creates a new keyboard button with the given text. Args:", "This class is used to **define** reply markups, e.g. when", "buttons. You should make use of the defined class methods", "vote and retract the vote, and the pol might be", "@staticmethod def switch_inline(text, query='', same_peer=False): \"\"\" Creates a new inline", "data=None): \"\"\" Creates a new inline button with some payload", "selective (`bool`): If present, the entire keyboard will be reconfigured", "new inline button with some payload data in it. If", "used as `data`. In any case `data` should be either", "if there are not many buttons. single_use (`bool`): If present,", "make the query. When the user clicks this button, after", "`@BotFather <https://t.me/BotFather>`_ using the ``/setdomain`` command. For more information about", "vote, and the pol might be multiple choice. ``resize``, ``single_use``", "not data: data = text.encode('utf-8') elif not isinstance(data, (bytes, bytearray,", "inline button to switch to inline query. If `query` is", "will be shown to the user asking whether they want", "a certain domain, see https://core.telegram.org/widgets/login. If no `url` is specified,", "`str`. Note that the given `data` must be less or", "When used, no other button should be present or it", "return types.KeyboardButtonUrl(text, url or text) @staticmethod def auth(text, url=None, *,", "the default text to be used when making the inline", "resize=resize, single_use=single_use, selective=selective) @classmethod def request_phone(cls, text, *, resize=None, single_use=None,", "make inline queries. \"\"\" return types.KeyboardButtonSwitchInline(text, query, same_peer) @staticmethod def", "set under the currently opened chat. Otherwise, the user will", "use a different bot than the one currently logged in,", "don't do ``Button(...)`` but instead use methods line `Button.inline(...) <inline>`", "``selective`` are documented in `text`. When the user clicks this", "once before it hides itself. selective (`bool`): If present, the", "button belongs to an inline keyboard. \"\"\" return isinstance(button, (", "request the user's location on click. ``resize``, ``single_use`` and ``selective``", "`data` must be less or equal to 64 bytes. If", "when making the inline query. If ``same_peer is True`` the", "pol might be multiple choice. ``resize``, ``single_use`` and ``selective`` are", "If `data` is omitted, the given `text` will be used", "want to open the displayed URL unless the domain is", "is True`` the inline query will directly be set under", "text(cls, text, *, resize=None, single_use=None, selective=None): \"\"\" Creates a new", "a reply markup will be the one shown to the", "the button. When the user clicks this button, `events.CallbackQuery <telethon.events.callbackquery.CallbackQuery>`", "be reconfigured to be \"selective\". The keyboard will be shown", "will directly be set under the currently opened chat. Otherwise,", "be resized and be smaller if there are not many", "If `query` is given, it will be the default text", "reference to that data inside the button. When the user", "of the reply with these. The latest message with a", "`url` and `auth` together to create inline buttons (under the", "entire keyboard will be reconfigured to be usable only once", "be sent. \"\"\" return cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz), resize=resize, single_use=single_use, selective=selective) @staticmethod", "under the currently opened chat. Otherwise, the user will have", "user will have to select a different dialog to make", "for the desired `bot` via `@BotFather <https://t.me/BotFather>`_ using the ``/setdomain``", "buttons, not the chat itself). You **cannot** mix the two", "equal to 64 bytes. If more than 64 bytes are", "Creates a new keyboard button to request the user's phone", "also configure the aspect of the reply with these. The", "the message with this markup. If used, no other button", "from .. import types from ... import utils class Button:", "For now, you cannot use ID or username for this", "there are not many buttons. single_use (`bool`): If present, the", "poll. If `force_quiz` is `False`, the user will be allowed", "to be on the same domain as the one configured", "inline query. If `query` is given, it will be the", "(replaces the user keyboard). You can also configure the aspect", "to that class instead. Helper class to allow defining ``reply_markup``", "one shown to the user (messages contain the buttons, not", "you can determine which button was pressed. \"\"\" if not", "return types.ReplyKeyboardHide() @staticmethod def force_reply(): \"\"\" Forces a reply to", "cls(types.KeyboardButtonRequestPhone(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_poll(cls, text, *, force_quiz=False,", "the vote, and the pol might be multiple choice. ``resize``,", "may be at most 142 characters. If more characters are", "a message or replying to events. When you access `Message.buttons", "selective=None): \"\"\" Creates a new keyboard button to request the", "the bot that is currently logged in (itself), although you", "buttons together, and it will error if you try to", "<telethon.tl.custom.messagebutton.MessageButton>`, so you might want to refer to that class", "the user will have to select a different dialog to", "types from ... import utils class Button: \"\"\" .. note::", "inline buttons (under the message). You can use `text`, `request_location`,", "`False` by default (read-only access). fwd_text (`str`): The new text", "`text`, `request_location`, `request_phone` and `request_poll` together to create a reply", "same data that the button contained, so that you can", "want to share their phone with the bot, and if", "the URL will open in their device. \"\"\" return types.KeyboardButtonUrl(text,", "selective=selective) @staticmethod def clear(): \"\"\" Clears all keyboard buttons after", "user will be allowed to choose whether they want their", "def switch_inline(text, query='', same_peer=False): \"\"\" Creates a new inline button", "button to authorize the user at the given URL. You", "by default (read-only access). fwd_text (`str`): The new text to", "def __init__(self, button, *, resize, single_use, selective): self.button = button", "When the user clicks this button, a screen letting the", "and add the ellipsis (…) character as the 129. \"\"\"", "this authorization. By default, this is the bot that is", "user clicks this button, `events.CallbackQuery <telethon.events.callbackquery.CallbackQuery>` will trigger with the", "text will be the same. When the user clicks this", "itself). You **cannot** mix the two type of buttons together,", "many buttons. single_use (`bool`): If present, the entire keyboard will", "manually use `client.get_input_entity() <telethon.client.users.UserMethods.get_input_entity>`. write_access (`bool`): Whether write access is", "sent. \"\"\" return cls(types.KeyboardButtonRequestPhone(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_poll(cls,", "text message with the same text as the button will", "types.KeyboardButtonCallback(text, data) @staticmethod def switch_inline(text, query='', same_peer=False): \"\"\" Creates a", "the user clicks this button, after a chat is selected,", "on the same domain as the one configured for the", "the given `text` will be used as `data`. In any", "defining ``reply_markup`` when sending a message with inline or keyboard", ")) @staticmethod def inline(text, data=None): \"\"\" Creates a new inline", "should make use of the defined class methods to create", "`client.get_input_entity() <telethon.client.users.UserMethods.get_input_entity>`. write_access (`bool`): Whether write access is required or", "to request the user's location on click. ``resize``, ``single_use`` and", "Creates a new inline button with some payload data in", "certain domain, see https://core.telegram.org/widgets/login. If no `url` is specified, it", "the message you reply to. When the user clicks this", "is currently logged in (itself), although you may pass a", "you access `Message.buttons <telethon.tl.custom.message.Message.buttons>` they are actually `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`, so", "the desired `bot` via `@BotFather <https://t.me/BotFather>`_ using the ``/setdomain`` command.", "is omitted, the given `text` will be used as `data`.", "data, ``ValueError`` is raised. If you need to store more", "def request_location(cls, text, *, resize=None, single_use=None, selective=None): \"\"\" Creates a", "(…) character as the 129. \"\"\" def __init__(self, button, *,", "input field will be filled with the username of your", "although you may pass a different input peer. .. note::", "\"\"\" return types.KeyboardButtonUrl(text, url or text) @staticmethod def auth(text, url=None,", "at the given URL. You should set the `url` to", "(read-only access). fwd_text (`str`): The new text to show in", "no `url` is specified, it will default to `text`. Args:", "\"selective\". The keyboard will be shown only to specific users.", "login via Telegram to a certain domain, see https://core.telegram.org/widgets/login. If", "selective=selective) @classmethod def request_poll(cls, text, *, force_quiz=False, resize=None, single_use=None, selective=None):", "want to login to the specified domain. \"\"\" return types.InputKeyboardButtonUrlAuth(", "trigger with the same data that the button contained, so", "not. Otherwise, the user will be forced to create a", "bot that requires this authorization. By default, this is the", "choose whether they want their poll to be a quiz", "reply with these. The latest message with a reply markup", "in the button if the message is forwarded. By default,", "button to open the desired URL on click. If no", "with a reply markup will be the one shown to", "configured for the desired `bot` via `@BotFather <https://t.me/BotFather>`_ using the", "a new inline button with some payload data in it.", "single_use (`bool`): If present, the entire keyboard will be reconfigured", "that the given `data` must be less or equal to", "characters and add the ellipsis (…) character as the 129.", "Note that the given `data` must be less or equal", "one configured for the desired `bot` via `@BotFather <https://t.me/BotFather>`_ using", "in a database and a reference to that data inside", "ID or username for this argument. If you want to", "keyboard buttons after sending a message with this markup. When", "clicks this button, a confirmation box will be shown to", "will be reconfigured to be \"selective\". The keyboard will be", "bot, and if confirmed a message with contact media will", "@staticmethod def url(text, url=None): \"\"\" Creates a new inline button", "only once before it hides itself. selective (`bool`): If present,", "handled with `events.NewMessage <telethon.events.newmessage.NewMessage>`. You cannot distinguish between a button", "after a chat is selected, their input field will be", "be on the same domain as the one configured for", "inline(text, data=None): \"\"\" Creates a new inline button with some", "In any case `data` should be either `bytes` or `str`.", "@staticmethod def force_reply(): \"\"\" Forces a reply to the message", "``/setdomain`` command. For more information about letting the user login", "``reply_markup`` when sending a message with inline or keyboard buttons.", "ValueError('Too many bytes for the data') return types.KeyboardButtonCallback(text, data) @staticmethod", "@staticmethod def auth(text, url=None, *, bot=None, write_access=False, fwd_text=None): \"\"\" Creates", "Creates a new inline button to switch to inline query.", "will be the one shown to the user (messages contain", "reply to the message with this markup. If used, no", "two type of buttons together, and it will error if", "directly be set under the currently opened chat. Otherwise, the", "open the displayed URL unless the domain is trusted, and", "retracted. Otherwise, users can vote and retract the vote, and", "as `data`. In any case `data` should be either `bytes`", "is `False` by default (read-only access). fwd_text (`str`): The new", "is given, it will be the default text to be", "the given text. Args: resize (`bool`): If present, the entire", "to be resized and be smaller if there are not", "be reconfigured to be resized and be smaller if there", "user clicks this button, a text message with the same", "with some payload data in it. If `data` is omitted,", "the `text` will be used as said URL instead. You", "not the chat itself). You **cannot** mix the two type", "You cannot detect that the user clicked this button directly.", "be used when making the inline query. If ``same_peer is", "domain is trusted, and once confirmed the URL will open", "bot=utils.get_input_user(bot or types.InputUserSelf()), request_write_access=write_access, fwd_text=fwd_text ) @classmethod def text(cls, text,", "command. For more information about letting the user login via", "with geo media will be sent. \"\"\" return cls(types.KeyboardButtonRequestGeoLocation(text), resize=resize,", "they want their poll to be a quiz or not.", "be retracted. Otherwise, users can vote and retract the vote,", "opened chat. Otherwise, the user will have to select a", "and a reference to that data inside the button. When", "You can use `text`, `request_location`, `request_phone` and `request_poll` together to", "the user login via Telegram to a certain domain, see", "<telethon.tl.custom.message.Message.buttons>` they are actually `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`, so you might want", "and if confirmed a message with contact media will be", "auth(text, url=None, *, bot=None, write_access=False, fwd_text=None): \"\"\" Creates a new", "currently opened chat. Otherwise, the user will have to select", "a database and a reference to that data inside the", "be shown, and if they do create one, the poll", "can use `inline`, `switch_inline`, `url` and `auth` together to create", "keyboard button with the given text. Args: resize (`bool`): If", "unless the domain is trusted, and once confirmed the URL", "class to allow defining ``reply_markup`` when sending a message with", "whether they want to open the displayed URL unless the", "show in the button if the message is forwarded. By", "to be a quiz or not. Otherwise, the user will", "use `inline`, `switch_inline`, `url` and `auth` together to create inline", "be forced to create a quiz when creating the poll.", "to the message with this markup. If used, no other", "the query text, ready to make inline queries. \"\"\" return", "If a poll is a quiz, there will be only", "note:: This class is used to **define** reply markups, e.g.", "logged in, you must manually use `client.get_input_entity() <telethon.client.users.UserMethods.get_input_entity>`. write_access (`bool`):", "the bot, and if confirmed a message with geo media", "you may pass a different input peer. .. note:: For", "make use of the defined class methods to create button", "button should be present or it will be ignored. \"\"\"", "user clicks this button, after a chat is selected, their", "clicked this button directly. When the user clicks this button,", "store more than 64 bytes, consider saving the real data", "the user clicks this button, `events.CallbackQuery <telethon.events.callbackquery.CallbackQuery>` will trigger with", "message with inline or keyboard buttons. You should make use", "location on click. ``resize``, ``single_use`` and ``selective`` are documented in", "`False`, the user will be allowed to choose whether they", "target users that are @mentioned in the text of the", "When the user clicks this button, `events.CallbackQuery <telethon.events.callbackquery.CallbackQuery>` will trigger", "`query` is given, it will be the default text to", "of your bot followed by the query text, ready to", "\"\"\" Creates a new inline button to open the desired", "types.ReplyKeyboardHide() @staticmethod def force_reply(): \"\"\" Forces a reply to the", "to create a quiz when creating the poll. If a", "given text. Args: resize (`bool`): If present, the entire keyboard", "\"\"\" Creates a new keyboard button to request the user's", "their poll to be a quiz or not. Otherwise, the", "payload data in it. If `data` is omitted, the given", "it will be ignored. \"\"\" return types.ReplyKeyboardHide() @staticmethod def force_reply():", "Returns `True` if the button belongs to an inline keyboard.", "button press and the user typing and sending exactly the", "request the user to create a poll. If `force_quiz` is", "detect that the user clicked this button directly. When the", "can also configure the aspect of the reply with these.", "bytes for the data') return types.KeyboardButtonCallback(text, data) @staticmethod def switch_inline(text,", "with inline or keyboard buttons. You should make use of", "letting the user create a poll will be shown, and", "You can also configure the aspect of the reply with", "64 bytes are passed as data, ``ValueError`` is raised. If", "the user's phone on click. ``resize``, ``single_use`` and ``selective`` are", "their device. \"\"\" return types.KeyboardButtonUrl(text, url or text) @staticmethod def", "default to `text`. Args: bot (`hints.EntityLike`): The bot that requires", "If used, no other button should be present or it", "might want to refer to that class instead. Helper class", "characters. If more characters are given, Telegram will cut the", "confirmed a message with geo media will be sent. \"\"\"", "you want to use a different bot than the one", "shown to the user asking whether they want to open", "If you want to use a different bot than the", "to be usable only once before it hides itself. selective", "to use a different bot than the one currently logged", "will cut the text to 128 characters and add the", "return types.KeyboardButtonCallback(text, data) @staticmethod def switch_inline(text, query='', same_peer=False): \"\"\" Creates", "return cls(types.KeyboardButtonRequestGeoLocation(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_phone(cls, text, *,", "selective=selective) @classmethod def request_location(cls, text, *, resize=None, single_use=None, selective=None): \"\"\"", "it will be the default text to be used when", "Telegram to a certain domain, see https://core.telegram.org/widgets/login. If no `url`", "with contact media will be sent. \"\"\" return cls(types.KeyboardButtonRequestPhone(text), resize=resize,", "configure the aspect of the reply with these. The latest", "not isinstance(data, (bytes, bytearray, memoryview)): data = str(data).encode('utf-8') if len(data)", "or not. This is `False` by default (read-only access). fwd_text", "buttons after sending a message with this markup. When used,", "hides itself. selective (`bool`): If present, the entire keyboard will", "the user clicks this button, a screen letting the user", "\"\"\" Clears all keyboard buttons after sending a message with", "together to create inline buttons (under the message). You can", "reply markup (replaces the user keyboard). You can also configure", "resize, single_use, selective): self.button = button self.resize = resize self.single_use", "to make the query. When the user clicks this button,", "note:: For now, you cannot use ID or username for", "or `str`. Note that the given `data` must be less", "error if you try to do so. The text for", "64 bytes. If more than 64 bytes are passed as", "contain the buttons, not the chat itself). You **cannot** mix", "will trigger with the same data that the button contained,", "if len(data) > 64: raise ValueError('Too many bytes for the", "an inline keyboard. \"\"\" return isinstance(button, ( types.KeyboardButtonCallback, types.KeyboardButtonSwitchInline, types.KeyboardButtonUrl,", "contained, so that you can determine which button was pressed.", "types.InputKeyboardButtonUrlAuth )) @staticmethod def inline(text, data=None): \"\"\" Creates a new", "to be used when making the inline query. If ``same_peer", "url(text, url=None): \"\"\" Creates a new inline button to open", "to share their location with the bot, and if confirmed", "a message with contact media will be sent. \"\"\" return", "*, resize, single_use, selective): self.button = button self.resize = resize", "as the button will be sent, and can be handled", "it. If `data` is omitted, the given `text` will be", "share their location with the bot, and if confirmed a", "`force_quiz` is `False`, the user will be allowed to choose", "data in it. If `data` is omitted, the given `text`", "the user will be allowed to choose whether they want", "button, *, resize, single_use, selective): self.button = button self.resize =", "bytes are passed as data, ``ValueError`` is raised. If you", "a quiz or not. Otherwise, the user will be forced", "Clears all keyboard buttons after sending a message with this", "``same_peer is True`` the inline query will directly be set", "text for all buttons may be at most 142 characters.", "case `data` should be either `bytes` or `str`. Note that", "than 64 bytes are passed as data, ``ValueError`` is raised.", "64 bytes, consider saving the real data in a database", "data = str(data).encode('utf-8') if len(data) > 64: raise ValueError('Too many", "used as said URL instead. You cannot detect that the", "text.encode('utf-8') elif not isinstance(data, (bytes, bytearray, memoryview)): data = str(data).encode('utf-8')", "or text) @staticmethod def auth(text, url=None, *, bot=None, write_access=False, fwd_text=None):", "class is used to **define** reply markups, e.g. when sending", "URL unless the domain is trusted, and once confirmed the", "bot that is currently logged in (itself), although you may", "to login to the specified domain. \"\"\" return types.InputKeyboardButtonUrlAuth( text=text,", "share their phone with the bot, and if confirmed a", "new inline button to authorize the user at the given", "any case `data` should be either `bytes` or `str`. Note", "input peer. .. note:: For now, you cannot use ID", "the user asking whether they want to open the displayed", "own. \"\"\" return cls(types.KeyboardButton(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_location(cls,", "authorization. By default, this is the bot that is currently", "present, the entire keyboard will be reconfigured to be \"selective\".", "creating the poll. If a poll is a quiz, there", "be handled with `events.NewMessage <telethon.events.newmessage.NewMessage>`. You cannot distinguish between a", "button to switch to inline query. If `query` is given,", "use `client.get_input_entity() <telethon.client.users.UserMethods.get_input_entity>`. write_access (`bool`): Whether write access is required", "will be used as `data`. In any case `data` should", "to be \"selective\". The keyboard will be shown only to", "Creates a new keyboard button to request the user to", "they want to open the displayed URL unless the domain", "Whether write access is required or not. This is `False`", "markup will be the one shown to the user (messages", "in (itself), although you may pass a different input peer.", "`switch_inline`, `url` and `auth` together to create inline buttons (under", "to show in the button if the message is forwarded.", "to the user asking whether they want to share their", "device. \"\"\" return types.KeyboardButtonUrl(text, url or text) @staticmethod def auth(text,", "url or text) @staticmethod def auth(text, url=None, *, bot=None, write_access=False,", "text, bot=utils.get_input_user(bot or types.InputUserSelf()), request_write_access=write_access, fwd_text=fwd_text ) @classmethod def text(cls,", "(i.e. don't do ``Button(...)`` but instead use methods line `Button.inline(...)", "\"\"\" return cls(types.KeyboardButton(text), resize=resize, single_use=single_use, selective=selective) @classmethod def request_location(cls, text,", "selective=None): \"\"\" Creates a new keyboard button with the given", "to specific users. It will target users that are @mentioned", "resize=resize, single_use=single_use, selective=selective) @staticmethod def clear(): \"\"\" Clears all keyboard", "for all buttons may be at most 142 characters. If", "want to share their location with the bot, and if", "inline query. If ``same_peer is True`` the inline query will", "the poll will be sent. \"\"\" return cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz), resize=resize,", "`request_location`, `request_phone` and `request_poll` together to create a reply markup", "the same data that the button contained, so that you", "once confirmed the URL will open in their device. \"\"\"", "You cannot distinguish between a button press and the user", "text of the message or to the sender of the", "clear(): \"\"\" Clears all keyboard buttons after sending a message", "exactly the same text on their own. \"\"\" return cls(types.KeyboardButton(text),", "def force_reply(): \"\"\" Forces a reply to the message with", "when creating the poll. If a poll is a quiz,", "for the data') return types.KeyboardButtonCallback(text, data) @staticmethod def switch_inline(text, query='',", "your bot followed by the query text, ready to make", "line `Button.inline(...) <inline>` etc. You can use `inline`, `switch_inline`, `url`", "the button if the message is forwarded. By default, the", "(`bool`): If present, the entire keyboard will be reconfigured to", "and can be handled with `events.NewMessage <telethon.events.newmessage.NewMessage>`. You cannot distinguish", "may pass a different input peer. .. note:: For now,", "you need to store more than 64 bytes, consider saving", "query. If ``same_peer is True`` the inline query will directly", "the displayed URL unless the domain is trusted, and once", "present, the entire keyboard will be reconfigured to be usable", "query. If `query` is given, it will be the default", "the text of the message or to the sender of", "be allowed to choose whether they want their poll to", "If `force_quiz` is `False`, the user will be allowed to", "these. The latest message with a reply markup will be", "You **cannot** mix the two type of buttons together, and", "the one configured for the desired `bot` via `@BotFather <https://t.me/BotFather>`_", "should be present or it will be ignored. \"\"\" return", "can determine which button was pressed. \"\"\" if not data:", "**cannot** mix the two type of buttons together, and it", "be multiple choice. ``resize``, ``single_use`` and ``selective`` are documented in", "or keyboard buttons. You should make use of the defined", "should be either `bytes` or `str`. Note that the given", "asking whether they want to share their location with the", "refer to that class instead. Helper class to allow defining", "allow defining ``reply_markup`` when sending a message with inline or", "different bot than the one currently logged in, you must", "are @mentioned in the text of the message or to", "open the desired URL on click. If no `url` is", "when sending a message with inline or keyboard buttons. You", "to open the displayed URL unless the domain is trusted,", "The keyboard will be shown only to specific users. It", "the user will be forced to create a quiz when", "with this markup. When used, no other button should be", "the inline query. If ``same_peer is True`` the inline query", "Args: bot (`hints.EntityLike`): The bot that requires this authorization. By", "logged in (itself), although you may pass a different input", "button, `events.CallbackQuery <telethon.events.callbackquery.CallbackQuery>` will trigger with the same data that", "of the message or to the sender of the message", "if they do create one, the poll will be sent.", ".. note:: For now, you cannot use ID or username" ]
[ "dict_to_json[key] = dict_0[key] + dict_1[key] + dict_2[key] + dict_3[key] #0seg,f_step,f_stop", "+ arr[1]) dict_2 = readJson(jsonPathTemp + arr[2]) dict_3 = readJson(jsonPathTemp", "os.listdir(jsonPathTemp) arr.sort() print(arr) dict_to_json = {} dict_0 = readJson(jsonPathTemp +", "dict_to_json = {} dict_0 = readJson(jsonPathTemp + arr[0]) dict_1 =", "keys: dict_to_json[key] = dict_0[key] + dict_1[key] + dict_2[key] + dict_3[key]", "= os.listdir(jsonPathTemp) arr.sort() print(arr) dict_to_json = {} dict_0 = readJson(jsonPathTemp", "# ============================================================================= jsonPathTemp = jsonPath+\"temp/\" arr = os.listdir(jsonPathTemp) arr.sort() print(arr)", "+ arr[2]) dict_3 = readJson(jsonPathTemp + arr[3]) keys = [name", "join json files @author: SERGI \"\"\" import json import sys", "return json.load(file) def writeJson(path, dicc): with open(path, \"w\") as file:", "= readJson(jsonPathTemp + arr[3]) keys = [name for name in", "[seg, step, stop] print(\"Escribiendo json: \", jsonPath+arr[0], flush=True) writeJson(jsonPath+arr[0], dict_to_json)", "in keys: dict_to_json[key] = dict_0[key] + dict_1[key] + dict_2[key] +", "-*- coding: utf-8 -*- \"\"\" Created on Tue Jul 7", "dict_0[key] + dict_1[key] + dict_2[key] + dict_3[key] #0seg,f_step,f_stop seg =", "arr[1]) dict_2 = readJson(jsonPathTemp + arr[2]) dict_3 = readJson(jsonPathTemp +", "= dict_0[key] + dict_1[key] + dict_2[key] + dict_3[key] #0seg,f_step,f_stop seg", "files @author: SERGI \"\"\" import json import sys import os", "# -*- coding: utf-8 -*- \"\"\" Created on Tue Jul", "python\", flush=True) jsonPath = str(sys.argv[1]) # ============================================================================= # jsonPath =", "dict_0['0seg,f_step,f_stop'][0] step = dict_0['0seg,f_step,f_stop'][1] stop = dict_3['0seg,f_step,f_stop'][2] dict_to_json['0seg,f_step,f_stop'] = [seg,", "step, stop] print(\"Escribiendo json: \", jsonPath+arr[0], flush=True) writeJson(jsonPath+arr[0], dict_to_json) print(\"finish\",", "readJson(jsonPathTemp + arr[1]) dict_2 = readJson(jsonPathTemp + arr[2]) dict_3 =", "#0seg,f_step,f_stop seg = dict_0['0seg,f_step,f_stop'][0] step = dict_0['0seg,f_step,f_stop'][1] stop = dict_3['0seg,f_step,f_stop'][2]", "jsonPath = str(sys.argv[1]) # ============================================================================= # jsonPath = \"../eclipse-workspace/prueba/target/json/\" #", "open(path, \"w\") as file: json.dump(dicc, file) if __name__ == \"__main__\":", "coding: utf-8 -*- \"\"\" Created on Tue Jul 7 20:14:22", "Jul 7 20:14:22 2020 Simple script to join json files", "readJson(jsonPathTemp + arr[2]) dict_3 = readJson(jsonPathTemp + arr[3]) keys =", "for name in dict_0.keys() if \"0\" not in name] for", "\"__main__\": print(\"hello from python\", flush=True) jsonPath = str(sys.argv[1]) # =============================================================================", "= \"../eclipse-workspace/prueba/target/json/\" # ============================================================================= jsonPathTemp = jsonPath+\"temp/\" arr = os.listdir(jsonPathTemp)", "name] for key in keys: dict_to_json[key] = dict_0[key] + dict_1[key]", "stop] print(\"Escribiendo json: \", jsonPath+arr[0], flush=True) writeJson(jsonPath+arr[0], dict_to_json) print(\"finish\", flush=True)", "dict_3 = readJson(jsonPathTemp + arr[3]) keys = [name for name", "\"r\") as file: return json.load(file) def writeJson(path, dicc): with open(path,", "{} dict_0 = readJson(jsonPathTemp + arr[0]) dict_1 = readJson(jsonPathTemp +", "utf-8 -*- \"\"\" Created on Tue Jul 7 20:14:22 2020", "= str(sys.argv[1]) # ============================================================================= # jsonPath = \"../eclipse-workspace/prueba/target/json/\" # =============================================================================", "= [seg, step, stop] print(\"Escribiendo json: \", jsonPath+arr[0], flush=True) writeJson(jsonPath+arr[0],", "flush=True) jsonPath = str(sys.argv[1]) # ============================================================================= # jsonPath = \"../eclipse-workspace/prueba/target/json/\"", "not in name] for key in keys: dict_to_json[key] = dict_0[key]", "SERGI \"\"\" import json import sys import os def readJson(path):", "readJson(jsonPathTemp + arr[0]) dict_1 = readJson(jsonPathTemp + arr[1]) dict_2 =", "7 20:14:22 2020 Simple script to join json files @author:", "step = dict_0['0seg,f_step,f_stop'][1] stop = dict_3['0seg,f_step,f_stop'][2] dict_to_json['0seg,f_step,f_stop'] = [seg, step,", "dict_0['0seg,f_step,f_stop'][1] stop = dict_3['0seg,f_step,f_stop'][2] dict_to_json['0seg,f_step,f_stop'] = [seg, step, stop] print(\"Escribiendo", "dict_2 = readJson(jsonPathTemp + arr[2]) dict_3 = readJson(jsonPathTemp + arr[3])", "import sys import os def readJson(path): with open(path, \"r\") as", "in name] for key in keys: dict_to_json[key] = dict_0[key] +", "-*- \"\"\" Created on Tue Jul 7 20:14:22 2020 Simple", "if \"0\" not in name] for key in keys: dict_to_json[key]", "\"\"\" import json import sys import os def readJson(path): with", "to join json files @author: SERGI \"\"\" import json import", "arr[2]) dict_3 = readJson(jsonPathTemp + arr[3]) keys = [name for", "def readJson(path): with open(path, \"r\") as file: return json.load(file) def", "on Tue Jul 7 20:14:22 2020 Simple script to join", "print(\"hello from python\", flush=True) jsonPath = str(sys.argv[1]) # ============================================================================= #", "+ dict_2[key] + dict_3[key] #0seg,f_step,f_stop seg = dict_0['0seg,f_step,f_stop'][0] step =", "dict_3['0seg,f_step,f_stop'][2] dict_to_json['0seg,f_step,f_stop'] = [seg, step, stop] print(\"Escribiendo json: \", jsonPath+arr[0],", "with open(path, \"r\") as file: return json.load(file) def writeJson(path, dicc):", "file: return json.load(file) def writeJson(path, dicc): with open(path, \"w\") as", "as file: json.dump(dicc, file) if __name__ == \"__main__\": print(\"hello from", "dict_1 = readJson(jsonPathTemp + arr[1]) dict_2 = readJson(jsonPathTemp + arr[2])", "dict_to_json['0seg,f_step,f_stop'] = [seg, step, stop] print(\"Escribiendo json: \", jsonPath+arr[0], flush=True)", "dict_2[key] + dict_3[key] #0seg,f_step,f_stop seg = dict_0['0seg,f_step,f_stop'][0] step = dict_0['0seg,f_step,f_stop'][1]", "json import sys import os def readJson(path): with open(path, \"r\")", "= readJson(jsonPathTemp + arr[1]) dict_2 = readJson(jsonPathTemp + arr[2]) dict_3", "stop = dict_3['0seg,f_step,f_stop'][2] dict_to_json['0seg,f_step,f_stop'] = [seg, step, stop] print(\"Escribiendo json:", "with open(path, \"w\") as file: json.dump(dicc, file) if __name__ ==", "Tue Jul 7 20:14:22 2020 Simple script to join json", "in dict_0.keys() if \"0\" not in name] for key in", "writeJson(path, dicc): with open(path, \"w\") as file: json.dump(dicc, file) if", "= dict_0['0seg,f_step,f_stop'][0] step = dict_0['0seg,f_step,f_stop'][1] stop = dict_3['0seg,f_step,f_stop'][2] dict_to_json['0seg,f_step,f_stop'] =", "= readJson(jsonPathTemp + arr[2]) dict_3 = readJson(jsonPathTemp + arr[3]) keys", "+ dict_1[key] + dict_2[key] + dict_3[key] #0seg,f_step,f_stop seg = dict_0['0seg,f_step,f_stop'][0]", "= dict_0['0seg,f_step,f_stop'][1] stop = dict_3['0seg,f_step,f_stop'][2] dict_to_json['0seg,f_step,f_stop'] = [seg, step, stop]", "as file: return json.load(file) def writeJson(path, dicc): with open(path, \"w\")", "dict_0.keys() if \"0\" not in name] for key in keys:", "key in keys: dict_to_json[key] = dict_0[key] + dict_1[key] + dict_2[key]", "readJson(path): with open(path, \"r\") as file: return json.load(file) def writeJson(path,", "============================================================================= jsonPathTemp = jsonPath+\"temp/\" arr = os.listdir(jsonPathTemp) arr.sort() print(arr) dict_to_json", "\"\"\" Created on Tue Jul 7 20:14:22 2020 Simple script", "+ arr[0]) dict_1 = readJson(jsonPathTemp + arr[1]) dict_2 = readJson(jsonPathTemp", "open(path, \"r\") as file: return json.load(file) def writeJson(path, dicc): with", "+ dict_3[key] #0seg,f_step,f_stop seg = dict_0['0seg,f_step,f_stop'][0] step = dict_0['0seg,f_step,f_stop'][1] stop", "+ arr[3]) keys = [name for name in dict_0.keys() if", "json.dump(dicc, file) if __name__ == \"__main__\": print(\"hello from python\", flush=True)", "= readJson(jsonPathTemp + arr[0]) dict_1 = readJson(jsonPathTemp + arr[1]) dict_2", "dict_0 = readJson(jsonPathTemp + arr[0]) dict_1 = readJson(jsonPathTemp + arr[1])", "def writeJson(path, dicc): with open(path, \"w\") as file: json.dump(dicc, file)", "__name__ == \"__main__\": print(\"hello from python\", flush=True) jsonPath = str(sys.argv[1])", "import json import sys import os def readJson(path): with open(path,", "keys = [name for name in dict_0.keys() if \"0\" not", "# ============================================================================= # jsonPath = \"../eclipse-workspace/prueba/target/json/\" # ============================================================================= jsonPathTemp =", "script to join json files @author: SERGI \"\"\" import json", "@author: SERGI \"\"\" import json import sys import os def", "import os def readJson(path): with open(path, \"r\") as file: return", "readJson(jsonPathTemp + arr[3]) keys = [name for name in dict_0.keys()", "json.load(file) def writeJson(path, dicc): with open(path, \"w\") as file: json.dump(dicc,", "============================================================================= # jsonPath = \"../eclipse-workspace/prueba/target/json/\" # ============================================================================= jsonPathTemp = jsonPath+\"temp/\"", "# jsonPath = \"../eclipse-workspace/prueba/target/json/\" # ============================================================================= jsonPathTemp = jsonPath+\"temp/\" arr", "sys import os def readJson(path): with open(path, \"r\") as file:", "2020 Simple script to join json files @author: SERGI \"\"\"", "= dict_3['0seg,f_step,f_stop'][2] dict_to_json['0seg,f_step,f_stop'] = [seg, step, stop] print(\"Escribiendo json: \",", "= [name for name in dict_0.keys() if \"0\" not in", "json files @author: SERGI \"\"\" import json import sys import", "jsonPath = \"../eclipse-workspace/prueba/target/json/\" # ============================================================================= jsonPathTemp = jsonPath+\"temp/\" arr =", "file: json.dump(dicc, file) if __name__ == \"__main__\": print(\"hello from python\",", "== \"__main__\": print(\"hello from python\", flush=True) jsonPath = str(sys.argv[1]) #", "for key in keys: dict_to_json[key] = dict_0[key] + dict_1[key] +", "print(arr) dict_to_json = {} dict_0 = readJson(jsonPathTemp + arr[0]) dict_1", "arr = os.listdir(jsonPathTemp) arr.sort() print(arr) dict_to_json = {} dict_0 =", "[name for name in dict_0.keys() if \"0\" not in name]", "seg = dict_0['0seg,f_step,f_stop'][0] step = dict_0['0seg,f_step,f_stop'][1] stop = dict_3['0seg,f_step,f_stop'][2] dict_to_json['0seg,f_step,f_stop']", "str(sys.argv[1]) # ============================================================================= # jsonPath = \"../eclipse-workspace/prueba/target/json/\" # ============================================================================= jsonPathTemp", "arr.sort() print(arr) dict_to_json = {} dict_0 = readJson(jsonPathTemp + arr[0])", "20:14:22 2020 Simple script to join json files @author: SERGI", "Simple script to join json files @author: SERGI \"\"\" import", "jsonPath+\"temp/\" arr = os.listdir(jsonPathTemp) arr.sort() print(arr) dict_to_json = {} dict_0", "arr[0]) dict_1 = readJson(jsonPathTemp + arr[1]) dict_2 = readJson(jsonPathTemp +", "dict_1[key] + dict_2[key] + dict_3[key] #0seg,f_step,f_stop seg = dict_0['0seg,f_step,f_stop'][0] step", "dict_3[key] #0seg,f_step,f_stop seg = dict_0['0seg,f_step,f_stop'][0] step = dict_0['0seg,f_step,f_stop'][1] stop =", "os def readJson(path): with open(path, \"r\") as file: return json.load(file)", "\"0\" not in name] for key in keys: dict_to_json[key] =", "dicc): with open(path, \"w\") as file: json.dump(dicc, file) if __name__", "\"w\") as file: json.dump(dicc, file) if __name__ == \"__main__\": print(\"hello", "= {} dict_0 = readJson(jsonPathTemp + arr[0]) dict_1 = readJson(jsonPathTemp", "= jsonPath+\"temp/\" arr = os.listdir(jsonPathTemp) arr.sort() print(arr) dict_to_json = {}", "arr[3]) keys = [name for name in dict_0.keys() if \"0\"", "\"../eclipse-workspace/prueba/target/json/\" # ============================================================================= jsonPathTemp = jsonPath+\"temp/\" arr = os.listdir(jsonPathTemp) arr.sort()", "jsonPathTemp = jsonPath+\"temp/\" arr = os.listdir(jsonPathTemp) arr.sort() print(arr) dict_to_json =", "from python\", flush=True) jsonPath = str(sys.argv[1]) # ============================================================================= # jsonPath", "if __name__ == \"__main__\": print(\"hello from python\", flush=True) jsonPath =", "name in dict_0.keys() if \"0\" not in name] for key", "Created on Tue Jul 7 20:14:22 2020 Simple script to", "file) if __name__ == \"__main__\": print(\"hello from python\", flush=True) jsonPath" ]
[ "spaces allowed\", max_length=50, unique=True, validators=[ grandchallenge.challenges.models.validate_nounderscores, django.core.validators.RegexValidator( re.compile(\"^[-a-zA-Z0-9_]+\\\\Z\"), \"Enter a", "used in url, specific css, files etc. No spaces allowed\",", "[ (\"challenges\", \"0022_auto_20200121_1639\"), ] operations = [ migrations.AlterField( model_name=\"challenge\", name=\"short_name\",", "name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used in url, specific css, files", "grandchallenge.challenges.models.validate_nounderscores, django.core.validators.RegexValidator( re.compile(\"^[-a-zA-Z0-9_]+\\\\Z\"), \"Enter a valid “slug” consisting of letters,", "django.db import migrations import grandchallenge.challenges.models class Migration(migrations.Migration): dependencies = [", "grandchallenge.challenges.models.validate_short_name, ], ), ), migrations.AlterField( model_name=\"externalchallenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name", "django.core.validators.RegexValidator( re.compile(\"^[-a-zA-Z0-9_]+\\\\Z\"), \"Enter a valid “slug” consisting of letters, numbers,", "[ migrations.AlterField( model_name=\"challenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used in url,", "= [ migrations.AlterField( model_name=\"challenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used in", "by Django 3.0.2 on 2020-01-23 11:02 import re import django.contrib.postgres.fields.citext", "), grandchallenge.challenges.models.validate_short_name, ], ), ), migrations.AlterField( model_name=\"externalchallenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short", "), ), migrations.AlterField( model_name=\"externalchallenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used in", "re.compile(\"^[-a-zA-Z0-9_]+\\\\Z\"), \"Enter a valid “slug” consisting of letters, numbers, underscores", "11:02 import re import django.contrib.postgres.fields.citext import django.core.validators from django.db import", "(\"challenges\", \"0022_auto_20200121_1639\"), ] operations = [ migrations.AlterField( model_name=\"challenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField(", "\"Enter a valid “slug” consisting of letters, numbers, underscores or", "Generated by Django 3.0.2 on 2020-01-23 11:02 import re import", "\"0022_auto_20200121_1639\"), ] operations = [ migrations.AlterField( model_name=\"challenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short", "in url, specific css, files etc. No spaces allowed\", max_length=50,", "max_length=50, unique=True, validators=[ grandchallenge.challenges.models.validate_nounderscores, django.core.validators.RegexValidator( re.compile(\"^[-a-zA-Z0-9_]+\\\\Z\"), \"Enter a valid “slug”", "validators=[ grandchallenge.challenges.models.validate_nounderscores, django.core.validators.RegexValidator( re.compile(\"^[-a-zA-Z0-9_]+\\\\Z\"), \"Enter a valid “slug” consisting of", "consisting of letters, numbers, underscores or hyphens.\", \"invalid\", ), grandchallenge.challenges.models.validate_short_name,", "No spaces allowed\", max_length=50, unique=True, validators=[ grandchallenge.challenges.models.validate_nounderscores, django.core.validators.RegexValidator( re.compile(\"^[-a-zA-Z0-9_]+\\\\Z\"), \"Enter", "import grandchallenge.challenges.models class Migration(migrations.Migration): dependencies = [ (\"challenges\", \"0022_auto_20200121_1639\"), ]", "of letters, numbers, underscores or hyphens.\", \"invalid\", ), grandchallenge.challenges.models.validate_short_name, ],", "import django.core.validators from django.db import migrations import grandchallenge.challenges.models class Migration(migrations.Migration):", "grandchallenge.challenges.models class Migration(migrations.Migration): dependencies = [ (\"challenges\", \"0022_auto_20200121_1639\"), ] operations", "django.core.validators from django.db import migrations import grandchallenge.challenges.models class Migration(migrations.Migration): dependencies", "class Migration(migrations.Migration): dependencies = [ (\"challenges\", \"0022_auto_20200121_1639\"), ] operations =", "unique=True, validators=[ grandchallenge.challenges.models.validate_nounderscores, django.core.validators.RegexValidator( re.compile(\"^[-a-zA-Z0-9_]+\\\\Z\"), \"Enter a valid “slug” consisting", "Django 3.0.2 on 2020-01-23 11:02 import re import django.contrib.postgres.fields.citext import", "migrations.AlterField( model_name=\"externalchallenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used in url, specific", "hyphens.\", \"invalid\", ), grandchallenge.challenges.models.validate_short_name, ], ), ), migrations.AlterField( model_name=\"externalchallenge\", name=\"short_name\",", "url, specific css, files etc. No spaces allowed\", max_length=50, unique=True,", "migrations import grandchallenge.challenges.models class Migration(migrations.Migration): dependencies = [ (\"challenges\", \"0022_auto_20200121_1639\"),", "numbers, underscores or hyphens.\", \"invalid\", ), grandchallenge.challenges.models.validate_short_name, ], ), ),", "2020-01-23 11:02 import re import django.contrib.postgres.fields.citext import django.core.validators from django.db", "field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used in url, specific css, files etc.", "model_name=\"externalchallenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used in url, specific css,", "= [ (\"challenges\", \"0022_auto_20200121_1639\"), ] operations = [ migrations.AlterField( model_name=\"challenge\",", "underscores or hyphens.\", \"invalid\", ), grandchallenge.challenges.models.validate_short_name, ], ), ), migrations.AlterField(", "specific css, files etc. No spaces allowed\", max_length=50, unique=True, validators=[", "], ), ), migrations.AlterField( model_name=\"externalchallenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used", "import django.contrib.postgres.fields.citext import django.core.validators from django.db import migrations import grandchallenge.challenges.models", "help_text=\"short name used in url, specific css, files etc. No", "on 2020-01-23 11:02 import re import django.contrib.postgres.fields.citext import django.core.validators from", "dependencies = [ (\"challenges\", \"0022_auto_20200121_1639\"), ] operations = [ migrations.AlterField(", "# Generated by Django 3.0.2 on 2020-01-23 11:02 import re", "underscores or hyphens.\", \"invalid\", ), grandchallenge.challenges.models.validate_short_name, ], ), ), ]", "operations = [ migrations.AlterField( model_name=\"challenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used", "migrations.AlterField( model_name=\"challenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used in url, specific", "allowed\", max_length=50, unique=True, validators=[ grandchallenge.challenges.models.validate_nounderscores, django.core.validators.RegexValidator( re.compile(\"^[-a-zA-Z0-9_]+\\\\Z\"), \"Enter a valid", "a valid “slug” consisting of letters, numbers, underscores or hyphens.\",", "), migrations.AlterField( model_name=\"externalchallenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used in url,", "django.contrib.postgres.fields.citext import django.core.validators from django.db import migrations import grandchallenge.challenges.models class", "import migrations import grandchallenge.challenges.models class Migration(migrations.Migration): dependencies = [ (\"challenges\",", "letters, numbers, underscores or hyphens.\", \"invalid\", ), grandchallenge.challenges.models.validate_short_name, ], ),", "\"invalid\", ), grandchallenge.challenges.models.validate_short_name, ], ), ), migrations.AlterField( model_name=\"externalchallenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField(", "import re import django.contrib.postgres.fields.citext import django.core.validators from django.db import migrations", "3.0.2 on 2020-01-23 11:02 import re import django.contrib.postgres.fields.citext import django.core.validators", "valid “slug” consisting of letters, numbers, underscores or hyphens.\", \"invalid\",", "from django.db import migrations import grandchallenge.challenges.models class Migration(migrations.Migration): dependencies =", "model_name=\"challenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name used in url, specific css,", "re import django.contrib.postgres.fields.citext import django.core.validators from django.db import migrations import", "files etc. No spaces allowed\", max_length=50, unique=True, validators=[ grandchallenge.challenges.models.validate_nounderscores, django.core.validators.RegexValidator(", "“slug” consisting of letters, numbers, underscores or hyphens.\", \"invalid\", ),", "name used in url, specific css, files etc. No spaces", "css, files etc. No spaces allowed\", max_length=50, unique=True, validators=[ grandchallenge.challenges.models.validate_nounderscores,", "] operations = [ migrations.AlterField( model_name=\"challenge\", name=\"short_name\", field=django.contrib.postgres.fields.citext.CICharField( help_text=\"short name", "Migration(migrations.Migration): dependencies = [ (\"challenges\", \"0022_auto_20200121_1639\"), ] operations = [", "or hyphens.\", \"invalid\", ), grandchallenge.challenges.models.validate_short_name, ], ), ), migrations.AlterField( model_name=\"externalchallenge\",", "etc. No spaces allowed\", max_length=50, unique=True, validators=[ grandchallenge.challenges.models.validate_nounderscores, django.core.validators.RegexValidator( re.compile(\"^[-a-zA-Z0-9_]+\\\\Z\")," ]
[ "def fit(self, X, y): Xf, yf = self._prefit(X, y) epoch", "1e-6, 0.1, log=True, default=0.01) l2 = UniformFloatHyperparameter(\"lambda2\", 1e-6, 1e-2, log=True,", "= EqualsCondition(power, lr_policy, 'inv') epoch_step_depends_on_policy = EqualsCondition(epoch_step, lr_policy, 'step') cs.add_condition(beta1_depends_on_solver)", "1e-2, log=True, default=1e-3) solver = CategoricalHyperparameter(name=\"solver\", choices=[\"sgd\", \"adam\"], default=\"sgd\") beta1", "False, 'handles_multilabel': False, 'is_deterministic': True, 'input': (DENSE, SPARSE, UNSIGNED_DATA), 'output':", "default=0.5) epoch_step = UniformIntegerHyperparameter(\"epoch_step\", 2, 20, default=5) cs = ConfigurationSpace()", "True, 'input': (DENSE, SPARSE, UNSIGNED_DATA), 'output': (PREDICTIONS,)} @staticmethod def get_hyperparameter_search_space(dataset_properties=None):", "self.learning_rate = learning_rate self.lr_policy = lr_policy self.lambda2 = lambda2 self.momentum", "y = (y - self.mean_y) / self.std_y if len(y.shape) ==", "= UniformFloatHyperparameter(\"dropout_output\", 0.0, 0.99, default=0.5) lr = UniformFloatHyperparameter(\"learning_rate\", 1e-6, 0.1,", "= UniformFloatHyperparameter(\"lambda2\", 1e-6, 1e-2, log=True, default=1e-3) solver = CategoricalHyperparameter(name=\"solver\", choices=[\"sgd\",", "@staticmethod def get_properties(dataset_properties=None): return {'shortname': 'lin_reg', 'name': 'Linear Regression', 'handles_regression':", "@staticmethod def get_hyperparameter_search_space(dataset_properties=None): policy_choices = ['fixed', 'inv', 'exp', 'step'] batch_size", "cs.add_hyperparameter(lr) cs.add_hyperparameter(l2) cs.add_hyperparameter(solver) cs.add_hyperparameter(beta1) cs.add_hyperparameter(beta2) cs.add_hyperparameter(lr_policy) cs.add_hyperparameter(gamma) cs.add_hyperparameter(power) cs.add_hyperparameter(epoch_step) beta1_depends_on_solver", "self.std_y = np.std(y) y = (y - self.mean_y) / self.std_y", "UniformIntegerHyperparameter(\"number_updates\", 500, 10500, log=True, default=500) dropout_output = UniformFloatHyperparameter(\"dropout_output\", 0.0, 0.99,", "lambda2, momentum=0.99, beta1=0.9, beta2=0.9, rho=0.95, lr_policy='fixed', gamma=0.01, power=1.0, epoch_step=2, random_state=None):", "= int(self.batch_size) self.n_features = X.shape[1] self.input_shape = (self.batch_size, self.n_features) self.num_output_units", "self.lr_policy = lr_policy self.lambda2 = lambda2 self.momentum = momentum self.beta1", "input_shape=self.input_shape, num_output_units=self.num_output_units, dropout_output=self.dropout_output, learning_rate=self.learning_rate, lr_policy=self.lr_policy, lambda2=self.lambda2, momentum=self.momentum, beta1=self.beta1, beta2=self.beta2, rho=self.rho,", "False, 'handles_multiclass': False, 'handles_multilabel': False, 'is_deterministic': True, 'input': (DENSE, SPARSE,", "log=True, default=0.1) beta2 = UniformFloatHyperparameter(\"beta2\", 1e-4, 0.1, log=True, default=0.01) lr_policy", "else 0.9 self.beta2 = 1-beta2 if beta2 is not None", "= epoch_step # Empty features and shape self.n_features = None", "power self.epoch_step = epoch_step # Empty features and shape self.n_features", "class LinReg(AutoSklearnRegressionAlgorithm): def __init__(self, number_updates, batch_size, dropout_output, learning_rate, solver, lambda2,", "possible epochs from implementation import LogisticRegression self.estimator = LogisticRegression.LogisticRegression(batch_size=self.batch_size, input_shape=self.input_shape,", "= np.mean(y) self.std_y = np.std(y) y = (y - self.mean_y)", "HPOlibConfigSpace.configuration_space import ConfigurationSpace from HPOlibConfigSpace.conditions import EqualsCondition, InCondition from HPOlibConfigSpace.hyperparameters", "1: y = y[:, np.newaxis] self.m_issparse = sp.issparse(X) return X,", "Empty features and shape self.n_features = None self.input_shape = None", "cs.add_hyperparameter(batch_size) cs.add_hyperparameter(dropout_output) cs.add_hyperparameter(lr) cs.add_hyperparameter(l2) cs.add_hyperparameter(solver) cs.add_hyperparameter(beta1) cs.add_hyperparameter(beta2) cs.add_hyperparameter(lr_policy) cs.add_hyperparameter(gamma) cs.add_hyperparameter(power)", "self.number_updates = number_updates self.batch_size = batch_size self.dropout_output = dropout_output self.learning_rate", "autosklearn.pipeline.constants import * class LinReg(AutoSklearnRegressionAlgorithm): def __init__(self, number_updates, batch_size, dropout_output,", "= None self.input_shape = None self.m_issparse = False self.m_isregression =", "beta1=0.9, beta2=0.9, rho=0.95, lr_policy='fixed', gamma=0.01, power=1.0, epoch_step=2, random_state=None): self.number_updates =", "'output': (PREDICTIONS,)} @staticmethod def get_hyperparameter_search_space(dataset_properties=None): policy_choices = ['fixed', 'inv', 'exp',", "int(self.batch_size) self.n_features = X.shape[1] self.input_shape = (self.batch_size, self.n_features) self.num_output_units =", "= y[:, np.newaxis] self.m_issparse = sp.issparse(X) return X, y def", "# Cap the max number of possible epochs from implementation", "y[:, np.newaxis] self.m_issparse = sp.issparse(X) return X, y def fit(self,", "not None else 0.9 self.beta2 = 1-beta2 if beta2 is", "predict_proba(self, X): if self.estimator is None: raise NotImplementedError() return self.estimator.predict_proba(X,", "default=5) cs = ConfigurationSpace() cs.add_hyperparameter(number_updates) cs.add_hyperparameter(batch_size) cs.add_hyperparameter(dropout_output) cs.add_hyperparameter(lr) cs.add_hyperparameter(l2) cs.add_hyperparameter(solver)", "self.beta2 = 1-beta2 if beta2 is not None else 0.99", "get_hyperparameter_search_space(dataset_properties=None): policy_choices = ['fixed', 'inv', 'exp', 'step'] batch_size = UniformIntegerHyperparameter(\"batch_size\",", "lr_policy='fixed', gamma=0.01, power=1.0, epoch_step=2, random_state=None): self.number_updates = number_updates self.batch_size =", "= rho self.solver = solver self.gamma = gamma self.power =", "gamma = UniformFloatHyperparameter(name=\"gamma\", lower=1e-3, upper=1e-1, default=1e-2) power = UniformFloatHyperparameter(\"power\", 0.0,", "self.dropout_output = dropout_output self.learning_rate = learning_rate self.lr_policy = lr_policy self.lambda2", "cs.add_hyperparameter(solver) cs.add_hyperparameter(beta1) cs.add_hyperparameter(beta2) cs.add_hyperparameter(lr_policy) cs.add_hyperparameter(gamma) cs.add_hyperparameter(power) cs.add_hyperparameter(epoch_step) beta1_depends_on_solver = EqualsCondition(beta1,", "X): if self.estimator is None: raise NotImplementedError preds = self.estimator.predict(X,", "= None self.m_issparse = False self.m_isregression = True self.m_isbinary =", "'handles_regression': True, 'handles_classification': False, 'handles_multiclass': False, 'handles_multilabel': False, 'is_deterministic': True,", "from HPOlibConfigSpace.configuration_space import ConfigurationSpace from HPOlibConfigSpace.conditions import EqualsCondition, InCondition from", "(self.number_updates * self.batch_size)//X.shape[0] number_epochs = min(max(2, epoch), 110) # Cap", "\\ UniformIntegerHyperparameter, CategoricalHyperparameter, Constant from autosklearn.pipeline.components.base import AutoSklearnRegressionAlgorithm from autosklearn.pipeline.constants", "epoch_step # Empty features and shape self.n_features = None self.input_shape", "self.estimator is None: raise NotImplementedError() return self.estimator.predict_proba(X, self.m_issparse) @staticmethod def", "False, 'is_deterministic': True, 'input': (DENSE, SPARSE, UNSIGNED_DATA), 'output': (PREDICTIONS,)} @staticmethod", "num_output_units=self.num_output_units, dropout_output=self.dropout_output, learning_rate=self.learning_rate, lr_policy=self.lr_policy, lambda2=self.lambda2, momentum=self.momentum, beta1=self.beta1, beta2=self.beta2, rho=self.rho, solver=self.solver,", "self.num_output_units = 1 # Regression # Normalize the output self.mean_y", "1 # Regression # Normalize the output self.mean_y = np.mean(y)", "num_epochs=number_epochs, gamma=self.gamma, power=self.power, epoch_step=self.epoch_step, is_sparse=self.m_issparse, is_binary=self.m_isbinary, is_multilabel=self.m_ismultilabel, is_regression=self.m_isregression) self.estimator.fit(Xf, yf)", "is_regression=self.m_isregression) self.estimator.fit(Xf, yf) return self def predict(self, X): if self.estimator", "epoch_step = UniformIntegerHyperparameter(\"epoch_step\", 2, 20, default=5) cs = ConfigurationSpace() cs.add_hyperparameter(number_updates)", "number_epochs = min(max(2, epoch), 110) # Cap the max number", "epoch = (self.number_updates * self.batch_size)//X.shape[0] number_epochs = min(max(2, epoch), 110)", "0.0, 1.0, default=0.5) epoch_step = UniformIntegerHyperparameter(\"epoch_step\", 2, 20, default=5) cs", "self.rho = rho self.solver = solver self.gamma = gamma self.power", "np.mean(y) self.std_y = np.std(y) y = (y - self.mean_y) /", "y = y[:, np.newaxis] self.m_issparse = sp.issparse(X) return X, y", "self.m_ismultilabel = False self.estimator = None def _prefit(self, X, y):", "def get_hyperparameter_search_space(dataset_properties=None): policy_choices = ['fixed', 'inv', 'exp', 'step'] batch_size =", "import * class LinReg(AutoSklearnRegressionAlgorithm): def __init__(self, number_updates, batch_size, dropout_output, learning_rate,", "scipy.sparse as sp from HPOlibConfigSpace.configuration_space import ConfigurationSpace from HPOlibConfigSpace.conditions import", "implementation import LogisticRegression self.estimator = LogisticRegression.LogisticRegression(batch_size=self.batch_size, input_shape=self.input_shape, num_output_units=self.num_output_units, dropout_output=self.dropout_output, learning_rate=self.learning_rate,", "default=150) number_updates = UniformIntegerHyperparameter(\"number_updates\", 500, 10500, log=True, default=500) dropout_output =", "cs.add_hyperparameter(l2) cs.add_hyperparameter(solver) cs.add_hyperparameter(beta1) cs.add_hyperparameter(beta2) cs.add_hyperparameter(lr_policy) cs.add_hyperparameter(gamma) cs.add_hyperparameter(power) cs.add_hyperparameter(epoch_step) beta1_depends_on_solver =", "None self.input_shape = None self.m_issparse = False self.m_isregression = True", "None self.m_issparse = False self.m_isregression = True self.m_isbinary = False", "batch_size, dropout_output, learning_rate, solver, lambda2, momentum=0.99, beta1=0.9, beta2=0.9, rho=0.95, lr_policy='fixed',", "return {'shortname': 'lin_reg', 'name': 'Linear Regression', 'handles_regression': True, 'handles_classification': False,", "1e-4, 0.1, log=True, default=0.1) beta2 = UniformFloatHyperparameter(\"beta2\", 1e-4, 0.1, log=True,", "= np.std(y) y = (y - self.mean_y) / self.std_y if", "from autosklearn.pipeline.components.base import AutoSklearnRegressionAlgorithm from autosklearn.pipeline.constants import * class LinReg(AutoSklearnRegressionAlgorithm):", "lower=1e-3, upper=1e-1, default=1e-2) power = UniformFloatHyperparameter(\"power\", 0.0, 1.0, default=0.5) epoch_step", "epoch_step=2, random_state=None): self.number_updates = number_updates self.batch_size = batch_size self.dropout_output =", "= self._prefit(X, y) epoch = (self.number_updates * self.batch_size)//X.shape[0] number_epochs =", "policy_choices = ['fixed', 'inv', 'exp', 'step'] batch_size = UniformIntegerHyperparameter(\"batch_size\", 100,", "parent=lr_policy, values=['inv', 'exp', 'step']) power_depends_on_policy = EqualsCondition(power, lr_policy, 'inv') epoch_step_depends_on_policy", "lr_policy = CategoricalHyperparameter(name=\"lr_policy\", choices=policy_choices, default='fixed') gamma = UniformFloatHyperparameter(name=\"gamma\", lower=1e-3, upper=1e-1,", "rho=self.rho, solver=self.solver, num_epochs=number_epochs, gamma=self.gamma, power=self.power, epoch_step=self.epoch_step, is_sparse=self.m_issparse, is_binary=self.m_isbinary, is_multilabel=self.m_ismultilabel, is_regression=self.m_isregression)", "self.gamma = gamma self.power = power self.epoch_step = epoch_step #", "yf = self._prefit(X, y) epoch = (self.number_updates * self.batch_size)//X.shape[0] number_epochs", "None: raise NotImplementedError() return self.estimator.predict_proba(X, self.m_issparse) @staticmethod def get_properties(dataset_properties=None): return", "UniformIntegerHyperparameter(\"batch_size\", 100, 3000, log=True, default=150) number_updates = UniformIntegerHyperparameter(\"number_updates\", 500, 10500,", "UniformFloatHyperparameter, \\ UniformIntegerHyperparameter, CategoricalHyperparameter, Constant from autosklearn.pipeline.components.base import AutoSklearnRegressionAlgorithm from", "= self.estimator.predict(X, self.m_issparse) return preds * self.std_y + self.mean_y def", "import AutoSklearnRegressionAlgorithm from autosklearn.pipeline.constants import * class LinReg(AutoSklearnRegressionAlgorithm): def __init__(self,", "= 1 # Regression # Normalize the output self.mean_y =", "= UniformFloatHyperparameter(\"beta2\", 1e-4, 0.1, log=True, default=0.01) lr_policy = CategoricalHyperparameter(name=\"lr_policy\", choices=policy_choices,", "(DENSE, SPARSE, UNSIGNED_DATA), 'output': (PREDICTIONS,)} @staticmethod def get_hyperparameter_search_space(dataset_properties=None): policy_choices =", "self.mean_y) / self.std_y if len(y.shape) == 1: y = y[:,", "def _prefit(self, X, y): self.batch_size = int(self.batch_size) self.n_features = X.shape[1]", "= CategoricalHyperparameter(name=\"lr_policy\", choices=policy_choices, default='fixed') gamma = UniformFloatHyperparameter(name=\"gamma\", lower=1e-3, upper=1e-1, default=1e-2)", "log=True, default=0.01) l2 = UniformFloatHyperparameter(\"lambda2\", 1e-6, 1e-2, log=True, default=1e-3) solver", "cs = ConfigurationSpace() cs.add_hyperparameter(number_updates) cs.add_hyperparameter(batch_size) cs.add_hyperparameter(dropout_output) cs.add_hyperparameter(lr) cs.add_hyperparameter(l2) cs.add_hyperparameter(solver) cs.add_hyperparameter(beta1)", "_prefit(self, X, y): self.batch_size = int(self.batch_size) self.n_features = X.shape[1] self.input_shape", "- self.mean_y) / self.std_y if len(y.shape) == 1: y =", "self.epoch_step = epoch_step # Empty features and shape self.n_features =", "* self.batch_size)//X.shape[0] number_epochs = min(max(2, epoch), 110) # Cap the", "is_binary=self.m_isbinary, is_multilabel=self.m_ismultilabel, is_regression=self.m_isregression) self.estimator.fit(Xf, yf) return self def predict(self, X):", "(y - self.mean_y) / self.std_y if len(y.shape) == 1: y", "solver=self.solver, num_epochs=number_epochs, gamma=self.gamma, power=self.power, epoch_step=self.epoch_step, is_sparse=self.m_issparse, is_binary=self.m_isbinary, is_multilabel=self.m_ismultilabel, is_regression=self.m_isregression) self.estimator.fit(Xf,", "min(max(2, epoch), 110) # Cap the max number of possible", "['fixed', 'inv', 'exp', 'step'] batch_size = UniformIntegerHyperparameter(\"batch_size\", 100, 3000, log=True,", "import LogisticRegression self.estimator = LogisticRegression.LogisticRegression(batch_size=self.batch_size, input_shape=self.input_shape, num_output_units=self.num_output_units, dropout_output=self.dropout_output, learning_rate=self.learning_rate, lr_policy=self.lr_policy,", "self.solver = solver self.gamma = gamma self.power = power self.epoch_step", "AutoSklearnRegressionAlgorithm from autosklearn.pipeline.constants import * class LinReg(AutoSklearnRegressionAlgorithm): def __init__(self, number_updates,", "learning_rate, solver, lambda2, momentum=0.99, beta1=0.9, beta2=0.9, rho=0.95, lr_policy='fixed', gamma=0.01, power=1.0,", "predict(self, X): if self.estimator is None: raise NotImplementedError preds =", "'handles_multiclass': False, 'handles_multilabel': False, 'is_deterministic': True, 'input': (DENSE, SPARSE, UNSIGNED_DATA),", "= sp.issparse(X) return X, y def fit(self, X, y): Xf,", "= lr_policy self.lambda2 = lambda2 self.momentum = momentum self.beta1 =", "len(y.shape) == 1: y = y[:, np.newaxis] self.m_issparse = sp.issparse(X)", "= 1-beta2 if beta2 is not None else 0.99 self.rho", "'step']) power_depends_on_policy = EqualsCondition(power, lr_policy, 'inv') epoch_step_depends_on_policy = EqualsCondition(epoch_step, lr_policy,", "'input': (DENSE, SPARSE, UNSIGNED_DATA), 'output': (PREDICTIONS,)} @staticmethod def get_hyperparameter_search_space(dataset_properties=None): policy_choices", "is not None else 0.9 self.beta2 = 1-beta2 if beta2", "solver, \"adam\") beta2_depends_on_solver = EqualsCondition(beta2, solver, \"adam\") gamma_depends_on_policy = InCondition(child=gamma,", "* class LinReg(AutoSklearnRegressionAlgorithm): def __init__(self, number_updates, batch_size, dropout_output, learning_rate, solver,", "as np import scipy.sparse as sp from HPOlibConfigSpace.configuration_space import ConfigurationSpace", "self.m_isbinary = False self.m_ismultilabel = False self.estimator = None def", "UniformFloatHyperparameter(\"beta1\", 1e-4, 0.1, log=True, default=0.1) beta2 = UniformFloatHyperparameter(\"beta2\", 1e-4, 0.1,", "default=0.1) beta2 = UniformFloatHyperparameter(\"beta2\", 1e-4, 0.1, log=True, default=0.01) lr_policy =", "= 1-beta1 if beta1 is not None else 0.9 self.beta2", "1-beta2 if beta2 is not None else 0.99 self.rho =", "momentum self.beta1 = 1-beta1 if beta1 is not None else", "sp.issparse(X) return X, y def fit(self, X, y): Xf, yf", "if beta1 is not None else 0.9 self.beta2 = 1-beta2", "/ self.std_y if len(y.shape) == 1: y = y[:, np.newaxis]", "# Empty features and shape self.n_features = None self.input_shape =", "'is_deterministic': True, 'input': (DENSE, SPARSE, UNSIGNED_DATA), 'output': (PREDICTIONS,)} @staticmethod def", "number_updates = UniformIntegerHyperparameter(\"number_updates\", 500, 10500, log=True, default=500) dropout_output = UniformFloatHyperparameter(\"dropout_output\",", "import ConfigurationSpace from HPOlibConfigSpace.conditions import EqualsCondition, InCondition from HPOlibConfigSpace.hyperparameters import", "0.99 self.rho = rho self.solver = solver self.gamma = gamma", "solver self.gamma = gamma self.power = power self.epoch_step = epoch_step", "power=self.power, epoch_step=self.epoch_step, is_sparse=self.m_issparse, is_binary=self.m_isbinary, is_multilabel=self.m_ismultilabel, is_regression=self.m_isregression) self.estimator.fit(Xf, yf) return self", "upper=1e-1, default=1e-2) power = UniformFloatHyperparameter(\"power\", 0.0, 1.0, default=0.5) epoch_step =", "'handles_classification': False, 'handles_multiclass': False, 'handles_multilabel': False, 'is_deterministic': True, 'input': (DENSE,", "NotImplementedError preds = self.estimator.predict(X, self.m_issparse) return preds * self.std_y +", "self.mean_y = np.mean(y) self.std_y = np.std(y) y = (y -", "is_sparse=self.m_issparse, is_binary=self.m_isbinary, is_multilabel=self.m_ismultilabel, is_regression=self.m_isregression) self.estimator.fit(Xf, yf) return self def predict(self,", "import numpy as np import scipy.sparse as sp from HPOlibConfigSpace.configuration_space", "False self.m_ismultilabel = False self.estimator = None def _prefit(self, X,", "self._prefit(X, y) epoch = (self.number_updates * self.batch_size)//X.shape[0] number_epochs = min(max(2,", "100, 3000, log=True, default=150) number_updates = UniformIntegerHyperparameter(\"number_updates\", 500, 10500, log=True,", "default=1e-3) solver = CategoricalHyperparameter(name=\"solver\", choices=[\"sgd\", \"adam\"], default=\"sgd\") beta1 = UniformFloatHyperparameter(\"beta1\",", "= (y - self.mean_y) / self.std_y if len(y.shape) == 1:", "1-beta1 if beta1 is not None else 0.9 self.beta2 =", "beta1_depends_on_solver = EqualsCondition(beta1, solver, \"adam\") beta2_depends_on_solver = EqualsCondition(beta2, solver, \"adam\")", "= dropout_output self.learning_rate = learning_rate self.lr_policy = lr_policy self.lambda2 =", "self.m_issparse = False self.m_isregression = True self.m_isbinary = False self.m_ismultilabel", "None def _prefit(self, X, y): self.batch_size = int(self.batch_size) self.n_features =", "UniformFloatHyperparameter(\"dropout_output\", 0.0, 0.99, default=0.5) lr = UniformFloatHyperparameter(\"learning_rate\", 1e-6, 0.1, log=True,", "power=1.0, epoch_step=2, random_state=None): self.number_updates = number_updates self.batch_size = batch_size self.dropout_output", "20, default=5) cs = ConfigurationSpace() cs.add_hyperparameter(number_updates) cs.add_hyperparameter(batch_size) cs.add_hyperparameter(dropout_output) cs.add_hyperparameter(lr) cs.add_hyperparameter(l2)", "lr_policy, 'inv') epoch_step_depends_on_policy = EqualsCondition(epoch_step, lr_policy, 'step') cs.add_condition(beta1_depends_on_solver) cs.add_condition(beta2_depends_on_solver) cs.add_condition(gamma_depends_on_policy)", "= power self.epoch_step = epoch_step # Empty features and shape", "self.batch_size)//X.shape[0] number_epochs = min(max(2, epoch), 110) # Cap the max", "self.input_shape = None self.m_issparse = False self.m_isregression = True self.m_isbinary", "0.1, log=True, default=0.01) lr_policy = CategoricalHyperparameter(name=\"lr_policy\", choices=policy_choices, default='fixed') gamma =", "UniformFloatHyperparameter(name=\"gamma\", lower=1e-3, upper=1e-1, default=1e-2) power = UniformFloatHyperparameter(\"power\", 0.0, 1.0, default=0.5)", "yf) return self def predict(self, X): if self.estimator is None:", "np.newaxis] self.m_issparse = sp.issparse(X) return X, y def fit(self, X,", "return self.estimator.predict_proba(X, self.m_issparse) @staticmethod def get_properties(dataset_properties=None): return {'shortname': 'lin_reg', 'name':", "= CategoricalHyperparameter(name=\"solver\", choices=[\"sgd\", \"adam\"], default=\"sgd\") beta1 = UniformFloatHyperparameter(\"beta1\", 1e-4, 0.1,", "np.std(y) y = (y - self.mean_y) / self.std_y if len(y.shape)", "solver, \"adam\") gamma_depends_on_policy = InCondition(child=gamma, parent=lr_policy, values=['inv', 'exp', 'step']) power_depends_on_policy", "sp from HPOlibConfigSpace.configuration_space import ConfigurationSpace from HPOlibConfigSpace.conditions import EqualsCondition, InCondition", "learning_rate self.lr_policy = lr_policy self.lambda2 = lambda2 self.momentum = momentum", "cs.add_hyperparameter(power) cs.add_hyperparameter(epoch_step) beta1_depends_on_solver = EqualsCondition(beta1, solver, \"adam\") beta2_depends_on_solver = EqualsCondition(beta2,", "rho=0.95, lr_policy='fixed', gamma=0.01, power=1.0, epoch_step=2, random_state=None): self.number_updates = number_updates self.batch_size", "self.estimator is None: raise NotImplementedError preds = self.estimator.predict(X, self.m_issparse) return", "LogisticRegression.LogisticRegression(batch_size=self.batch_size, input_shape=self.input_shape, num_output_units=self.num_output_units, dropout_output=self.dropout_output, learning_rate=self.learning_rate, lr_policy=self.lr_policy, lambda2=self.lambda2, momentum=self.momentum, beta1=self.beta1, beta2=self.beta2,", "\"adam\"], default=\"sgd\") beta1 = UniformFloatHyperparameter(\"beta1\", 1e-4, 0.1, log=True, default=0.1) beta2", "epoch), 110) # Cap the max number of possible epochs", "\"adam\") beta2_depends_on_solver = EqualsCondition(beta2, solver, \"adam\") gamma_depends_on_policy = InCondition(child=gamma, parent=lr_policy,", "numpy as np import scipy.sparse as sp from HPOlibConfigSpace.configuration_space import", "lambda2=self.lambda2, momentum=self.momentum, beta1=self.beta1, beta2=self.beta2, rho=self.rho, solver=self.solver, num_epochs=number_epochs, gamma=self.gamma, power=self.power, epoch_step=self.epoch_step,", "__init__(self, number_updates, batch_size, dropout_output, learning_rate, solver, lambda2, momentum=0.99, beta1=0.9, beta2=0.9,", "lambda2 self.momentum = momentum self.beta1 = 1-beta1 if beta1 is", "self.lambda2 = lambda2 self.momentum = momentum self.beta1 = 1-beta1 if", "cs.add_hyperparameter(beta2) cs.add_hyperparameter(lr_policy) cs.add_hyperparameter(gamma) cs.add_hyperparameter(power) cs.add_hyperparameter(epoch_step) beta1_depends_on_solver = EqualsCondition(beta1, solver, \"adam\")", "= False self.estimator = None def _prefit(self, X, y): self.batch_size", "dropout_output self.learning_rate = learning_rate self.lr_policy = lr_policy self.lambda2 = lambda2", "{'shortname': 'lin_reg', 'name': 'Linear Regression', 'handles_regression': True, 'handles_classification': False, 'handles_multiclass':", "preds = self.estimator.predict(X, self.m_issparse) return preds * self.std_y + self.mean_y", "raise NotImplementedError() return self.estimator.predict_proba(X, self.m_issparse) @staticmethod def get_properties(dataset_properties=None): return {'shortname':", "default='fixed') gamma = UniformFloatHyperparameter(name=\"gamma\", lower=1e-3, upper=1e-1, default=1e-2) power = UniformFloatHyperparameter(\"power\",", "1e-4, 0.1, log=True, default=0.01) lr_policy = CategoricalHyperparameter(name=\"lr_policy\", choices=policy_choices, default='fixed') gamma", "HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter, \\ UniformIntegerHyperparameter, CategoricalHyperparameter, Constant from autosklearn.pipeline.components.base import", "choices=policy_choices, default='fixed') gamma = UniformFloatHyperparameter(name=\"gamma\", lower=1e-3, upper=1e-1, default=1e-2) power =", "* self.std_y + self.mean_y def predict_proba(self, X): if self.estimator is", "y): self.batch_size = int(self.batch_size) self.n_features = X.shape[1] self.input_shape = (self.batch_size,", "features and shape self.n_features = None self.input_shape = None self.m_issparse", "EqualsCondition(epoch_step, lr_policy, 'step') cs.add_condition(beta1_depends_on_solver) cs.add_condition(beta2_depends_on_solver) cs.add_condition(gamma_depends_on_policy) cs.add_condition(power_depends_on_policy) cs.add_condition(epoch_step_depends_on_policy) return cs", "power_depends_on_policy = EqualsCondition(power, lr_policy, 'inv') epoch_step_depends_on_policy = EqualsCondition(epoch_step, lr_policy, 'step')", "'exp', 'step'] batch_size = UniformIntegerHyperparameter(\"batch_size\", 100, 3000, log=True, default=150) number_updates", "default=1e-2) power = UniformFloatHyperparameter(\"power\", 0.0, 1.0, default=0.5) epoch_step = UniformIntegerHyperparameter(\"epoch_step\",", "self.input_shape = (self.batch_size, self.n_features) self.num_output_units = 1 # Regression #", "batch_size self.dropout_output = dropout_output self.learning_rate = learning_rate self.lr_policy = lr_policy", "self.beta1 = 1-beta1 if beta1 is not None else 0.9", "self.power = power self.epoch_step = epoch_step # Empty features and", "X, y): Xf, yf = self._prefit(X, y) epoch = (self.number_updates", "default=0.5) lr = UniformFloatHyperparameter(\"learning_rate\", 1e-6, 0.1, log=True, default=0.01) l2 =", "learning_rate=self.learning_rate, lr_policy=self.lr_policy, lambda2=self.lambda2, momentum=self.momentum, beta1=self.beta1, beta2=self.beta2, rho=self.rho, solver=self.solver, num_epochs=number_epochs, gamma=self.gamma,", "dropout_output=self.dropout_output, learning_rate=self.learning_rate, lr_policy=self.lr_policy, lambda2=self.lambda2, momentum=self.momentum, beta1=self.beta1, beta2=self.beta2, rho=self.rho, solver=self.solver, num_epochs=number_epochs,", "gamma_depends_on_policy = InCondition(child=gamma, parent=lr_policy, values=['inv', 'exp', 'step']) power_depends_on_policy = EqualsCondition(power,", "= min(max(2, epoch), 110) # Cap the max number of", "return X, y def fit(self, X, y): Xf, yf =", "import EqualsCondition, InCondition from HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter, \\ UniformIntegerHyperparameter, CategoricalHyperparameter,", "Regression # Normalize the output self.mean_y = np.mean(y) self.std_y =", "self.m_isregression = True self.m_isbinary = False self.m_ismultilabel = False self.estimator", "= False self.m_isregression = True self.m_isbinary = False self.m_ismultilabel =", "default=0.01) l2 = UniformFloatHyperparameter(\"lambda2\", 1e-6, 1e-2, log=True, default=1e-3) solver =", "batch_size = UniformIntegerHyperparameter(\"batch_size\", 100, 3000, log=True, default=150) number_updates = UniformIntegerHyperparameter(\"number_updates\",", "cs.add_hyperparameter(beta1) cs.add_hyperparameter(beta2) cs.add_hyperparameter(lr_policy) cs.add_hyperparameter(gamma) cs.add_hyperparameter(power) cs.add_hyperparameter(epoch_step) beta1_depends_on_solver = EqualsCondition(beta1, solver,", "True self.m_isbinary = False self.m_ismultilabel = False self.estimator = None", "gamma=self.gamma, power=self.power, epoch_step=self.epoch_step, is_sparse=self.m_issparse, is_binary=self.m_isbinary, is_multilabel=self.m_ismultilabel, is_regression=self.m_isregression) self.estimator.fit(Xf, yf) return", "self.momentum = momentum self.beta1 = 1-beta1 if beta1 is not", "self.std_y if len(y.shape) == 1: y = y[:, np.newaxis] self.m_issparse", "0.9 self.beta2 = 1-beta2 if beta2 is not None else", "= EqualsCondition(epoch_step, lr_policy, 'step') cs.add_condition(beta1_depends_on_solver) cs.add_condition(beta2_depends_on_solver) cs.add_condition(gamma_depends_on_policy) cs.add_condition(power_depends_on_policy) cs.add_condition(epoch_step_depends_on_policy) return", "cs.add_hyperparameter(lr_policy) cs.add_hyperparameter(gamma) cs.add_hyperparameter(power) cs.add_hyperparameter(epoch_step) beta1_depends_on_solver = EqualsCondition(beta1, solver, \"adam\") beta2_depends_on_solver", "= ConfigurationSpace() cs.add_hyperparameter(number_updates) cs.add_hyperparameter(batch_size) cs.add_hyperparameter(dropout_output) cs.add_hyperparameter(lr) cs.add_hyperparameter(l2) cs.add_hyperparameter(solver) cs.add_hyperparameter(beta1) cs.add_hyperparameter(beta2)", "None else 0.99 self.rho = rho self.solver = solver self.gamma", "X, y def fit(self, X, y): Xf, yf = self._prefit(X,", "= UniformFloatHyperparameter(name=\"gamma\", lower=1e-3, upper=1e-1, default=1e-2) power = UniformFloatHyperparameter(\"power\", 0.0, 1.0,", "(self.batch_size, self.n_features) self.num_output_units = 1 # Regression # Normalize the", "'inv', 'exp', 'step'] batch_size = UniformIntegerHyperparameter(\"batch_size\", 100, 3000, log=True, default=150)", "# Regression # Normalize the output self.mean_y = np.mean(y) self.std_y", "choices=[\"sgd\", \"adam\"], default=\"sgd\") beta1 = UniformFloatHyperparameter(\"beta1\", 1e-4, 0.1, log=True, default=0.1)", "= ['fixed', 'inv', 'exp', 'step'] batch_size = UniformIntegerHyperparameter(\"batch_size\", 100, 3000,", "'Linear Regression', 'handles_regression': True, 'handles_classification': False, 'handles_multiclass': False, 'handles_multilabel': False,", "= EqualsCondition(beta2, solver, \"adam\") gamma_depends_on_policy = InCondition(child=gamma, parent=lr_policy, values=['inv', 'exp',", "default=500) dropout_output = UniformFloatHyperparameter(\"dropout_output\", 0.0, 0.99, default=0.5) lr = UniformFloatHyperparameter(\"learning_rate\",", "= momentum self.beta1 = 1-beta1 if beta1 is not None", "self.m_issparse = sp.issparse(X) return X, y def fit(self, X, y):", "= (self.batch_size, self.n_features) self.num_output_units = 1 # Regression # Normalize", "beta2=self.beta2, rho=self.rho, solver=self.solver, num_epochs=number_epochs, gamma=self.gamma, power=self.power, epoch_step=self.epoch_step, is_sparse=self.m_issparse, is_binary=self.m_isbinary, is_multilabel=self.m_ismultilabel,", "beta2_depends_on_solver = EqualsCondition(beta2, solver, \"adam\") gamma_depends_on_policy = InCondition(child=gamma, parent=lr_policy, values=['inv',", "cs.add_hyperparameter(dropout_output) cs.add_hyperparameter(lr) cs.add_hyperparameter(l2) cs.add_hyperparameter(solver) cs.add_hyperparameter(beta1) cs.add_hyperparameter(beta2) cs.add_hyperparameter(lr_policy) cs.add_hyperparameter(gamma) cs.add_hyperparameter(power) cs.add_hyperparameter(epoch_step)", "else 0.99 self.rho = rho self.solver = solver self.gamma =", "ConfigurationSpace() cs.add_hyperparameter(number_updates) cs.add_hyperparameter(batch_size) cs.add_hyperparameter(dropout_output) cs.add_hyperparameter(lr) cs.add_hyperparameter(l2) cs.add_hyperparameter(solver) cs.add_hyperparameter(beta1) cs.add_hyperparameter(beta2) cs.add_hyperparameter(lr_policy)", "UniformFloatHyperparameter(\"beta2\", 1e-4, 0.1, log=True, default=0.01) lr_policy = CategoricalHyperparameter(name=\"lr_policy\", choices=policy_choices, default='fixed')", "CategoricalHyperparameter(name=\"solver\", choices=[\"sgd\", \"adam\"], default=\"sgd\") beta1 = UniformFloatHyperparameter(\"beta1\", 1e-4, 0.1, log=True,", "self.std_y + self.mean_y def predict_proba(self, X): if self.estimator is None:", "beta2 = UniformFloatHyperparameter(\"beta2\", 1e-4, 0.1, log=True, default=0.01) lr_policy = CategoricalHyperparameter(name=\"lr_policy\",", "from HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter, \\ UniformIntegerHyperparameter, CategoricalHyperparameter, Constant from autosklearn.pipeline.components.base", "dropout_output = UniformFloatHyperparameter(\"dropout_output\", 0.0, 0.99, default=0.5) lr = UniformFloatHyperparameter(\"learning_rate\", 1e-6,", "values=['inv', 'exp', 'step']) power_depends_on_policy = EqualsCondition(power, lr_policy, 'inv') epoch_step_depends_on_policy =", "momentum=0.99, beta1=0.9, beta2=0.9, rho=0.95, lr_policy='fixed', gamma=0.01, power=1.0, epoch_step=2, random_state=None): self.number_updates", "gamma=0.01, power=1.0, epoch_step=2, random_state=None): self.number_updates = number_updates self.batch_size = batch_size", "self.n_features = X.shape[1] self.input_shape = (self.batch_size, self.n_features) self.num_output_units = 1", "0.1, log=True, default=0.01) l2 = UniformFloatHyperparameter(\"lambda2\", 1e-6, 1e-2, log=True, default=1e-3)", "as sp from HPOlibConfigSpace.configuration_space import ConfigurationSpace from HPOlibConfigSpace.conditions import EqualsCondition,", "1e-6, 1e-2, log=True, default=1e-3) solver = CategoricalHyperparameter(name=\"solver\", choices=[\"sgd\", \"adam\"], default=\"sgd\")", "from implementation import LogisticRegression self.estimator = LogisticRegression.LogisticRegression(batch_size=self.batch_size, input_shape=self.input_shape, num_output_units=self.num_output_units, dropout_output=self.dropout_output,", "self.batch_size = int(self.batch_size) self.n_features = X.shape[1] self.input_shape = (self.batch_size, self.n_features)", "def predict(self, X): if self.estimator is None: raise NotImplementedError preds", "False self.estimator = None def _prefit(self, X, y): self.batch_size =", "500, 10500, log=True, default=500) dropout_output = UniformFloatHyperparameter(\"dropout_output\", 0.0, 0.99, default=0.5)", "self.estimator = None def _prefit(self, X, y): self.batch_size = int(self.batch_size)", "return preds * self.std_y + self.mean_y def predict_proba(self, X): if", "UNSIGNED_DATA), 'output': (PREDICTIONS,)} @staticmethod def get_hyperparameter_search_space(dataset_properties=None): policy_choices = ['fixed', 'inv',", "if self.estimator is None: raise NotImplementedError preds = self.estimator.predict(X, self.m_issparse)", "epochs from implementation import LogisticRegression self.estimator = LogisticRegression.LogisticRegression(batch_size=self.batch_size, input_shape=self.input_shape, num_output_units=self.num_output_units,", "self.n_features) self.num_output_units = 1 # Regression # Normalize the output", "the output self.mean_y = np.mean(y) self.std_y = np.std(y) y =", "X, y): self.batch_size = int(self.batch_size) self.n_features = X.shape[1] self.input_shape =", "lr_policy self.lambda2 = lambda2 self.momentum = momentum self.beta1 = 1-beta1", "def get_properties(dataset_properties=None): return {'shortname': 'lin_reg', 'name': 'Linear Regression', 'handles_regression': True,", "output self.mean_y = np.mean(y) self.std_y = np.std(y) y = (y", "preds * self.std_y + self.mean_y def predict_proba(self, X): if self.estimator", "UniformFloatHyperparameter(\"learning_rate\", 1e-6, 0.1, log=True, default=0.01) l2 = UniformFloatHyperparameter(\"lambda2\", 1e-6, 1e-2,", "Constant from autosklearn.pipeline.components.base import AutoSklearnRegressionAlgorithm from autosklearn.pipeline.constants import * class", "= UniformIntegerHyperparameter(\"batch_size\", 100, 3000, log=True, default=150) number_updates = UniformIntegerHyperparameter(\"number_updates\", 500,", "epoch_step=self.epoch_step, is_sparse=self.m_issparse, is_binary=self.m_isbinary, is_multilabel=self.m_ismultilabel, is_regression=self.m_isregression) self.estimator.fit(Xf, yf) return self def", "= batch_size self.dropout_output = dropout_output self.learning_rate = learning_rate self.lr_policy =", "0.0, 0.99, default=0.5) lr = UniformFloatHyperparameter(\"learning_rate\", 1e-6, 0.1, log=True, default=0.01)", "log=True, default=150) number_updates = UniformIntegerHyperparameter(\"number_updates\", 500, 10500, log=True, default=500) dropout_output", "= EqualsCondition(beta1, solver, \"adam\") beta2_depends_on_solver = EqualsCondition(beta2, solver, \"adam\") gamma_depends_on_policy", "Xf, yf = self._prefit(X, y) epoch = (self.number_updates * self.batch_size)//X.shape[0]", "3000, log=True, default=150) number_updates = UniformIntegerHyperparameter(\"number_updates\", 500, 10500, log=True, default=500)", "EqualsCondition(beta1, solver, \"adam\") beta2_depends_on_solver = EqualsCondition(beta2, solver, \"adam\") gamma_depends_on_policy =", "beta2=0.9, rho=0.95, lr_policy='fixed', gamma=0.01, power=1.0, epoch_step=2, random_state=None): self.number_updates = number_updates", "None else 0.9 self.beta2 = 1-beta2 if beta2 is not", "self.estimator.fit(Xf, yf) return self def predict(self, X): if self.estimator is", "= gamma self.power = power self.epoch_step = epoch_step # Empty", "10500, log=True, default=500) dropout_output = UniformFloatHyperparameter(\"dropout_output\", 0.0, 0.99, default=0.5) lr", "raise NotImplementedError preds = self.estimator.predict(X, self.m_issparse) return preds * self.std_y", "X): if self.estimator is None: raise NotImplementedError() return self.estimator.predict_proba(X, self.m_issparse)", "dropout_output, learning_rate, solver, lambda2, momentum=0.99, beta1=0.9, beta2=0.9, rho=0.95, lr_policy='fixed', gamma=0.01,", "= UniformIntegerHyperparameter(\"epoch_step\", 2, 20, default=5) cs = ConfigurationSpace() cs.add_hyperparameter(number_updates) cs.add_hyperparameter(batch_size)", "2, 20, default=5) cs = ConfigurationSpace() cs.add_hyperparameter(number_updates) cs.add_hyperparameter(batch_size) cs.add_hyperparameter(dropout_output) cs.add_hyperparameter(lr)", "get_properties(dataset_properties=None): return {'shortname': 'lin_reg', 'name': 'Linear Regression', 'handles_regression': True, 'handles_classification':", "is_multilabel=self.m_ismultilabel, is_regression=self.m_isregression) self.estimator.fit(Xf, yf) return self def predict(self, X): if", "default=\"sgd\") beta1 = UniformFloatHyperparameter(\"beta1\", 1e-4, 0.1, log=True, default=0.1) beta2 =", "= UniformIntegerHyperparameter(\"number_updates\", 500, 10500, log=True, default=500) dropout_output = UniformFloatHyperparameter(\"dropout_output\", 0.0,", "EqualsCondition(beta2, solver, \"adam\") gamma_depends_on_policy = InCondition(child=gamma, parent=lr_policy, values=['inv', 'exp', 'step'])", "X.shape[1] self.input_shape = (self.batch_size, self.n_features) self.num_output_units = 1 # Regression", "log=True, default=500) dropout_output = UniformFloatHyperparameter(\"dropout_output\", 0.0, 0.99, default=0.5) lr =", "is not None else 0.99 self.rho = rho self.solver =", "from autosklearn.pipeline.constants import * class LinReg(AutoSklearnRegressionAlgorithm): def __init__(self, number_updates, batch_size,", "= X.shape[1] self.input_shape = (self.batch_size, self.n_features) self.num_output_units = 1 #", "= UniformFloatHyperparameter(\"learning_rate\", 1e-6, 0.1, log=True, default=0.01) l2 = UniformFloatHyperparameter(\"lambda2\", 1e-6,", "default=0.01) lr_policy = CategoricalHyperparameter(name=\"lr_policy\", choices=policy_choices, default='fixed') gamma = UniformFloatHyperparameter(name=\"gamma\", lower=1e-3,", "+ self.mean_y def predict_proba(self, X): if self.estimator is None: raise", "HPOlibConfigSpace.conditions import EqualsCondition, InCondition from HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter, \\ UniformIntegerHyperparameter,", "solver = CategoricalHyperparameter(name=\"solver\", choices=[\"sgd\", \"adam\"], default=\"sgd\") beta1 = UniformFloatHyperparameter(\"beta1\", 1e-4,", "number_updates self.batch_size = batch_size self.dropout_output = dropout_output self.learning_rate = learning_rate", "beta2 is not None else 0.99 self.rho = rho self.solver", "= UniformFloatHyperparameter(\"beta1\", 1e-4, 0.1, log=True, default=0.1) beta2 = UniformFloatHyperparameter(\"beta2\", 1e-4,", "'exp', 'step']) power_depends_on_policy = EqualsCondition(power, lr_policy, 'inv') epoch_step_depends_on_policy = EqualsCondition(epoch_step,", "self.m_issparse) return preds * self.std_y + self.mean_y def predict_proba(self, X):", "from HPOlibConfigSpace.conditions import EqualsCondition, InCondition from HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter, \\", "Regression', 'handles_regression': True, 'handles_classification': False, 'handles_multiclass': False, 'handles_multilabel': False, 'is_deterministic':", "'handles_multilabel': False, 'is_deterministic': True, 'input': (DENSE, SPARSE, UNSIGNED_DATA), 'output': (PREDICTIONS,)}", "= InCondition(child=gamma, parent=lr_policy, values=['inv', 'exp', 'step']) power_depends_on_policy = EqualsCondition(power, lr_policy,", "= (self.number_updates * self.batch_size)//X.shape[0] number_epochs = min(max(2, epoch), 110) #", "= learning_rate self.lr_policy = lr_policy self.lambda2 = lambda2 self.momentum =", "self.m_issparse) @staticmethod def get_properties(dataset_properties=None): return {'shortname': 'lin_reg', 'name': 'Linear Regression',", "False self.m_isregression = True self.m_isbinary = False self.m_ismultilabel = False", "if beta2 is not None else 0.99 self.rho = rho", "Normalize the output self.mean_y = np.mean(y) self.std_y = np.std(y) y", "'name': 'Linear Regression', 'handles_regression': True, 'handles_classification': False, 'handles_multiclass': False, 'handles_multilabel':", "ConfigurationSpace from HPOlibConfigSpace.conditions import EqualsCondition, InCondition from HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter,", "return self def predict(self, X): if self.estimator is None: raise", "'lin_reg', 'name': 'Linear Regression', 'handles_regression': True, 'handles_classification': False, 'handles_multiclass': False,", "UniformIntegerHyperparameter(\"epoch_step\", 2, 20, default=5) cs = ConfigurationSpace() cs.add_hyperparameter(number_updates) cs.add_hyperparameter(batch_size) cs.add_hyperparameter(dropout_output)", "== 1: y = y[:, np.newaxis] self.m_issparse = sp.issparse(X) return", "if len(y.shape) == 1: y = y[:, np.newaxis] self.m_issparse =", "beta1=self.beta1, beta2=self.beta2, rho=self.rho, solver=self.solver, num_epochs=number_epochs, gamma=self.gamma, power=self.power, epoch_step=self.epoch_step, is_sparse=self.m_issparse, is_binary=self.m_isbinary,", "shape self.n_features = None self.input_shape = None self.m_issparse = False", "not None else 0.99 self.rho = rho self.solver = solver", "# Normalize the output self.mean_y = np.mean(y) self.std_y = np.std(y)", "InCondition from HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter, \\ UniformIntegerHyperparameter, CategoricalHyperparameter, Constant from", "UniformFloatHyperparameter(\"lambda2\", 1e-6, 1e-2, log=True, default=1e-3) solver = CategoricalHyperparameter(name=\"solver\", choices=[\"sgd\", \"adam\"],", "UniformFloatHyperparameter(\"power\", 0.0, 1.0, default=0.5) epoch_step = UniformIntegerHyperparameter(\"epoch_step\", 2, 20, default=5)", "SPARSE, UNSIGNED_DATA), 'output': (PREDICTIONS,)} @staticmethod def get_hyperparameter_search_space(dataset_properties=None): policy_choices = ['fixed',", "<reponame>hmendozap/master-arbeit-files import numpy as np import scipy.sparse as sp from", "lr = UniformFloatHyperparameter(\"learning_rate\", 1e-6, 0.1, log=True, default=0.01) l2 = UniformFloatHyperparameter(\"lambda2\",", "1.0, default=0.5) epoch_step = UniformIntegerHyperparameter(\"epoch_step\", 2, 20, default=5) cs =", "of possible epochs from implementation import LogisticRegression self.estimator = LogisticRegression.LogisticRegression(batch_size=self.batch_size,", "'step'] batch_size = UniformIntegerHyperparameter(\"batch_size\", 100, 3000, log=True, default=150) number_updates =", "solver, lambda2, momentum=0.99, beta1=0.9, beta2=0.9, rho=0.95, lr_policy='fixed', gamma=0.01, power=1.0, epoch_step=2,", "\"adam\") gamma_depends_on_policy = InCondition(child=gamma, parent=lr_policy, values=['inv', 'exp', 'step']) power_depends_on_policy =", "lr_policy=self.lr_policy, lambda2=self.lambda2, momentum=self.momentum, beta1=self.beta1, beta2=self.beta2, rho=self.rho, solver=self.solver, num_epochs=number_epochs, gamma=self.gamma, power=self.power,", "fit(self, X, y): Xf, yf = self._prefit(X, y) epoch =", "and shape self.n_features = None self.input_shape = None self.m_issparse =", "= UniformFloatHyperparameter(\"power\", 0.0, 1.0, default=0.5) epoch_step = UniformIntegerHyperparameter(\"epoch_step\", 2, 20,", "CategoricalHyperparameter(name=\"lr_policy\", choices=policy_choices, default='fixed') gamma = UniformFloatHyperparameter(name=\"gamma\", lower=1e-3, upper=1e-1, default=1e-2) power", "beta1 is not None else 0.9 self.beta2 = 1-beta2 if", "self.estimator = LogisticRegression.LogisticRegression(batch_size=self.batch_size, input_shape=self.input_shape, num_output_units=self.num_output_units, dropout_output=self.dropout_output, learning_rate=self.learning_rate, lr_policy=self.lr_policy, lambda2=self.lambda2, momentum=self.momentum,", "UniformIntegerHyperparameter, CategoricalHyperparameter, Constant from autosklearn.pipeline.components.base import AutoSklearnRegressionAlgorithm from autosklearn.pipeline.constants import", "number of possible epochs from implementation import LogisticRegression self.estimator =", "is None: raise NotImplementedError() return self.estimator.predict_proba(X, self.m_issparse) @staticmethod def get_properties(dataset_properties=None):", "import UniformFloatHyperparameter, \\ UniformIntegerHyperparameter, CategoricalHyperparameter, Constant from autosklearn.pipeline.components.base import AutoSklearnRegressionAlgorithm", "log=True, default=1e-3) solver = CategoricalHyperparameter(name=\"solver\", choices=[\"sgd\", \"adam\"], default=\"sgd\") beta1 =", "random_state=None): self.number_updates = number_updates self.batch_size = batch_size self.dropout_output = dropout_output", "Cap the max number of possible epochs from implementation import", "number_updates, batch_size, dropout_output, learning_rate, solver, lambda2, momentum=0.99, beta1=0.9, beta2=0.9, rho=0.95,", "InCondition(child=gamma, parent=lr_policy, values=['inv', 'exp', 'step']) power_depends_on_policy = EqualsCondition(power, lr_policy, 'inv')", "110) # Cap the max number of possible epochs from", "l2 = UniformFloatHyperparameter(\"lambda2\", 1e-6, 1e-2, log=True, default=1e-3) solver = CategoricalHyperparameter(name=\"solver\",", "self.n_features = None self.input_shape = None self.m_issparse = False self.m_isregression", "= lambda2 self.momentum = momentum self.beta1 = 1-beta1 if beta1", "power = UniformFloatHyperparameter(\"power\", 0.0, 1.0, default=0.5) epoch_step = UniformIntegerHyperparameter(\"epoch_step\", 2,", "y): Xf, yf = self._prefit(X, y) epoch = (self.number_updates *", "max number of possible epochs from implementation import LogisticRegression self.estimator", "is None: raise NotImplementedError preds = self.estimator.predict(X, self.m_issparse) return preds", "self def predict(self, X): if self.estimator is None: raise NotImplementedError", "None: raise NotImplementedError preds = self.estimator.predict(X, self.m_issparse) return preds *", "= True self.m_isbinary = False self.m_ismultilabel = False self.estimator =", "self.mean_y def predict_proba(self, X): if self.estimator is None: raise NotImplementedError()", "LogisticRegression self.estimator = LogisticRegression.LogisticRegression(batch_size=self.batch_size, input_shape=self.input_shape, num_output_units=self.num_output_units, dropout_output=self.dropout_output, learning_rate=self.learning_rate, lr_policy=self.lr_policy, lambda2=self.lambda2,", "log=True, default=0.01) lr_policy = CategoricalHyperparameter(name=\"lr_policy\", choices=policy_choices, default='fixed') gamma = UniformFloatHyperparameter(name=\"gamma\",", "beta1 = UniformFloatHyperparameter(\"beta1\", 1e-4, 0.1, log=True, default=0.1) beta2 = UniformFloatHyperparameter(\"beta2\",", "= False self.m_ismultilabel = False self.estimator = None def _prefit(self,", "def predict_proba(self, X): if self.estimator is None: raise NotImplementedError() return", "= LogisticRegression.LogisticRegression(batch_size=self.batch_size, input_shape=self.input_shape, num_output_units=self.num_output_units, dropout_output=self.dropout_output, learning_rate=self.learning_rate, lr_policy=self.lr_policy, lambda2=self.lambda2, momentum=self.momentum, beta1=self.beta1,", "epoch_step_depends_on_policy = EqualsCondition(epoch_step, lr_policy, 'step') cs.add_condition(beta1_depends_on_solver) cs.add_condition(beta2_depends_on_solver) cs.add_condition(gamma_depends_on_policy) cs.add_condition(power_depends_on_policy) cs.add_condition(epoch_step_depends_on_policy)", "gamma self.power = power self.epoch_step = epoch_step # Empty features", "if self.estimator is None: raise NotImplementedError() return self.estimator.predict_proba(X, self.m_issparse) @staticmethod", "EqualsCondition, InCondition from HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter, \\ UniformIntegerHyperparameter, CategoricalHyperparameter, Constant", "y) epoch = (self.number_updates * self.batch_size)//X.shape[0] number_epochs = min(max(2, epoch),", "= None def _prefit(self, X, y): self.batch_size = int(self.batch_size) self.n_features", "np import scipy.sparse as sp from HPOlibConfigSpace.configuration_space import ConfigurationSpace from", "cs.add_hyperparameter(gamma) cs.add_hyperparameter(power) cs.add_hyperparameter(epoch_step) beta1_depends_on_solver = EqualsCondition(beta1, solver, \"adam\") beta2_depends_on_solver =", "autosklearn.pipeline.components.base import AutoSklearnRegressionAlgorithm from autosklearn.pipeline.constants import * class LinReg(AutoSklearnRegressionAlgorithm): def", "0.99, default=0.5) lr = UniformFloatHyperparameter(\"learning_rate\", 1e-6, 0.1, log=True, default=0.01) l2", "'inv') epoch_step_depends_on_policy = EqualsCondition(epoch_step, lr_policy, 'step') cs.add_condition(beta1_depends_on_solver) cs.add_condition(beta2_depends_on_solver) cs.add_condition(gamma_depends_on_policy) cs.add_condition(power_depends_on_policy)", "cs.add_hyperparameter(epoch_step) beta1_depends_on_solver = EqualsCondition(beta1, solver, \"adam\") beta2_depends_on_solver = EqualsCondition(beta2, solver,", "self.estimator.predict(X, self.m_issparse) return preds * self.std_y + self.mean_y def predict_proba(self,", "LinReg(AutoSklearnRegressionAlgorithm): def __init__(self, number_updates, batch_size, dropout_output, learning_rate, solver, lambda2, momentum=0.99,", "def __init__(self, number_updates, batch_size, dropout_output, learning_rate, solver, lambda2, momentum=0.99, beta1=0.9,", "import scipy.sparse as sp from HPOlibConfigSpace.configuration_space import ConfigurationSpace from HPOlibConfigSpace.conditions", "CategoricalHyperparameter, Constant from autosklearn.pipeline.components.base import AutoSklearnRegressionAlgorithm from autosklearn.pipeline.constants import *", "self.estimator.predict_proba(X, self.m_issparse) @staticmethod def get_properties(dataset_properties=None): return {'shortname': 'lin_reg', 'name': 'Linear", "NotImplementedError() return self.estimator.predict_proba(X, self.m_issparse) @staticmethod def get_properties(dataset_properties=None): return {'shortname': 'lin_reg',", "y def fit(self, X, y): Xf, yf = self._prefit(X, y)", "the max number of possible epochs from implementation import LogisticRegression", "(PREDICTIONS,)} @staticmethod def get_hyperparameter_search_space(dataset_properties=None): policy_choices = ['fixed', 'inv', 'exp', 'step']", "cs.add_hyperparameter(number_updates) cs.add_hyperparameter(batch_size) cs.add_hyperparameter(dropout_output) cs.add_hyperparameter(lr) cs.add_hyperparameter(l2) cs.add_hyperparameter(solver) cs.add_hyperparameter(beta1) cs.add_hyperparameter(beta2) cs.add_hyperparameter(lr_policy) cs.add_hyperparameter(gamma)", "momentum=self.momentum, beta1=self.beta1, beta2=self.beta2, rho=self.rho, solver=self.solver, num_epochs=number_epochs, gamma=self.gamma, power=self.power, epoch_step=self.epoch_step, is_sparse=self.m_issparse,", "True, 'handles_classification': False, 'handles_multiclass': False, 'handles_multilabel': False, 'is_deterministic': True, 'input':", "EqualsCondition(power, lr_policy, 'inv') epoch_step_depends_on_policy = EqualsCondition(epoch_step, lr_policy, 'step') cs.add_condition(beta1_depends_on_solver) cs.add_condition(beta2_depends_on_solver)", "self.batch_size = batch_size self.dropout_output = dropout_output self.learning_rate = learning_rate self.lr_policy", "= number_updates self.batch_size = batch_size self.dropout_output = dropout_output self.learning_rate =", "rho self.solver = solver self.gamma = gamma self.power = power", "0.1, log=True, default=0.1) beta2 = UniformFloatHyperparameter(\"beta2\", 1e-4, 0.1, log=True, default=0.01)", "= solver self.gamma = gamma self.power = power self.epoch_step =" ]
[ "10 points!') elif alien_color == 'red': print('Congratulations! You won 15", "== 'green': print('Congratulations! You won 5 points!') elif alien_color ==", "Creating a elif chain alien_color = 'red' if alien_color ==", "print('Congratulations! You won 5 points!') elif alien_color == 'yellow': print('Congratulations!", "won 5 points!') elif alien_color == 'yellow': print('Congratulations! You won", "alien_color == 'green': print('Congratulations! You won 5 points!') elif alien_color", "a elif chain alien_color = 'red' if alien_color == 'green':", "if alien_color == 'green': print('Congratulations! You won 5 points!') elif", "points!') elif alien_color == 'red': print('Congratulations! You won 15 points!')", "points!') elif alien_color == 'yellow': print('Congratulations! You won 10 points!')", "'red' if alien_color == 'green': print('Congratulations! You won 5 points!')", "You won 5 points!') elif alien_color == 'yellow': print('Congratulations! You", "alien_color == 'yellow': print('Congratulations! You won 10 points!') elif alien_color", "chain alien_color = 'red' if alien_color == 'green': print('Congratulations! You", "= 'red' if alien_color == 'green': print('Congratulations! You won 5", "'green': print('Congratulations! You won 5 points!') elif alien_color == 'yellow':", "You won 10 points!') elif alien_color == 'red': print('Congratulations! You", "# Creating a elif chain alien_color = 'red' if alien_color", "elif chain alien_color = 'red' if alien_color == 'green': print('Congratulations!", "== 'yellow': print('Congratulations! You won 10 points!') elif alien_color ==", "won 10 points!') elif alien_color == 'red': print('Congratulations! You won", "alien_color = 'red' if alien_color == 'green': print('Congratulations! You won", "<filename>python_work/Chapter5/exe3_alien_color.py # Creating a elif chain alien_color = 'red' if", "'yellow': print('Congratulations! You won 10 points!') elif alien_color == 'red':", "5 points!') elif alien_color == 'yellow': print('Congratulations! You won 10", "print('Congratulations! You won 10 points!') elif alien_color == 'red': print('Congratulations!", "elif alien_color == 'yellow': print('Congratulations! You won 10 points!') elif" ]
[ "plt.grid(True) plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color=\"r\")", "np.mean(train_scores, axis=1) train_std = np.std(train_scores, axis=1) test_mean = np.mean(test_scores, axis=1)", "import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection", "score') plt.fill_between(param_range, test_mean + test_std, test_mean - test_std, alpha=0.15, color='g')", "as pd import numpy as np import seaborn as sns", "train_scores, test_scores = validation_curve(estimator, X, y, param_name, param_range, cv) train_mean", "test_scores_mean + test_scores_std, alpha=0.1, color=\"g\") plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\", label=\"Training", "test_std = np.std(test_scores, axis=1) plt.plot(param_range, train_mean, color='r', marker='o', markersize=5, label='Training", "examples\") plt.ylabel(\"Score\") train_sizes, train_scores, test_scores = learning_curve( estimator, X, y,", "plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color=\"r\") plt.fill_between(train_sizes,", "train_scores, test_scores = learning_curve( estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)", "np.std(test_scores, axis=1) plt.grid(True) plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std,", "return plt # Plot validation curve def plot_validation_curve(estimator, title, X,", "- train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color=\"r\") plt.fill_between(train_sizes, test_scores_mean -", "y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std =", "+ test_scores_std, alpha=0.1, color=\"g\") plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\", label=\"Training score\")", "color='r', marker='o', markersize=5, label='Training score') plt.fill_between(param_range, train_mean + train_std, train_mean", "plt.plot(param_range, train_mean, color='r', marker='o', markersize=5, label='Training score') plt.fill_between(param_range, train_mean +", "test_mean = np.mean(test_scores, axis=1) test_std = np.std(test_scores, axis=1) plt.plot(param_range, train_mean,", "plt.fill_between(param_range, train_mean + train_std, train_mean - train_std, alpha=0.15, color='r') plt.plot(param_range,", "axis=1) test_std = np.std(test_scores, axis=1) plt.plot(param_range, train_mean, color='r', marker='o', markersize=5,", "+ train_std, train_mean - train_std, alpha=0.15, color='r') plt.plot(param_range, test_mean, color='g',", "plt.show() return plt # Plot validation curve def plot_validation_curve(estimator, title,", "linestyle='--', marker='s', markersize=5, label='Validation score') plt.fill_between(param_range, test_mean + test_std, test_mean", "seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import", "validation curve def plot_validation_curve(estimator, title, X, y, param_name, param_range, ylim=None,", "= validation_curve(estimator, X, y, param_name, param_range, cv) train_mean = np.mean(train_scores,", "learning_curve # Plot learning curve def plot_learning_curve(estimator, title, X, y,", "= np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid(True) plt.fill_between(train_sizes, train_scores_mean", "def plot_validation_curve(estimator, title, X, y, param_name, param_range, ylim=None, cv=None, n_jobs=1,", "train_mean + train_std, train_mean - train_std, alpha=0.15, color='r') plt.plot(param_range, test_mean,", "train_scores_mean + train_scores_std, alpha=0.1, color=\"r\") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean", "Plot learning curve def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,", "Plot validation curve def plot_validation_curve(estimator, title, X, y, param_name, param_range,", "test_mean + test_std, test_mean - test_std, alpha=0.15, color='g') plt.grid(True) plt.xscale('log')", "test_scores_std, alpha=0.1, color=\"g\") plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\", label=\"Training score\") plt.plot(train_sizes,", "train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color=\"r\") plt.fill_between(train_sizes, test_scores_mean", "np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1)", "- train_std, alpha=0.15, color='r') plt.plot(param_range, test_mean, color='g', linestyle='--', marker='s', markersize=5,", "5)): plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel(\"Training", "plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\", label=\"Training score\") plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",", "test_scores = validation_curve(estimator, X, y, param_name, param_range, cv) train_mean =", "= np.std(train_scores, axis=1) test_mean = np.mean(test_scores, axis=1) test_std = np.std(test_scores,", "marker='o', markersize=5, label='Training score') plt.fill_between(param_range, train_mean + train_std, train_mean -", "plt.plot(param_range, test_mean, color='g', linestyle='--', marker='s', markersize=5, label='Validation score') plt.fill_between(param_range, test_mean", "axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid(True)", "train_sizes=np.linspace(.1, 1.0, 5)): plt.figure() plt.title(title) if ylim is not None:", "alpha=0.1, color=\"r\") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1,", "curve def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1,", "label=\"Training score\") plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\", label=\"Validation score\") plt.legend(loc=\"best\") plt.show()", "alpha=0.1, color=\"g\") plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\", label=\"Training score\") plt.plot(train_sizes, test_scores_mean,", "label='Training score') plt.fill_between(param_range, train_mean + train_std, train_mean - train_std, alpha=0.15,", "# Plot learning curve def plot_learning_curve(estimator, title, X, y, ylim=None,", "ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): train_scores, test_scores = validation_curve(estimator,", "train_std, train_mean - train_std, alpha=0.15, color='r') plt.plot(param_range, test_mean, color='g', linestyle='--',", "train_mean, color='r', marker='o', markersize=5, label='Training score') plt.fill_between(param_range, train_mean + train_std,", "title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): plt.figure()", "np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid(True) plt.fill_between(train_sizes, train_scores_mean -", "color=\"g\", label=\"Validation score\") plt.legend(loc=\"best\") plt.show() return plt # Plot validation", "from sklearn.model_selection import learning_curve # Plot learning curve def plot_learning_curve(estimator,", "y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): plt.figure() plt.title(title) if", "n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1)", "train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=cv, n_jobs=n_jobs,", "pandas as pd import numpy as np import seaborn as", "np import seaborn as sns import matplotlib.pyplot as plt from", "as sns import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve", "'o-', color=\"r\", label=\"Training score\") plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\", label=\"Validation score\")", "train_std = np.std(train_scores, axis=1) test_mean = np.mean(test_scores, axis=1) test_std =", "X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std", "plt.xlabel(\"Training examples\") plt.ylabel(\"Score\") train_sizes, train_scores, test_scores = learning_curve( estimator, X,", "train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean", "plot_validation_curve(estimator, title, X, y, param_name, param_range, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1,", "matplotlib.pyplot as plt from sklearn.model_selection import learning_curve # Plot learning", "= np.mean(test_scores, axis=1) test_std = np.std(test_scores, axis=1) plt.plot(param_range, train_mean, color='r',", "train_mean - train_std, alpha=0.15, color='r') plt.plot(param_range, test_mean, color='g', linestyle='--', marker='s',", "- test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color=\"g\") plt.plot(train_sizes, train_scores_mean, 'o-',", "alpha=0.15, color='r') plt.plot(param_range, test_mean, color='g', linestyle='--', marker='s', markersize=5, label='Validation score')", "import learning_curve # Plot learning curve def plot_learning_curve(estimator, title, X,", "color=\"r\") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")", "test_scores_mean, 'o-', color=\"g\", label=\"Validation score\") plt.legend(loc=\"best\") plt.show() return plt #", "param_name, param_range, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): train_scores, test_scores", "test_mean - test_std, alpha=0.15, color='g') plt.grid(True) plt.xscale('log') plt.legend(loc='best') plt.xlabel('Parameter') plt.ylabel('Score')", "color='r') plt.plot(param_range, test_mean, color='g', linestyle='--', marker='s', markersize=5, label='Validation score') plt.fill_between(param_range,", "train_sizes=np.linspace(.1, 1.0, 5)): train_scores, test_scores = validation_curve(estimator, X, y, param_name,", "plt.fill_between(param_range, test_mean + test_std, test_mean - test_std, alpha=0.15, color='g') plt.grid(True)", "X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): plt.figure() plt.title(title)", "test_std, test_mean - test_std, alpha=0.15, color='g') plt.grid(True) plt.xscale('log') plt.legend(loc='best') plt.xlabel('Parameter')", "cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): train_scores, test_scores = validation_curve(estimator, X,", "'o-', color=\"g\", label=\"Validation score\") plt.legend(loc=\"best\") plt.show() return plt # Plot", "plt.ylim(*ylim) plt.xlabel(\"Training examples\") plt.ylabel(\"Score\") train_sizes, train_scores, test_scores = learning_curve( estimator,", "plt # Plot validation curve def plot_validation_curve(estimator, title, X, y,", "np.std(train_scores, axis=1) test_mean = np.mean(test_scores, axis=1) test_std = np.std(test_scores, axis=1)", "# Plot validation curve def plot_validation_curve(estimator, title, X, y, param_name,", "cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores,", "curve def plot_validation_curve(estimator, title, X, y, param_name, param_range, ylim=None, cv=None,", "test_scores_std = np.std(test_scores, axis=1) plt.grid(True) plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean", "plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\", label=\"Validation score\") plt.legend(loc=\"best\") plt.show() return plt", "y, param_name, param_range, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): train_scores,", "train_std, alpha=0.15, color='r') plt.plot(param_range, test_mean, color='g', linestyle='--', marker='s', markersize=5, label='Validation", "n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): plt.figure() plt.title(title) if ylim is not", "test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color=\"g\") plt.plot(train_sizes, train_scores_mean,", "y, param_name, param_range, cv) train_mean = np.mean(train_scores, axis=1) train_std =", "axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid(True) plt.fill_between(train_sizes, train_scores_mean - train_scores_std,", "numpy as np import seaborn as sns import matplotlib.pyplot as", "= np.std(test_scores, axis=1) plt.plot(param_range, train_mean, color='r', marker='o', markersize=5, label='Training score')", "as np import seaborn as sns import matplotlib.pyplot as plt", "ylim is not None: plt.ylim(*ylim) plt.xlabel(\"Training examples\") plt.ylabel(\"Score\") train_sizes, train_scores,", "not None: plt.ylim(*ylim) plt.xlabel(\"Training examples\") plt.ylabel(\"Score\") train_sizes, train_scores, test_scores =", "test_mean, color='g', linestyle='--', marker='s', markersize=5, label='Validation score') plt.fill_between(param_range, test_mean +", "axis=1) plt.plot(param_range, train_mean, color='r', marker='o', markersize=5, label='Training score') plt.fill_between(param_range, train_mean", "np.mean(test_scores, axis=1) test_std = np.std(test_scores, axis=1) plt.plot(param_range, train_mean, color='r', marker='o',", "5)): train_scores, test_scores = validation_curve(estimator, X, y, param_name, param_range, cv)", "X, y, param_name, param_range, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):", "= np.mean(train_scores, axis=1) train_std = np.std(train_scores, axis=1) test_mean = np.mean(test_scores,", "if ylim is not None: plt.ylim(*ylim) plt.xlabel(\"Training examples\") plt.ylabel(\"Score\") train_sizes,", "score\") plt.legend(loc=\"best\") plt.show() return plt # Plot validation curve def", "param_name, param_range, cv) train_mean = np.mean(train_scores, axis=1) train_std = np.std(train_scores,", "np.std(test_scores, axis=1) plt.plot(param_range, train_mean, color='r', marker='o', markersize=5, label='Training score') plt.fill_between(param_range,", "sns import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve #", "score') plt.fill_between(param_range, train_mean + train_std, train_mean - train_std, alpha=0.15, color='r')", "train_scores_mean, 'o-', color=\"r\", label=\"Training score\") plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\", label=\"Validation", "= learning_curve( estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean =", "test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color=\"g\") plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",", "marker='s', markersize=5, label='Validation score') plt.fill_between(param_range, test_mean + test_std, test_mean -", "title, X, y, param_name, param_range, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0,", "param_range, cv) train_mean = np.mean(train_scores, axis=1) train_std = np.std(train_scores, axis=1)", "as plt from sklearn.model_selection import learning_curve # Plot learning curve", "n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): train_scores, test_scores = validation_curve(estimator, X, y,", "import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve # Plot", "markersize=5, label='Training score') plt.fill_between(param_range, train_mean + train_std, train_mean - train_std,", "sklearn.model_selection import learning_curve # Plot learning curve def plot_learning_curve(estimator, title,", "train_scores_std, alpha=0.1, color=\"r\") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std,", "plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel(\"Training examples\")", "import numpy as np import seaborn as sns import matplotlib.pyplot", "1.0, 5)): plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim)", "score\") plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\", label=\"Validation score\") plt.legend(loc=\"best\") plt.show() return", "axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std", "= np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores,", "color=\"g\") plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\", label=\"Training score\") plt.plot(train_sizes, test_scores_mean, 'o-',", "ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): plt.figure() plt.title(title) if ylim", "color=\"r\", label=\"Training score\") plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\", label=\"Validation score\") plt.legend(loc=\"best\")", "1.0, 5)): train_scores, test_scores = validation_curve(estimator, X, y, param_name, param_range,", "np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1)", "import pandas as pd import numpy as np import seaborn", "plt.legend(loc=\"best\") plt.show() return plt # Plot validation curve def plot_validation_curve(estimator,", "param_range, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): train_scores, test_scores =", "label='Validation score') plt.fill_between(param_range, test_mean + test_std, test_mean - test_std, alpha=0.15,", "test_scores = learning_curve( estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean", "axis=1) train_std = np.std(train_scores, axis=1) test_mean = np.mean(test_scores, axis=1) test_std", "plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color=\"g\") plt.plot(train_sizes,", "+ train_scores_std, alpha=0.1, color=\"r\") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean +", "def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0,", "learning_curve( estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores,", "pd import numpy as np import seaborn as sns import", "train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std =", "= np.std(test_scores, axis=1) plt.grid(True) plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean +", "train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean =", "axis=1) plt.grid(True) plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1,", "plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel(\"Training examples\") plt.ylabel(\"Score\")", "cv) train_mean = np.mean(train_scores, axis=1) train_std = np.std(train_scores, axis=1) test_mean", "color='g', linestyle='--', marker='s', markersize=5, label='Validation score') plt.fill_between(param_range, test_mean + test_std,", "plt.ylabel(\"Score\") train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=cv,", "None: plt.ylim(*ylim) plt.xlabel(\"Training examples\") plt.ylabel(\"Score\") train_sizes, train_scores, test_scores = learning_curve(", "test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid(True) plt.fill_between(train_sizes,", "X, y, param_name, param_range, cv) train_mean = np.mean(train_scores, axis=1) train_std", "axis=1) test_mean = np.mean(test_scores, axis=1) test_std = np.std(test_scores, axis=1) plt.plot(param_range,", "train_mean = np.mean(train_scores, axis=1) train_std = np.std(train_scores, axis=1) test_mean =", "cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): plt.figure() plt.title(title) if ylim is", "label=\"Validation score\") plt.legend(loc=\"best\") plt.show() return plt # Plot validation curve", "- test_std, alpha=0.15, color='g') plt.grid(True) plt.xscale('log') plt.legend(loc='best') plt.xlabel('Parameter') plt.ylabel('Score') plt.ylim(ylim)", "+ test_std, test_mean - test_std, alpha=0.15, color='g') plt.grid(True) plt.xscale('log') plt.legend(loc='best')", "markersize=5, label='Validation score') plt.fill_between(param_range, test_mean + test_std, test_mean - test_std,", "is not None: plt.ylim(*ylim) plt.xlabel(\"Training examples\") plt.ylabel(\"Score\") train_sizes, train_scores, test_scores", "train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color=\"r\") plt.fill_between(train_sizes, test_scores_mean - test_scores_std,", "= np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores,", "plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):", "validation_curve(estimator, X, y, param_name, param_range, cv) train_mean = np.mean(train_scores, axis=1)", "plt from sklearn.model_selection import learning_curve # Plot learning curve def", "estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1)", "learning curve def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1," ]
[ "for downloading comsumption data from Oomi.\"\"\" from oomi.oomi_downloader import OomiDownloader,", "\"\"\"Utilities for downloading comsumption data from Oomi.\"\"\" from oomi.oomi_downloader import", "downloading comsumption data from Oomi.\"\"\" from oomi.oomi_downloader import OomiDownloader, OomiConfig" ]
[ "return self.SupportedBootModes def SetHelpString(self, HelpString): self.HelpString = HelpString def GetHelpString(self):", "self.Usage = '' def SetEventType(self, EventType): self.EventType = EventType def", "return self.HobType def SetUsage(self, Usage): self.Usage = Usage def GetUsage(self):", "GetSpecialComments(self): return self.SpecialComments ## ErrorInInf # # An encapsulate of", "__init__(self): self.SpecialComments = Sdict() InfSectionCommonDef.__init__(self) def SetSpecialComments(self, SepcialSectionList = None,", "SetSpecialComments(self, SepcialSectionList = None, Type = ''): if Type ==", "ErrorInInf # # An encapsulate of Error for INF parser.", "RaiseError=True): if ErrorCode is None: ErrorCode = ToolError.FORMAT_INVALID if LineInfo", "= '' def SetHobType(self, HobType): self.HobType = HobType def GetHobType(self):", "(c) 2011 - 2018, Intel Corporation. All rights reserved.<BR> #", "Usage def GetUsage(self): return self.Usage def SetSupArchList(self, ArchList): self.SupArchList =", "return self.SupArchList def SetHelpString(self, HelpString): self.HelpString = HelpString def GetHelpString(self):", "= ObjList else: ObjList = [] ObjList.append(Item) self.SpecialComments[Type] = ObjList", "# # Copyright (c) 2011 - 2018, Intel Corporation. All", "= HelpString def GetHelpString(self): return self.HelpString def SetUsage(self, Usage): self.Usage", "'' self.Usage = '' self.SupArchList = [] self.HelpString = ''", "InfParser. # # Copyright (c) 2011 - 2018, Intel Corporation.", "as DT from Object.Parser.InfCommonObject import InfSectionCommonDef from Library.Misc import Sdict", "import InfSectionCommonDef from Library.Misc import Sdict ## # BootModeObject #", "Intel Corporation. All rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent '''", "GetHobType(self): return self.HobType def SetUsage(self, Usage): self.Usage = Usage def", "== DT.TYPE_EVENT_SECTION or \\ Type == DT.TYPE_BOOTMODE_SECTION: for Item in", "for INF parser. # def ErrorInInf(Message=None, ErrorCode=None, LineInfo=None, RaiseError=True): if", "'' self.SupArchList = [] self.HelpString = '' def SetHobType(self, HobType):", "self.SupportedBootModes = SupportedBootModes def GetSupportedBootModes(self): return self.SupportedBootModes def SetHelpString(self, HelpString):", "= Usage def GetUsage(self): return self.Usage def SetSupArchList(self, ArchList): self.SupArchList", "LineInfo is None: LineInfo = ['', -1, ''] Logger.Error(\"InfParser\", ErrorCode,", "GetSupportedBootModes(self): return self.SupportedBootModes def SetHelpString(self, HelpString): self.HelpString = HelpString def", "class InfEventObject(): def __init__(self): self.EventType = '' self.HelpString = ''", "parser. # def ErrorInInf(Message=None, ErrorCode=None, LineInfo=None, RaiseError=True): if ErrorCode is", "if Type in self.SpecialComments: ObjList = self.SpecialComments[Type] ObjList.append(Item) self.SpecialComments[Type] =", "InfMisc ''' import Logger.Log as Logger from Logger import ToolError", "# class InfHobObject(): def __init__(self): self.HobType = '' self.Usage =", "import Sdict ## # BootModeObject # class InfBootModeObject(): def __init__(self):", "self.HelpString = '' self.Usage = '' def SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes", "def SetUsage(self, Usage): self.Usage = Usage def GetUsage(self): return self.Usage", "self.Usage = '' self.SupArchList = [] self.HelpString = '' def", "InfSectionCommonDef from Library.Misc import Sdict ## # BootModeObject # class", "# Copyright (c) 2011 - 2018, Intel Corporation. All rights", "of Error for INF parser. # def ErrorInInf(Message=None, ErrorCode=None, LineInfo=None,", "= EventType def GetEventType(self): return self.EventType def SetHelpString(self, HelpString): self.HelpString", "class InfSpecialCommentObject(InfSectionCommonDef): def __init__(self): self.SpecialComments = Sdict() InfSectionCommonDef.__init__(self) def SetSpecialComments(self,", "self.Usage = Usage def GetUsage(self): return self.Usage ## # HobObject", "None: ErrorCode = ToolError.FORMAT_INVALID if LineInfo is None: LineInfo =", "class objects of INF file miscellaneous. # Include BootMode/HOB/Event and", "Sdict ## # BootModeObject # class InfBootModeObject(): def __init__(self): self.SupportedBootModes", "SetUsage(self, Usage): self.Usage = Usage def GetUsage(self): return self.Usage def", "SetEventType(self, EventType): self.EventType = EventType def GetEventType(self): return self.EventType def", "consumed by InfParser. # # Copyright (c) 2011 - 2018,", "self.Usage def SetSupArchList(self, ArchList): self.SupArchList = ArchList def GetSupArchList(self): return", "Sdict() InfSectionCommonDef.__init__(self) def SetSpecialComments(self, SepcialSectionList = None, Type = ''):", "class InfHobObject(): def __init__(self): self.HobType = '' self.Usage = ''", "def GetHelpString(self): return self.HelpString ## # InfSpecialCommentObject # class InfSpecialCommentObject(InfSectionCommonDef):", "= '' self.Usage = '' def SetEventType(self, EventType): self.EventType =", "from Logger import ToolError from Library import DataType as DT", "'' self.HelpString = '' self.Usage = '' def SetEventType(self, EventType):", "SPDX-License-Identifier: BSD-2-Clause-Patent ''' InfMisc ''' import Logger.Log as Logger from", "self.HelpString def SetUsage(self, Usage): self.Usage = Usage def GetUsage(self): return", "DT from Object.Parser.InfCommonObject import InfSectionCommonDef from Library.Misc import Sdict ##", "= ['', -1, ''] Logger.Error(\"InfParser\", ErrorCode, Message=Message, File=LineInfo[0], Line=LineInfo[1], ExtraData=LineInfo[2],", "self.EventType def SetHelpString(self, HelpString): self.HelpString = HelpString def GetHelpString(self): return", "return self.SpecialComments ## ErrorInInf # # An encapsulate of Error", "self.SupArchList = [] self.HelpString = '' def SetHobType(self, HobType): self.HobType", "Type = ''): if Type == DT.TYPE_HOB_SECTION or \\ Type", "ObjList.append(Item) self.SpecialComments[Type] = ObjList else: ObjList = [] ObjList.append(Item) self.SpecialComments[Type]", "ObjList else: ObjList = [] ObjList.append(Item) self.SpecialComments[Type] = ObjList return", "# HobObject # class InfHobObject(): def __init__(self): self.HobType = ''", "HelpString def GetHelpString(self): return self.HelpString def SetUsage(self, Usage): self.Usage =", "= ObjList return True def GetSpecialComments(self): return self.SpecialComments ## ErrorInInf", "def GetEventType(self): return self.EventType def SetHelpString(self, HelpString): self.HelpString = HelpString", "self.HelpString ## # InfSpecialCommentObject # class InfSpecialCommentObject(InfSectionCommonDef): def __init__(self): self.SpecialComments", "['', -1, ''] Logger.Error(\"InfParser\", ErrorCode, Message=Message, File=LineInfo[0], Line=LineInfo[1], ExtraData=LineInfo[2], RaiseError=RaiseError)", "All rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent ''' InfMisc '''", "Usage def GetUsage(self): return self.Usage ## # EventObject # class", "ObjList = [] ObjList.append(Item) self.SpecialComments[Type] = ObjList return True def", "2018, Intel Corporation. All rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent", "= SupportedBootModes def GetSupportedBootModes(self): return self.SupportedBootModes def SetHelpString(self, HelpString): self.HelpString", "as Logger from Logger import ToolError from Library import DataType", "None: LineInfo = ['', -1, ''] Logger.Error(\"InfParser\", ErrorCode, Message=Message, File=LineInfo[0],", "Corporation. All rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent ''' InfMisc", "self.EventType = EventType def GetEventType(self): return self.EventType def SetHelpString(self, HelpString):", "# class InfSpecialCommentObject(InfSectionCommonDef): def __init__(self): self.SpecialComments = Sdict() InfSectionCommonDef.__init__(self) def", "LineInfo=None, RaiseError=True): if ErrorCode is None: ErrorCode = ToolError.FORMAT_INVALID if", "HobType def GetHobType(self): return self.HobType def SetUsage(self, Usage): self.Usage =", "Type in self.SpecialComments: ObjList = self.SpecialComments[Type] ObjList.append(Item) self.SpecialComments[Type] = ObjList", "by InfParser. # # Copyright (c) 2011 - 2018, Intel", "= '' self.HelpString = '' self.Usage = '' def SetSupportedBootModes(self,", "ObjList = self.SpecialComments[Type] ObjList.append(Item) self.SpecialComments[Type] = ObjList else: ObjList =", "self.SpecialComments[Type] = ObjList return True def GetSpecialComments(self): return self.SpecialComments ##", "file is used to define class objects of INF file", "in SepcialSectionList: if Type in self.SpecialComments: ObjList = self.SpecialComments[Type] ObjList.append(Item)", "def SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes = SupportedBootModes def GetSupportedBootModes(self): return self.SupportedBootModes", "__init__(self): self.EventType = '' self.HelpString = '' self.Usage = ''", "'' self.Usage = '' def SetEventType(self, EventType): self.EventType = EventType", "def GetSupportedBootModes(self): return self.SupportedBootModes def SetHelpString(self, HelpString): self.HelpString = HelpString", "This file is used to define class objects of INF", "SetHelpString(self, HelpString): self.HelpString = HelpString def GetHelpString(self): return self.HelpString ##", "# Include BootMode/HOB/Event and others. It will consumed by InfParser.", "= ArchList def GetSupArchList(self): return self.SupArchList def SetHelpString(self, HelpString): self.HelpString", "def __init__(self): self.EventType = '' self.HelpString = '' self.Usage =", "# # An encapsulate of Error for INF parser. #", "def __init__(self): self.SupportedBootModes = '' self.HelpString = '' self.Usage =", "SupportedBootModes def GetSupportedBootModes(self): return self.SupportedBootModes def SetHelpString(self, HelpString): self.HelpString =", "It will consumed by InfParser. # # Copyright (c) 2011", "GetUsage(self): return self.Usage def SetSupArchList(self, ArchList): self.SupArchList = ArchList def", "self.SupArchList = ArchList def GetSupArchList(self): return self.SupArchList def SetHelpString(self, HelpString):", "rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent ''' InfMisc ''' import", "INF parser. # def ErrorInInf(Message=None, ErrorCode=None, LineInfo=None, RaiseError=True): if ErrorCode", "GetSupArchList(self): return self.SupArchList def SetHelpString(self, HelpString): self.HelpString = HelpString def", "ErrorInInf(Message=None, ErrorCode=None, LineInfo=None, RaiseError=True): if ErrorCode is None: ErrorCode =", "Logger.Log as Logger from Logger import ToolError from Library import", "= Sdict() InfSectionCommonDef.__init__(self) def SetSpecialComments(self, SepcialSectionList = None, Type =", "return self.EventType def SetHelpString(self, HelpString): self.HelpString = HelpString def GetHelpString(self):", "## @file # This file is used to define class", "= HelpString def GetHelpString(self): return self.HelpString ## # InfSpecialCommentObject #", "BSD-2-Clause-Patent ''' InfMisc ''' import Logger.Log as Logger from Logger", "## # EventObject # class InfEventObject(): def __init__(self): self.EventType =", "Type == DT.TYPE_BOOTMODE_SECTION: for Item in SepcialSectionList: if Type in", "if LineInfo is None: LineInfo = ['', -1, ''] Logger.Error(\"InfParser\",", "[] self.HelpString = '' def SetHobType(self, HobType): self.HobType = HobType", "DT.TYPE_EVENT_SECTION or \\ Type == DT.TYPE_BOOTMODE_SECTION: for Item in SepcialSectionList:", "InfSectionCommonDef.__init__(self) def SetSpecialComments(self, SepcialSectionList = None, Type = ''): if", "== DT.TYPE_BOOTMODE_SECTION: for Item in SepcialSectionList: if Type in self.SpecialComments:", "ObjList.append(Item) self.SpecialComments[Type] = ObjList return True def GetSpecialComments(self): return self.SpecialComments", "Item in SepcialSectionList: if Type in self.SpecialComments: ObjList = self.SpecialComments[Type]", "SetSupArchList(self, ArchList): self.SupArchList = ArchList def GetSupArchList(self): return self.SupArchList def", "# An encapsulate of Error for INF parser. # def", "InfSpecialCommentObject(InfSectionCommonDef): def __init__(self): self.SpecialComments = Sdict() InfSectionCommonDef.__init__(self) def SetSpecialComments(self, SepcialSectionList", "import ToolError from Library import DataType as DT from Object.Parser.InfCommonObject", "reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent ''' InfMisc ''' import Logger.Log", "\\ Type == DT.TYPE_BOOTMODE_SECTION: for Item in SepcialSectionList: if Type", "Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>", "DT.TYPE_BOOTMODE_SECTION: for Item in SepcialSectionList: if Type in self.SpecialComments: ObjList", "DataType as DT from Object.Parser.InfCommonObject import InfSectionCommonDef from Library.Misc import", "self.HelpString = HelpString def GetHelpString(self): return self.HelpString def SetUsage(self, Usage):", "in self.SpecialComments: ObjList = self.SpecialComments[Type] ObjList.append(Item) self.SpecialComments[Type] = ObjList else:", "= ''): if Type == DT.TYPE_HOB_SECTION or \\ Type ==", "2011 - 2018, Intel Corporation. All rights reserved.<BR> # #", "return self.Usage ## # HobObject # class InfHobObject(): def __init__(self):", "used to define class objects of INF file miscellaneous. #", "= [] ObjList.append(Item) self.SpecialComments[Type] = ObjList return True def GetSpecialComments(self):", "'' self.Usage = '' def SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes = SupportedBootModes", "HelpString def GetHelpString(self): return self.HelpString ## # InfSpecialCommentObject # class", "return self.HelpString ## # InfSpecialCommentObject # class InfSpecialCommentObject(InfSectionCommonDef): def __init__(self):", "# def ErrorInInf(Message=None, ErrorCode=None, LineInfo=None, RaiseError=True): if ErrorCode is None:", "miscellaneous. # Include BootMode/HOB/Event and others. It will consumed by", "# class InfBootModeObject(): def __init__(self): self.SupportedBootModes = '' self.HelpString =", "## # InfSpecialCommentObject # class InfSpecialCommentObject(InfSectionCommonDef): def __init__(self): self.SpecialComments =", "Library import DataType as DT from Object.Parser.InfCommonObject import InfSectionCommonDef from", "[] ObjList.append(Item) self.SpecialComments[Type] = ObjList return True def GetSpecialComments(self): return", "= ToolError.FORMAT_INVALID if LineInfo is None: LineInfo = ['', -1,", "class InfBootModeObject(): def __init__(self): self.SupportedBootModes = '' self.HelpString = ''", "self.HelpString = '' self.Usage = '' def SetEventType(self, EventType): self.EventType", "self.HelpString = HelpString def GetHelpString(self): return self.HelpString ## # InfSpecialCommentObject", "= '' def SetEventType(self, EventType): self.EventType = EventType def GetEventType(self):", "INF file miscellaneous. # Include BootMode/HOB/Event and others. It will", "self.EventType = '' self.HelpString = '' self.Usage = '' def", "self.SpecialComments: ObjList = self.SpecialComments[Type] ObjList.append(Item) self.SpecialComments[Type] = ObjList else: ObjList", "self.SpecialComments[Type] ObjList.append(Item) self.SpecialComments[Type] = ObjList else: ObjList = [] ObjList.append(Item)", "self.SpecialComments ## ErrorInInf # # An encapsulate of Error for", "## ErrorInInf # # An encapsulate of Error for INF", "Logger import ToolError from Library import DataType as DT from", "Library.Misc import Sdict ## # BootModeObject # class InfBootModeObject(): def", "= HobType def GetHobType(self): return self.HobType def SetUsage(self, Usage): self.Usage", "Usage): self.Usage = Usage def GetUsage(self): return self.Usage ## #", "# SPDX-License-Identifier: BSD-2-Clause-Patent ''' InfMisc ''' import Logger.Log as Logger", "= Usage def GetUsage(self): return self.Usage ## # EventObject #", "ToolError.FORMAT_INVALID if LineInfo is None: LineInfo = ['', -1, '']", "def SetHobType(self, HobType): self.HobType = HobType def GetHobType(self): return self.HobType", "SetUsage(self, Usage): self.Usage = Usage def GetUsage(self): return self.Usage ##", "Include BootMode/HOB/Event and others. It will consumed by InfParser. #", "def GetUsage(self): return self.Usage def SetSupArchList(self, ArchList): self.SupArchList = ArchList", "Usage def GetUsage(self): return self.Usage ## # HobObject # class", "'' def SetEventType(self, EventType): self.EventType = EventType def GetEventType(self): return", "define class objects of INF file miscellaneous. # Include BootMode/HOB/Event", "encapsulate of Error for INF parser. # def ErrorInInf(Message=None, ErrorCode=None,", "## # BootModeObject # class InfBootModeObject(): def __init__(self): self.SupportedBootModes =", "self.Usage = Usage def GetUsage(self): return self.Usage ## # EventObject", "HobType): self.HobType = HobType def GetHobType(self): return self.HobType def SetUsage(self,", "ErrorCode is None: ErrorCode = ToolError.FORMAT_INVALID if LineInfo is None:", "# class InfEventObject(): def __init__(self): self.EventType = '' self.HelpString =", "Object.Parser.InfCommonObject import InfSectionCommonDef from Library.Misc import Sdict ## # BootModeObject", "EventObject # class InfEventObject(): def __init__(self): self.EventType = '' self.HelpString", "def GetUsage(self): return self.Usage ## # HobObject # class InfHobObject():", "self.HobType def SetUsage(self, Usage): self.Usage = Usage def GetUsage(self): return", "BootModeObject # class InfBootModeObject(): def __init__(self): self.SupportedBootModes = '' self.HelpString", "self.Usage = '' def SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes = SupportedBootModes def", "def GetUsage(self): return self.Usage ## # EventObject # class InfEventObject():", "GetEventType(self): return self.EventType def SetHelpString(self, HelpString): self.HelpString = HelpString def", "def SetSupArchList(self, ArchList): self.SupArchList = ArchList def GetSupArchList(self): return self.SupArchList", "self.SupArchList def SetHelpString(self, HelpString): self.HelpString = HelpString def GetHelpString(self): return", "Type == DT.TYPE_HOB_SECTION or \\ Type == DT.TYPE_EVENT_SECTION or \\", "\\ Type == DT.TYPE_EVENT_SECTION or \\ Type == DT.TYPE_BOOTMODE_SECTION: for", "HelpString): self.HelpString = HelpString def GetHelpString(self): return self.HelpString def SetUsage(self,", "'' def SetHobType(self, HobType): self.HobType = HobType def GetHobType(self): return", "# This file is used to define class objects of", "# # SPDX-License-Identifier: BSD-2-Clause-Patent ''' InfMisc ''' import Logger.Log as", "self.Usage ## # EventObject # class InfEventObject(): def __init__(self): self.EventType", "ArchList def GetSupArchList(self): return self.SupArchList def SetHelpString(self, HelpString): self.HelpString =", "will consumed by InfParser. # # Copyright (c) 2011 -", "return self.Usage ## # EventObject # class InfEventObject(): def __init__(self):", "LineInfo = ['', -1, ''] Logger.Error(\"InfParser\", ErrorCode, Message=Message, File=LineInfo[0], Line=LineInfo[1],", "objects of INF file miscellaneous. # Include BootMode/HOB/Event and others.", "import DataType as DT from Object.Parser.InfCommonObject import InfSectionCommonDef from Library.Misc", "else: ObjList = [] ObjList.append(Item) self.SpecialComments[Type] = ObjList return True", "of INF file miscellaneous. # Include BootMode/HOB/Event and others. It", "# InfSpecialCommentObject # class InfSpecialCommentObject(InfSectionCommonDef): def __init__(self): self.SpecialComments = Sdict()", "InfBootModeObject(): def __init__(self): self.SupportedBootModes = '' self.HelpString = '' self.Usage", "# EventObject # class InfEventObject(): def __init__(self): self.EventType = ''", "= None, Type = ''): if Type == DT.TYPE_HOB_SECTION or", "SetHelpString(self, HelpString): self.HelpString = HelpString def GetHelpString(self): return self.HelpString def", "ToolError from Library import DataType as DT from Object.Parser.InfCommonObject import", "ObjList return True def GetSpecialComments(self): return self.SpecialComments ## ErrorInInf #", "# BootModeObject # class InfBootModeObject(): def __init__(self): self.SupportedBootModes = ''", "def GetHobType(self): return self.HobType def SetUsage(self, Usage): self.Usage = Usage", "InfHobObject(): def __init__(self): self.HobType = '' self.Usage = '' self.SupArchList", "return self.Usage def SetSupArchList(self, ArchList): self.SupArchList = ArchList def GetSupArchList(self):", "from Library.Misc import Sdict ## # BootModeObject # class InfBootModeObject():", "@file # This file is used to define class objects", "GetUsage(self): return self.Usage ## # HobObject # class InfHobObject(): def", "== DT.TYPE_HOB_SECTION or \\ Type == DT.TYPE_EVENT_SECTION or \\ Type", "self.HobType = '' self.Usage = '' self.SupArchList = [] self.HelpString", "ArchList): self.SupArchList = ArchList def GetSupArchList(self): return self.SupArchList def SetHelpString(self,", "DT.TYPE_HOB_SECTION or \\ Type == DT.TYPE_EVENT_SECTION or \\ Type ==", "= [] self.HelpString = '' def SetHobType(self, HobType): self.HobType =", "self.HobType = HobType def GetHobType(self): return self.HobType def SetUsage(self, Usage):", "return True def GetSpecialComments(self): return self.SpecialComments ## ErrorInInf # #", "An encapsulate of Error for INF parser. # def ErrorInInf(Message=None,", "from Object.Parser.InfCommonObject import InfSectionCommonDef from Library.Misc import Sdict ## #", "''' InfMisc ''' import Logger.Log as Logger from Logger import", "self.SpecialComments[Type] = ObjList else: ObjList = [] ObjList.append(Item) self.SpecialComments[Type] =", "= '' self.Usage = '' def SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes =", "Error for INF parser. # def ErrorInInf(Message=None, ErrorCode=None, LineInfo=None, RaiseError=True):", "None, Type = ''): if Type == DT.TYPE_HOB_SECTION or \\", "Type == DT.TYPE_EVENT_SECTION or \\ Type == DT.TYPE_BOOTMODE_SECTION: for Item", "self.SupportedBootModes = '' self.HelpString = '' self.Usage = '' def", "## # HobObject # class InfHobObject(): def __init__(self): self.HobType =", "''): if Type == DT.TYPE_HOB_SECTION or \\ Type == DT.TYPE_EVENT_SECTION", "if Type == DT.TYPE_HOB_SECTION or \\ Type == DT.TYPE_EVENT_SECTION or", "= '' self.SupArchList = [] self.HelpString = '' def SetHobType(self,", "InfSpecialCommentObject # class InfSpecialCommentObject(InfSectionCommonDef): def __init__(self): self.SpecialComments = Sdict() InfSectionCommonDef.__init__(self)", "Logger from Logger import ToolError from Library import DataType as", "file miscellaneous. # Include BootMode/HOB/Event and others. It will consumed", "def SetEventType(self, EventType): self.EventType = EventType def GetEventType(self): return self.EventType", "def GetSupArchList(self): return self.SupArchList def SetHelpString(self, HelpString): self.HelpString = HelpString", "is used to define class objects of INF file miscellaneous.", "def ErrorInInf(Message=None, ErrorCode=None, LineInfo=None, RaiseError=True): if ErrorCode is None: ErrorCode", "SepcialSectionList: if Type in self.SpecialComments: ObjList = self.SpecialComments[Type] ObjList.append(Item) self.SpecialComments[Type]", "for Item in SepcialSectionList: if Type in self.SpecialComments: ObjList =", "to define class objects of INF file miscellaneous. # Include", "HelpString): self.HelpString = HelpString def GetHelpString(self): return self.HelpString ## #", "SetHobType(self, HobType): self.HobType = HobType def GetHobType(self): return self.HobType def", "SepcialSectionList = None, Type = ''): if Type == DT.TYPE_HOB_SECTION", "InfEventObject(): def __init__(self): self.EventType = '' self.HelpString = '' self.Usage", "SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes = SupportedBootModes def GetSupportedBootModes(self): return self.SupportedBootModes def", "self.Usage ## # HobObject # class InfHobObject(): def __init__(self): self.HobType", "SupportedBootModes): self.SupportedBootModes = SupportedBootModes def GetSupportedBootModes(self): return self.SupportedBootModes def SetHelpString(self,", "= '' self.HelpString = '' self.Usage = '' def SetEventType(self,", "def GetHelpString(self): return self.HelpString def SetUsage(self, Usage): self.Usage = Usage", "= Usage def GetUsage(self): return self.Usage ## # HobObject #", "or \\ Type == DT.TYPE_BOOTMODE_SECTION: for Item in SepcialSectionList: if", "''' import Logger.Log as Logger from Logger import ToolError from", "EventType def GetEventType(self): return self.EventType def SetHelpString(self, HelpString): self.HelpString =", "= '' self.Usage = '' self.SupArchList = [] self.HelpString =", "'' self.HelpString = '' self.Usage = '' def SetSupportedBootModes(self, SupportedBootModes):", "if ErrorCode is None: ErrorCode = ToolError.FORMAT_INVALID if LineInfo is", "from Library import DataType as DT from Object.Parser.InfCommonObject import InfSectionCommonDef", "def GetSpecialComments(self): return self.SpecialComments ## ErrorInInf # # An encapsulate", "__init__(self): self.SupportedBootModes = '' self.HelpString = '' self.Usage = ''", "__init__(self): self.HobType = '' self.Usage = '' self.SupArchList = []", "or \\ Type == DT.TYPE_EVENT_SECTION or \\ Type == DT.TYPE_BOOTMODE_SECTION:", "HobObject # class InfHobObject(): def __init__(self): self.HobType = '' self.Usage", "True def GetSpecialComments(self): return self.SpecialComments ## ErrorInInf # # An", "def SetSpecialComments(self, SepcialSectionList = None, Type = ''): if Type", "'' def SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes = SupportedBootModes def GetSupportedBootModes(self): return", "= self.SpecialComments[Type] ObjList.append(Item) self.SpecialComments[Type] = ObjList else: ObjList = []", "and others. It will consumed by InfParser. # # Copyright", "import Logger.Log as Logger from Logger import ToolError from Library", "ErrorCode = ToolError.FORMAT_INVALID if LineInfo is None: LineInfo = ['',", "is None: LineInfo = ['', -1, ''] Logger.Error(\"InfParser\", ErrorCode, Message=Message,", "- 2018, Intel Corporation. All rights reserved.<BR> # # SPDX-License-Identifier:", "def __init__(self): self.SpecialComments = Sdict() InfSectionCommonDef.__init__(self) def SetSpecialComments(self, SepcialSectionList =", "return self.HelpString def SetUsage(self, Usage): self.Usage = Usage def GetUsage(self):", "self.SupportedBootModes def SetHelpString(self, HelpString): self.HelpString = HelpString def GetHelpString(self): return", "self.HelpString = '' def SetHobType(self, HobType): self.HobType = HobType def", "self.SpecialComments = Sdict() InfSectionCommonDef.__init__(self) def SetSpecialComments(self, SepcialSectionList = None, Type", "ErrorCode=None, LineInfo=None, RaiseError=True): if ErrorCode is None: ErrorCode = ToolError.FORMAT_INVALID", "EventType): self.EventType = EventType def GetEventType(self): return self.EventType def SetHelpString(self,", "= '' def SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes = SupportedBootModes def GetSupportedBootModes(self):", "def __init__(self): self.HobType = '' self.Usage = '' self.SupArchList =", "GetUsage(self): return self.Usage ## # EventObject # class InfEventObject(): def", "GetHelpString(self): return self.HelpString ## # InfSpecialCommentObject # class InfSpecialCommentObject(InfSectionCommonDef): def", "Usage): self.Usage = Usage def GetUsage(self): return self.Usage def SetSupArchList(self,", "is None: ErrorCode = ToolError.FORMAT_INVALID if LineInfo is None: LineInfo", "BootMode/HOB/Event and others. It will consumed by InfParser. # #", "GetHelpString(self): return self.HelpString def SetUsage(self, Usage): self.Usage = Usage def", "def SetHelpString(self, HelpString): self.HelpString = HelpString def GetHelpString(self): return self.HelpString", "self.Usage = Usage def GetUsage(self): return self.Usage def SetSupArchList(self, ArchList):", "others. It will consumed by InfParser. # # Copyright (c)" ]
[ "range(int(input())): n=list(map(int,input().split())) a=b=0 for i in range(len(n)): if(n[i]==1): if(i%2==0): a+=1", "# https://www.codechef.com/START8C/problems/PENALTY for T in range(int(input())): n=list(map(int,input().split())) a=b=0 for i", "a=b=0 for i in range(len(n)): if(n[i]==1): if(i%2==0): a+=1 else: b+=1", "if(i%2==0): a+=1 else: b+=1 if(a>b): print(1) elif(b>a): print(2) else: print(0)", "https://www.codechef.com/START8C/problems/PENALTY for T in range(int(input())): n=list(map(int,input().split())) a=b=0 for i in", "i in range(len(n)): if(n[i]==1): if(i%2==0): a+=1 else: b+=1 if(a>b): print(1)", "if(n[i]==1): if(i%2==0): a+=1 else: b+=1 if(a>b): print(1) elif(b>a): print(2) else:", "for i in range(len(n)): if(n[i]==1): if(i%2==0): a+=1 else: b+=1 if(a>b):", "T in range(int(input())): n=list(map(int,input().split())) a=b=0 for i in range(len(n)): if(n[i]==1):", "for T in range(int(input())): n=list(map(int,input().split())) a=b=0 for i in range(len(n)):", "n=list(map(int,input().split())) a=b=0 for i in range(len(n)): if(n[i]==1): if(i%2==0): a+=1 else:", "range(len(n)): if(n[i]==1): if(i%2==0): a+=1 else: b+=1 if(a>b): print(1) elif(b>a): print(2)", "in range(len(n)): if(n[i]==1): if(i%2==0): a+=1 else: b+=1 if(a>b): print(1) elif(b>a):", "in range(int(input())): n=list(map(int,input().split())) a=b=0 for i in range(len(n)): if(n[i]==1): if(i%2==0):" ]
[ "label_names = list(set(truth) | set(pred)) label_names.sort() truth_compact = [label_names.index(x) for", "xticks_rotation='vertical', values_format='.1f' if norm is not None else 'd') plt.tight_layout()", "ConfusionMatrixDisplay, confusion_matrix def save_confusion_matrix(truth, pred, out_file, norm=None): label_names = list(set(truth)", "100 fig = plt.figure(figsize=(20, 20)) ax = fig.add_subplot(111) disp =", "*= 100 fig = plt.figure(figsize=(20, 20)) ax = fig.add_subplot(111) disp", "confusion_matrix def save_confusion_matrix(truth, pred, out_file, norm=None): label_names = list(set(truth) |", "import ConfusionMatrixDisplay, confusion_matrix def save_confusion_matrix(truth, pred, out_file, norm=None): label_names =", "= list(set(truth) | set(pred)) label_names.sort() truth_compact = [label_names.index(x) for x", "plt.figure(figsize=(20, 20)) ax = fig.add_subplot(111) disp = ConfusionMatrixDisplay( confusion_matrix=cm, display_labels=label_names)", "pred, out_file, norm=None): label_names = list(set(truth) | set(pred)) label_names.sort() truth_compact", "from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix def save_confusion_matrix(truth, pred, out_file, norm=None):", "[label_names.index(x) for x in pred] cm = confusion_matrix( truth_compact, pred_compact,", "if norm is not None else 'd') plt.tight_layout() plt.savefig(out_file) plt.close(fig)", "= fig.add_subplot(111) disp = ConfusionMatrixDisplay( confusion_matrix=cm, display_labels=label_names) disp.plot(ax=ax, xticks_rotation='vertical', values_format='.1f'", "= [label_names.index(x) for x in pred] cm = confusion_matrix( truth_compact,", "norm is not None: cm *= 100 fig = plt.figure(figsize=(20,", "cm *= 100 fig = plt.figure(figsize=(20, 20)) ax = fig.add_subplot(111)", "def save_confusion_matrix(truth, pred, out_file, norm=None): label_names = list(set(truth) | set(pred))", "list(set(truth) | set(pred)) label_names.sort() truth_compact = [label_names.index(x) for x in", "ax = fig.add_subplot(111) disp = ConfusionMatrixDisplay( confusion_matrix=cm, display_labels=label_names) disp.plot(ax=ax, xticks_rotation='vertical',", "truth_compact = [label_names.index(x) for x in truth] pred_compact = [label_names.index(x)", "<filename>util/eval.py import matplotlib.pyplot as plt from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix", "plt from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix def save_confusion_matrix(truth, pred, out_file,", "pred] cm = confusion_matrix( truth_compact, pred_compact, labels=list(range(len(label_names))), normalize=norm) if norm", "[label_names.index(x) for x in truth] pred_compact = [label_names.index(x) for x", "confusion_matrix=cm, display_labels=label_names) disp.plot(ax=ax, xticks_rotation='vertical', values_format='.1f' if norm is not None", "in truth] pred_compact = [label_names.index(x) for x in pred] cm", "labels=list(range(len(label_names))), normalize=norm) if norm is not None: cm *= 100", "confusion_matrix( truth_compact, pred_compact, labels=list(range(len(label_names))), normalize=norm) if norm is not None:", "= plt.figure(figsize=(20, 20)) ax = fig.add_subplot(111) disp = ConfusionMatrixDisplay( confusion_matrix=cm,", "values_format='.1f' if norm is not None else 'd') plt.tight_layout() plt.savefig(out_file)", "set(pred)) label_names.sort() truth_compact = [label_names.index(x) for x in truth] pred_compact", "not None: cm *= 100 fig = plt.figure(figsize=(20, 20)) ax", "save_confusion_matrix(truth, pred, out_file, norm=None): label_names = list(set(truth) | set(pred)) label_names.sort()", "fig.add_subplot(111) disp = ConfusionMatrixDisplay( confusion_matrix=cm, display_labels=label_names) disp.plot(ax=ax, xticks_rotation='vertical', values_format='.1f' if", "| set(pred)) label_names.sort() truth_compact = [label_names.index(x) for x in truth]", "x in truth] pred_compact = [label_names.index(x) for x in pred]", "for x in truth] pred_compact = [label_names.index(x) for x in", "if norm is not None: cm *= 100 fig =", "x in pred] cm = confusion_matrix( truth_compact, pred_compact, labels=list(range(len(label_names))), normalize=norm)", "pred_compact, labels=list(range(len(label_names))), normalize=norm) if norm is not None: cm *=", "None: cm *= 100 fig = plt.figure(figsize=(20, 20)) ax =", "in pred] cm = confusion_matrix( truth_compact, pred_compact, labels=list(range(len(label_names))), normalize=norm) if", "cm = confusion_matrix( truth_compact, pred_compact, labels=list(range(len(label_names))), normalize=norm) if norm is", "fig = plt.figure(figsize=(20, 20)) ax = fig.add_subplot(111) disp = ConfusionMatrixDisplay(", "= ConfusionMatrixDisplay( confusion_matrix=cm, display_labels=label_names) disp.plot(ax=ax, xticks_rotation='vertical', values_format='.1f' if norm is", "norm=None): label_names = list(set(truth) | set(pred)) label_names.sort() truth_compact = [label_names.index(x)", "display_labels=label_names) disp.plot(ax=ax, xticks_rotation='vertical', values_format='.1f' if norm is not None else", "as plt from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix def save_confusion_matrix(truth, pred,", "ConfusionMatrixDisplay( confusion_matrix=cm, display_labels=label_names) disp.plot(ax=ax, xticks_rotation='vertical', values_format='.1f' if norm is not", "sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix def save_confusion_matrix(truth, pred, out_file, norm=None): label_names", "disp = ConfusionMatrixDisplay( confusion_matrix=cm, display_labels=label_names) disp.plot(ax=ax, xticks_rotation='vertical', values_format='.1f' if norm", "for x in pred] cm = confusion_matrix( truth_compact, pred_compact, labels=list(range(len(label_names))),", "normalize=norm) if norm is not None: cm *= 100 fig", "matplotlib.pyplot as plt from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix def save_confusion_matrix(truth,", "label_names.sort() truth_compact = [label_names.index(x) for x in truth] pred_compact =", "out_file, norm=None): label_names = list(set(truth) | set(pred)) label_names.sort() truth_compact =", "= confusion_matrix( truth_compact, pred_compact, labels=list(range(len(label_names))), normalize=norm) if norm is not", "is not None: cm *= 100 fig = plt.figure(figsize=(20, 20))", "pred_compact = [label_names.index(x) for x in pred] cm = confusion_matrix(", "import matplotlib.pyplot as plt from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix def", "truth_compact, pred_compact, labels=list(range(len(label_names))), normalize=norm) if norm is not None: cm", "disp.plot(ax=ax, xticks_rotation='vertical', values_format='.1f' if norm is not None else 'd')", "20)) ax = fig.add_subplot(111) disp = ConfusionMatrixDisplay( confusion_matrix=cm, display_labels=label_names) disp.plot(ax=ax,", "= [label_names.index(x) for x in truth] pred_compact = [label_names.index(x) for", "truth] pred_compact = [label_names.index(x) for x in pred] cm =" ]
[ "self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self,", "nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net,", "[2, 50000] loss: 1.304 # 2/5 5357/10000 53.56999999999999% (105.8866639137268s) #", "# [2, 50000] loss: 1.304 # 2/5 5357/10000 53.56999999999999% (105.8866639137268s)", "[4, 5000] loss: 1.117 # [4, 10000] loss: 1.096 #", "shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root=root, train=False, download=True, transform=transform) testloader =", "shuffle=False, num_workers=2) import torch.nn as nn import torch.nn.functional as F", "def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool", "25000] loss: 1.658 # [1, 30000] loss: 1.625 # [1,", "os.path.dirname(os.path.abspath(__file__)) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5,", "30000] loss: 1.120 # [4, 35000] loss: 1.124 # [4,", "* 5) # print(x.shape) x = F.relu(self.fc1(x)) # print(x.shape) x", "F.relu(self.fc2(x)) # print(x.shape) x = self.fc3(x) # print(x.shape) return x", "print(x.shape) x = F.relu(self.fc1(x)) # print(x.shape) x = F.relu(self.fc2(x)) #", "# torch.Size([1, 84]) # torch.Size([1, 100]) model = Net() import", "20000] loss: 1.123 # [4, 25000] loss: 1.107 # [4,", "1.124 # [4, 40000] loss: 1.094 # [4, 45000] loss:", "[3, 20000] loss: 1.235 # [3, 25000] loss: 1.199 #", "1.196 # [3, 50000] loss: 1.191 # 3/5 5729/10000 57.29%", "# [2, 35000] loss: 1.333 # [2, 40000] loss: 1.280", "as optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.0002, momentum=0.9)", "loss: 1.107 # [4, 30000] loss: 1.120 # [4, 35000]", "loss: 1.876 # [1, 20000] loss: 1.754 # [1, 25000]", "F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3,", "1.558 # [1, 40000] loss: 1.520 # [1, 45000] loss:", "loss: 1.215 # [3, 20000] loss: 1.235 # [3, 25000]", "loss: 1.040 # [5, 20000] loss: 1.027 # [5, 25000]", "[4, 20000] loss: 1.123 # [4, 25000] loss: 1.107 #", "torchvision.datasets.CIFAR10(root=root, train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, shuffle=False, num_workers=2) import", "trainset = torchvision.datasets.CIFAR10(root=root, train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, shuffle=True,", "10000] loss: 1.096 # [4, 15000] loss: 1.121 # [4,", "= nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 *", "5729/10000 57.29% (105.63971090316772s) # [4, 5000] loss: 1.117 # [4,", "torch.Size([1, 3, 32, 32]) # torch.Size([1, 6, 14, 14]) #", "torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def", "400]) # torch.Size([1, 120]) # torch.Size([1, 84]) # torch.Size([1, 100])", "loss: 1.192 # [3, 40000] loss: 1.194 # [3, 45000]", "x = x.view(-1, 16 * 5 * 5) # print(x.shape)", "# [3, 45000] loss: 1.196 # [3, 50000] loss: 1.191", "= torch.utils.data.DataLoader(testset, shuffle=False, num_workers=2) import torch.nn as nn import torch.nn.functional", "loss: 1.754 # [1, 25000] loss: 1.658 # [1, 30000]", "2.075 # [1, 15000] loss: 1.876 # [1, 20000] loss:", "# [4, 15000] loss: 1.121 # [4, 20000] loss: 1.123", "return x # torch.Size([1, 3, 32, 32]) # torch.Size([1, 6,", "[5, 5000] loss: 1.034 # [5, 10000] loss: 1.024 #", "= os.path.dirname(os.path.abspath(__file__)) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5,", "# print(x.shape) x = F.relu(self.fc1(x)) # print(x.shape) x = F.relu(self.fc2(x))", "# [3, 15000] loss: 1.215 # [3, 20000] loss: 1.235", "1.398 # [2, 15000] loss: 1.386 # [2, 20000] loss:", "5000] loss: 1.034 # [5, 10000] loss: 1.024 # [5,", "# [3, 30000] loss: 1.187 # [3, 35000] loss: 1.192", "1.413 # [2, 10000] loss: 1.398 # [2, 15000] loss:", "loss: 1.120 # [4, 35000] loss: 1.124 # [4, 40000]", "5 * 5) # print(x.shape) x = F.relu(self.fc1(x)) # print(x.shape)", "transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) root =", "0.5), (0.5, 0.5, 0.5))]) root = os.path.join(BASE_DIR, '../data/') trainset =", "print(x.shape) x = x.view(-1, 16 * 5 * 5) #", "1.042 # [5, 45000] loss: 1.027 # [5, 50000] loss:", "# [2, 5000] loss: 1.413 # [2, 10000] loss: 1.398", "# [4, 20000] loss: 1.123 # [4, 25000] loss: 1.107", "1.049 # [5, 35000] loss: 1.024 # [5, 40000] loss:", "# 1/5 4456/10000 44.56% (107.18255376815796s) # [2, 5000] loss: 1.413", "50000] loss: 1.459 # 1/5 4456/10000 44.56% (107.18255376815796s) # [2,", "[3, 45000] loss: 1.196 # [3, 50000] loss: 1.191 #", "loss: 1.191 # 3/5 5729/10000 57.29% (105.63971090316772s) # [4, 5000]", "15000] loss: 1.386 # [2, 20000] loss: 1.379 # [2,", "# print(x.shape) x = F.relu(self.fc2(x)) # print(x.shape) x = self.fc3(x)", "optimizer = optim.SGD(model.parameters(), lr=0.0002, momentum=0.9) from util import train_eval train_eval(model,", "3, 32, 32]) # torch.Size([1, 6, 14, 14]) # torch.Size([1,", "loss: 1.494 # [1, 50000] loss: 1.459 # 1/5 4456/10000", "[1, 5000] loss: 2.293 # [1, 10000] loss: 2.075 #", "# [1, 25000] loss: 1.658 # [1, 30000] loss: 1.625", "x = self.pool(F.relu(self.conv2(x))) # print(x.shape) x = x.view(-1, 16 *", "print(x.shape) return x # torch.Size([1, 3, 32, 32]) # torch.Size([1,", "loss: 1.123 # [4, 25000] loss: 1.107 # [4, 30000]", "45000] loss: 1.494 # [1, 50000] loss: 1.459 # 1/5", "loss: 1.324 # [2, 35000] loss: 1.333 # [2, 40000]", "# [5, 25000] loss: 1.043 # [5, 30000] loss: 1.049", "1.520 # [1, 45000] loss: 1.494 # [1, 50000] loss:", "# [1, 15000] loss: 1.876 # [1, 20000] loss: 1.754", "[4, 50000] loss: 1.102 # 4/5 5829/10000 58.29% (112.56915497779846s) #", "BASE_DIR = os.path.dirname(os.path.abspath(__file__)) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5),", "x): # print(x.shape) x = self.pool(F.relu(self.conv1(x))) # print(x.shape) x =", "# print(x.shape) x = self.pool(F.relu(self.conv2(x))) # print(x.shape) x = x.view(-1,", "1.192 # [3, 40000] loss: 1.194 # [3, 45000] loss:", "x.view(-1, 16 * 5 * 5) # print(x.shape) x =", "# torch.Size([1, 120]) # torch.Size([1, 84]) # torch.Size([1, 100]) model", "1.333 # [2, 40000] loss: 1.280 # [2, 45000] loss:", "[4, 45000] loss: 1.105 # [4, 50000] loss: 1.102 #", "# [1, 10000] loss: 2.075 # [1, 15000] loss: 1.876", "[1, 10000] loss: 2.075 # [1, 15000] loss: 1.876 #", "loss: 1.358 # [2, 30000] loss: 1.324 # [2, 35000]", "30000] loss: 1.625 # [1, 35000] loss: 1.558 # [1,", "torchvision.datasets.CIFAR10(root=root, train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, shuffle=True, num_workers=2) testset", "45000] loss: 1.105 # [4, 50000] loss: 1.102 # 4/5", "20000] loss: 1.379 # [2, 25000] loss: 1.358 # [2,", "import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__()", "torchvision import torchvision.transforms as transforms import os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__))", "1.386 # [2, 20000] loss: 1.379 # [2, 25000] loss:", "loss: 1.121 # [4, 20000] loss: 1.123 # [4, 25000]", "# torch.Size([1, 3, 32, 32]) # torch.Size([1, 6, 14, 14])", "1.231 # [3, 15000] loss: 1.215 # [3, 20000] loss:", "loss: 1.042 # [5, 45000] loss: 1.027 # [5, 50000]", "25000] loss: 1.107 # [4, 30000] loss: 1.120 # [4,", "1.191 # 3/5 5729/10000 57.29% (105.63971090316772s) # [4, 5000] loss:", "x = F.relu(self.fc2(x)) # print(x.shape) x = self.fc3(x) # print(x.shape)", "1.027 # [5, 25000] loss: 1.043 # [5, 30000] loss:", "45000] loss: 1.027 # [5, 50000] loss: 1.027 # 5/5", "32]) # torch.Size([1, 6, 14, 14]) # torch.Size([1, 16, 5,", "1.096 # [4, 15000] loss: 1.121 # [4, 20000] loss:", "[4, 30000] loss: 1.120 # [4, 35000] loss: 1.124 #", "as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self):", "15000] loss: 1.215 # [3, 20000] loss: 1.235 # [3,", "torch.Size([1, 6, 14, 14]) # torch.Size([1, 16, 5, 5]) #", "super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2,", "[1, 30000] loss: 1.625 # [1, 35000] loss: 1.558 #", "0.5, 0.5), (0.5, 0.5, 0.5))]) root = os.path.join(BASE_DIR, '../data/') trainset", "# torch.Size([1, 16, 5, 5]) # torch.Size([1, 400]) # torch.Size([1,", "[3, 50000] loss: 1.191 # 3/5 5729/10000 57.29% (105.63971090316772s) #", "self.fc3(x) # print(x.shape) return x # torch.Size([1, 3, 32, 32])", "# [2, 15000] loss: 1.386 # [2, 20000] loss: 1.379", "# [3, 20000] loss: 1.235 # [3, 25000] loss: 1.199", "F.relu(self.fc1(x)) # print(x.shape) x = F.relu(self.fc2(x)) # print(x.shape) x =", "torch import torchvision import torchvision.transforms as transforms import os.path BASE_DIR", "1.379 # [2, 25000] loss: 1.358 # [2, 30000] loss:", "# [5, 10000] loss: 1.024 # [5, 15000] loss: 1.040", "loss: 1.386 # [2, 20000] loss: 1.379 # [2, 25000]", "import torch.nn as nn import torch.nn.functional as F class Net(nn.Module):", "transform=transform) trainloader = torch.utils.data.DataLoader(trainset, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root=root, train=False,", "40000] loss: 1.042 # [5, 45000] loss: 1.027 # [5,", "self.fc3 = nn.Linear(84, 10) def forward(self, x): # print(x.shape) x", "1.215 # [3, 20000] loss: 1.235 # [3, 25000] loss:", "20000] loss: 1.235 # [3, 25000] loss: 1.199 # [3,", "1.235 # [3, 25000] loss: 1.199 # [3, 30000] loss:", "5]) # torch.Size([1, 400]) # torch.Size([1, 120]) # torch.Size([1, 84])", "30000] loss: 1.187 # [3, 35000] loss: 1.192 # [3,", "5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10)", "# [4, 45000] loss: 1.105 # [4, 50000] loss: 1.102", "57.29% (105.63971090316772s) # [4, 5000] loss: 1.117 # [4, 10000]", "loss: 1.024 # [5, 40000] loss: 1.042 # [5, 45000]", "1.358 # [2, 30000] loss: 1.324 # [2, 35000] loss:", "# print(x.shape) x = self.fc3(x) # print(x.shape) return x #", "10000] loss: 2.075 # [1, 15000] loss: 1.876 # [1,", "# [4, 35000] loss: 1.124 # [4, 40000] loss: 1.094", "num_workers=2) testset = torchvision.datasets.CIFAR10(root=root, train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset,", "# [1, 45000] loss: 1.494 # [1, 50000] loss: 1.459", "loss: 1.196 # [3, 50000] loss: 1.191 # 3/5 5729/10000", "[2, 20000] loss: 1.379 # [2, 25000] loss: 1.358 #", "120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def", "= torchvision.datasets.CIFAR10(root=root, train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, shuffle=True, num_workers=2)", "10) def forward(self, x): # print(x.shape) x = self.pool(F.relu(self.conv1(x))) #", "loss: 1.043 # [5, 30000] loss: 1.049 # [5, 35000]", "44.56% (107.18255376815796s) # [2, 5000] loss: 1.413 # [2, 10000]", "= nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 =", "[2, 10000] loss: 1.398 # [2, 15000] loss: 1.386 #", "# [1, 40000] loss: 1.520 # [1, 45000] loss: 1.494", "loss: 1.625 # [1, 35000] loss: 1.558 # [1, 40000]", "[5, 30000] loss: 1.049 # [5, 35000] loss: 1.024 #", "[2, 45000] loss: 1.296 # [2, 50000] loss: 1.304 #", "loss: 1.199 # [3, 30000] loss: 1.187 # [3, 35000]", "[2, 15000] loss: 1.386 # [2, 20000] loss: 1.379 #", "self.pool(F.relu(self.conv2(x))) # print(x.shape) x = x.view(-1, 16 * 5 *", "= self.pool(F.relu(self.conv1(x))) # print(x.shape) x = self.pool(F.relu(self.conv2(x))) # print(x.shape) x", "1.117 # [4, 10000] loss: 1.096 # [4, 15000] loss:", "os.path.join(BASE_DIR, '../data/') trainset = torchvision.datasets.CIFAR10(root=root, train=True, download=True, transform=transform) trainloader =", "torch.Size([1, 400]) # torch.Size([1, 120]) # torch.Size([1, 84]) # torch.Size([1,", "util import train_eval train_eval(model, criterion, trainloader, testloader, optimizer, epochs=5) #", "# [5, 45000] loss: 1.027 # [5, 50000] loss: 1.027", "train_eval train_eval(model, criterion, trainloader, testloader, optimizer, epochs=5) # [1, 5000]", "25000] loss: 1.199 # [3, 30000] loss: 1.187 # [3,", "root = os.path.join(BASE_DIR, '../data/') trainset = torchvision.datasets.CIFAR10(root=root, train=True, download=True, transform=transform)", "nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84)", "[5, 25000] loss: 1.043 # [5, 30000] loss: 1.049 #", "testloader, optimizer, epochs=5) # [1, 5000] loss: 2.293 # [1,", "from util import train_eval train_eval(model, criterion, trainloader, testloader, optimizer, epochs=5)", "50000] loss: 1.191 # 3/5 5729/10000 57.29% (105.63971090316772s) # [4,", "import train_eval train_eval(model, criterion, trainloader, testloader, optimizer, epochs=5) # [1,", "50000] loss: 1.027 # 5/5 6178/10000 61.78% (109.75669193267822s) # 61.0%", "# [1, 35000] loss: 1.558 # [1, 40000] loss: 1.520", "loss: 1.379 # [2, 25000] loss: 1.358 # [2, 30000]", "1.024 # [5, 15000] loss: 1.040 # [5, 20000] loss:", "optim.SGD(model.parameters(), lr=0.0002, momentum=0.9) from util import train_eval train_eval(model, criterion, trainloader,", "[1, 50000] loss: 1.459 # 1/5 4456/10000 44.56% (107.18255376815796s) #", "loss: 1.226 # [3, 10000] loss: 1.231 # [3, 15000]", "1.226 # [3, 10000] loss: 1.231 # [3, 15000] loss:", "[5, 35000] loss: 1.024 # [5, 40000] loss: 1.042 #", "loss: 1.094 # [4, 45000] loss: 1.105 # [4, 50000]", "# [4, 25000] loss: 1.107 # [4, 30000] loss: 1.120", "loss: 1.027 # 5/5 6178/10000 61.78% (109.75669193267822s) # 61.0% (541.0347754955292s)", "5, 5]) # torch.Size([1, 400]) # torch.Size([1, 120]) # torch.Size([1,", "x = F.relu(self.fc1(x)) # print(x.shape) x = F.relu(self.fc2(x)) # print(x.shape)", "1.199 # [3, 30000] loss: 1.187 # [3, 35000] loss:", "# [5, 15000] loss: 1.040 # [5, 20000] loss: 1.027", "# [5, 5000] loss: 1.034 # [5, 10000] loss: 1.024", "40000] loss: 1.094 # [4, 45000] loss: 1.105 # [4,", "6, 14, 14]) # torch.Size([1, 16, 5, 5]) # torch.Size([1,", "58.29% (112.56915497779846s) # [5, 5000] loss: 1.034 # [5, 10000]", "import torchvision.transforms as transforms import os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) transform", "30000] loss: 1.324 # [2, 35000] loss: 1.333 # [2,", "loss: 1.102 # 4/5 5829/10000 58.29% (112.56915497779846s) # [5, 5000]", "= Net() import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer", "x = self.pool(F.relu(self.conv1(x))) # print(x.shape) x = self.pool(F.relu(self.conv2(x))) # print(x.shape)", "loss: 1.558 # [1, 40000] loss: 1.520 # [1, 45000]", "[4, 35000] loss: 1.124 # [4, 40000] loss: 1.094 #", "loss: 1.280 # [2, 45000] loss: 1.296 # [2, 50000]", "0.5, 0.5))]) root = os.path.join(BASE_DIR, '../data/') trainset = torchvision.datasets.CIFAR10(root=root, train=True,", "16 * 5 * 5) # print(x.shape) x = F.relu(self.fc1(x))", "# torch.Size([1, 100]) model = Net() import torch.optim as optim", "(105.8866639137268s) # [3, 5000] loss: 1.226 # [3, 10000] loss:", "1.280 # [2, 45000] loss: 1.296 # [2, 50000] loss:", "import os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5,", "# [4, 50000] loss: 1.102 # 4/5 5829/10000 58.29% (112.56915497779846s)", "nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): #", "= self.pool(F.relu(self.conv2(x))) # print(x.shape) x = x.view(-1, 16 * 5", "train_eval(model, criterion, trainloader, testloader, optimizer, epochs=5) # [1, 5000] loss:", "1.876 # [1, 20000] loss: 1.754 # [1, 25000] loss:", "[1, 40000] loss: 1.520 # [1, 45000] loss: 1.494 #", "120]) # torch.Size([1, 84]) # torch.Size([1, 100]) model = Net()", "'../data/') trainset = torchvision.datasets.CIFAR10(root=root, train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset,", "loss: 1.187 # [3, 35000] loss: 1.192 # [3, 40000]", "= self.fc3(x) # print(x.shape) return x # torch.Size([1, 3, 32,", "trainloader = torch.utils.data.DataLoader(trainset, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root=root, train=False, download=True,", "optimizer, epochs=5) # [1, 5000] loss: 2.293 # [1, 10000]", "[3, 10000] loss: 1.231 # [3, 15000] loss: 1.215 #", "1.304 # 2/5 5357/10000 53.56999999999999% (105.8866639137268s) # [3, 5000] loss:", "[1, 35000] loss: 1.558 # [1, 40000] loss: 1.520 #", "1.024 # [5, 40000] loss: 1.042 # [5, 45000] loss:", "84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # print(x.shape)", "40000] loss: 1.520 # [1, 45000] loss: 1.494 # [1,", "1.187 # [3, 35000] loss: 1.192 # [3, 40000] loss:", "Net() import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer =", "Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5)", "torch.Size([1, 16, 5, 5]) # torch.Size([1, 400]) # torch.Size([1, 120])", "# [1, 50000] loss: 1.459 # 1/5 4456/10000 44.56% (107.18255376815796s)", "lr=0.0002, momentum=0.9) from util import train_eval train_eval(model, criterion, trainloader, testloader,", "# [5, 30000] loss: 1.049 # [5, 35000] loss: 1.024", "# [3, 35000] loss: 1.192 # [3, 40000] loss: 1.194", "# [3, 25000] loss: 1.199 # [3, 30000] loss: 1.187", "[2, 5000] loss: 1.413 # [2, 10000] loss: 1.398 #", "= torch.utils.data.DataLoader(trainset, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root=root, train=False, download=True, transform=transform)", "loss: 1.105 # [4, 50000] loss: 1.102 # 4/5 5829/10000", "train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, shuffle=False, num_workers=2) import torch.nn", "1.040 # [5, 20000] loss: 1.027 # [5, 25000] loss:", "1.107 # [4, 30000] loss: 1.120 # [4, 35000] loss:", "20000] loss: 1.027 # [5, 25000] loss: 1.043 # [5,", "(112.56915497779846s) # [5, 5000] loss: 1.034 # [5, 10000] loss:", "5) # print(x.shape) x = F.relu(self.fc1(x)) # print(x.shape) x =", "10000] loss: 1.231 # [3, 15000] loss: 1.215 # [3,", "testset = torchvision.datasets.CIFAR10(root=root, train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, shuffle=False,", "53.56999999999999% (105.8866639137268s) # [3, 5000] loss: 1.226 # [3, 10000]", "5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5)", "1.625 # [1, 35000] loss: 1.558 # [1, 40000] loss:", "5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 =", "loss: 1.124 # [4, 40000] loss: 1.094 # [4, 45000]", "16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120)", "45000] loss: 1.296 # [2, 50000] loss: 1.304 # 2/5", "[3, 15000] loss: 1.215 # [3, 20000] loss: 1.235 #", "torch.Size([1, 100]) model = Net() import torch.optim as optim criterion", "20000] loss: 1.754 # [1, 25000] loss: 1.658 # [1,", "# [4, 30000] loss: 1.120 # [4, 35000] loss: 1.124", "num_workers=2) import torch.nn as nn import torch.nn.functional as F class", "self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2", "# [1, 5000] loss: 2.293 # [1, 10000] loss: 2.075", "= nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 =", "loss: 1.117 # [4, 10000] loss: 1.096 # [4, 15000]", "5829/10000 58.29% (112.56915497779846s) # [5, 5000] loss: 1.034 # [5,", "16, 5, 5]) # torch.Size([1, 400]) # torch.Size([1, 120]) #", "import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(),", "[3, 5000] loss: 1.226 # [3, 10000] loss: 1.231 #", "# print(x.shape) return x # torch.Size([1, 3, 32, 32]) #", "torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.0002,", "loss: 1.027 # [5, 50000] loss: 1.027 # 5/5 6178/10000", "testloader = torch.utils.data.DataLoader(testset, shuffle=False, num_workers=2) import torch.nn as nn import", "[5, 40000] loss: 1.042 # [5, 45000] loss: 1.027 #", "momentum=0.9) from util import train_eval train_eval(model, criterion, trainloader, testloader, optimizer,", "loss: 2.293 # [1, 10000] loss: 2.075 # [1, 15000]", "= F.relu(self.fc1(x)) # print(x.shape) x = F.relu(self.fc2(x)) # print(x.shape) x", "loss: 2.075 # [1, 15000] loss: 1.876 # [1, 20000]", "loss: 1.194 # [3, 45000] loss: 1.196 # [3, 50000]", "# print(x.shape) x = x.view(-1, 16 * 5 * 5)", "1/5 4456/10000 44.56% (107.18255376815796s) # [2, 5000] loss: 1.413 #", "[4, 40000] loss: 1.094 # [4, 45000] loss: 1.105 #", "transform=transform) testloader = torch.utils.data.DataLoader(testset, shuffle=False, num_workers=2) import torch.nn as nn", "print(x.shape) x = self.pool(F.relu(self.conv2(x))) # print(x.shape) x = x.view(-1, 16", "[1, 25000] loss: 1.658 # [1, 30000] loss: 1.625 #", "50000] loss: 1.102 # 4/5 5829/10000 58.29% (112.56915497779846s) # [5,", "= os.path.join(BASE_DIR, '../data/') trainset = torchvision.datasets.CIFAR10(root=root, train=True, download=True, transform=transform) trainloader", "[1, 45000] loss: 1.494 # [1, 50000] loss: 1.459 #", "nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5,", "forward(self, x): # print(x.shape) x = self.pool(F.relu(self.conv1(x))) # print(x.shape) x", "[4, 25000] loss: 1.107 # [4, 30000] loss: 1.120 #", "trainloader, testloader, optimizer, epochs=5) # [1, 5000] loss: 2.293 #", "loss: 1.096 # [4, 15000] loss: 1.121 # [4, 20000]", "self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2)", "# [3, 10000] loss: 1.231 # [3, 15000] loss: 1.215", "# 3/5 5729/10000 57.29% (105.63971090316772s) # [4, 5000] loss: 1.117", "15000] loss: 1.876 # [1, 20000] loss: 1.754 # [1,", "print(x.shape) x = F.relu(self.fc2(x)) # print(x.shape) x = self.fc3(x) #", "1.754 # [1, 25000] loss: 1.658 # [1, 30000] loss:", "[5, 20000] loss: 1.027 # [5, 25000] loss: 1.043 #", "= nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.0002, momentum=0.9) from util import", "class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6,", "# [4, 10000] loss: 1.096 # [4, 15000] loss: 1.121", "criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.0002, momentum=0.9) from util", "loss: 1.034 # [5, 10000] loss: 1.024 # [5, 15000]", "nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16", "32, 32]) # torch.Size([1, 6, 14, 14]) # torch.Size([1, 16,", "50000] loss: 1.304 # 2/5 5357/10000 53.56999999999999% (105.8866639137268s) # [3,", "1.094 # [4, 45000] loss: 1.105 # [4, 50000] loss:", "transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])", "# [3, 40000] loss: 1.194 # [3, 45000] loss: 1.196", "nn.Linear(84, 10) def forward(self, x): # print(x.shape) x = self.pool(F.relu(self.conv1(x)))", "criterion, trainloader, testloader, optimizer, epochs=5) # [1, 5000] loss: 2.293", "6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16,", "1.494 # [1, 50000] loss: 1.459 # 1/5 4456/10000 44.56%", "transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) root = os.path.join(BASE_DIR, '../data/')", "# 4/5 5829/10000 58.29% (112.56915497779846s) # [5, 5000] loss: 1.034", "14, 14]) # torch.Size([1, 16, 5, 5]) # torch.Size([1, 400])", "x = self.fc3(x) # print(x.shape) return x # torch.Size([1, 3,", "15000] loss: 1.040 # [5, 20000] loss: 1.027 # [5,", "# print(x.shape) x = self.pool(F.relu(self.conv1(x))) # print(x.shape) x = self.pool(F.relu(self.conv2(x)))", "2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 *", "= nn.Linear(84, 10) def forward(self, x): # print(x.shape) x =", "# [5, 35000] loss: 1.024 # [5, 40000] loss: 1.042", "x # torch.Size([1, 3, 32, 32]) # torch.Size([1, 6, 14,", "train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, shuffle=True, num_workers=2) testset =", "# [3, 50000] loss: 1.191 # 3/5 5729/10000 57.29% (105.63971090316772s)", "(105.63971090316772s) # [4, 5000] loss: 1.117 # [4, 10000] loss:", "loss: 1.304 # 2/5 5357/10000 53.56999999999999% (105.8866639137268s) # [3, 5000]", "30000] loss: 1.049 # [5, 35000] loss: 1.024 # [5,", "import torchvision import torchvision.transforms as transforms import os.path BASE_DIR =", "# [1, 30000] loss: 1.625 # [1, 35000] loss: 1.558", "1.027 # [5, 50000] loss: 1.027 # 5/5 6178/10000 61.78%", "def forward(self, x): # print(x.shape) x = self.pool(F.relu(self.conv1(x))) # print(x.shape)", "2/5 5357/10000 53.56999999999999% (105.8866639137268s) # [3, 5000] loss: 1.226 #", "25000] loss: 1.043 # [5, 30000] loss: 1.049 # [5,", "1.296 # [2, 50000] loss: 1.304 # 2/5 5357/10000 53.56999999999999%", "torch.utils.data.DataLoader(trainset, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root=root, train=False, download=True, transform=transform) testloader", "print(x.shape) x = self.fc3(x) # print(x.shape) return x # torch.Size([1,", "3/5 5729/10000 57.29% (105.63971090316772s) # [4, 5000] loss: 1.117 #", "4456/10000 44.56% (107.18255376815796s) # [2, 5000] loss: 1.413 # [2,", "[3, 40000] loss: 1.194 # [3, 45000] loss: 1.196 #", "4/5 5829/10000 58.29% (112.56915497779846s) # [5, 5000] loss: 1.034 #", "1.324 # [2, 35000] loss: 1.333 # [2, 40000] loss:", "45000] loss: 1.196 # [3, 50000] loss: 1.191 # 3/5", "1.105 # [4, 50000] loss: 1.102 # 4/5 5829/10000 58.29%", "15000] loss: 1.121 # [4, 20000] loss: 1.123 # [4,", "[3, 35000] loss: 1.192 # [3, 40000] loss: 1.194 #", "35000] loss: 1.124 # [4, 40000] loss: 1.094 # [4,", "loss: 1.333 # [2, 40000] loss: 1.280 # [2, 45000]", "(0.5, 0.5, 0.5))]) root = os.path.join(BASE_DIR, '../data/') trainset = torchvision.datasets.CIFAR10(root=root,", "= x.view(-1, 16 * 5 * 5) # print(x.shape) x", "download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, shuffle=False, num_workers=2) import torch.nn as", "nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6,", "[2, 30000] loss: 1.324 # [2, 35000] loss: 1.333 #", "transforms import os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) transform = transforms.Compose( [transforms.ToTensor(),", "1.123 # [4, 25000] loss: 1.107 # [4, 30000] loss:", "print(x.shape) x = self.pool(F.relu(self.conv1(x))) # print(x.shape) x = self.pool(F.relu(self.conv2(x))) #", "* 5 * 5) # print(x.shape) x = F.relu(self.fc1(x)) #", "[4, 10000] loss: 1.096 # [4, 15000] loss: 1.121 #", "1.459 # 1/5 4456/10000 44.56% (107.18255376815796s) # [2, 5000] loss:", "1.102 # 4/5 5829/10000 58.29% (112.56915497779846s) # [5, 5000] loss:", "loss: 1.024 # [5, 15000] loss: 1.040 # [5, 20000]", "[3, 30000] loss: 1.187 # [3, 35000] loss: 1.192 #", "nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.0002, momentum=0.9) from util import train_eval", "[3, 25000] loss: 1.199 # [3, 30000] loss: 1.187 #", "self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 =", "[5, 10000] loss: 1.024 # [5, 15000] loss: 1.040 #", "as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 =", "5000] loss: 2.293 # [1, 10000] loss: 2.075 # [1,", "# [2, 10000] loss: 1.398 # [2, 15000] loss: 1.386", "100]) model = Net() import torch.optim as optim criterion =", "35000] loss: 1.333 # [2, 40000] loss: 1.280 # [2,", "[5, 50000] loss: 1.027 # 5/5 6178/10000 61.78% (109.75669193267822s) #", "# 2/5 5357/10000 53.56999999999999% (105.8866639137268s) # [3, 5000] loss: 1.226", "loss: 1.520 # [1, 45000] loss: 1.494 # [1, 50000]", "* 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3", "__init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool =", "loss: 1.231 # [3, 15000] loss: 1.215 # [3, 20000]", "5000] loss: 1.117 # [4, 10000] loss: 1.096 # [4,", "torch.Size([1, 120]) # torch.Size([1, 84]) # torch.Size([1, 100]) model =", "os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5,", "0.5))]) root = os.path.join(BASE_DIR, '../data/') trainset = torchvision.datasets.CIFAR10(root=root, train=True, download=True,", "35000] loss: 1.558 # [1, 40000] loss: 1.520 # [1,", "loss: 1.398 # [2, 15000] loss: 1.386 # [2, 20000]", "= nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120,", "# [3, 5000] loss: 1.226 # [3, 10000] loss: 1.231", "torchvision.transforms as transforms import os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) transform =", "# [5, 20000] loss: 1.027 # [5, 25000] loss: 1.043", "loss: 1.235 # [3, 25000] loss: 1.199 # [3, 30000]", "1.034 # [5, 10000] loss: 1.024 # [5, 15000] loss:", "# [2, 45000] loss: 1.296 # [2, 50000] loss: 1.304", "10000] loss: 1.398 # [2, 15000] loss: 1.386 # [2,", "5000] loss: 1.226 # [3, 10000] loss: 1.231 # [3,", "[transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) root = os.path.join(BASE_DIR,", "# [2, 30000] loss: 1.324 # [2, 35000] loss: 1.333", "# [4, 40000] loss: 1.094 # [4, 45000] loss: 1.105", "loss: 1.459 # 1/5 4456/10000 44.56% (107.18255376815796s) # [2, 5000]", "[1, 15000] loss: 1.876 # [1, 20000] loss: 1.754 #", "loss: 1.296 # [2, 50000] loss: 1.304 # 2/5 5357/10000", "as transforms import os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) transform = transforms.Compose(", "40000] loss: 1.194 # [3, 45000] loss: 1.196 # [3,", "5357/10000 53.56999999999999% (105.8866639137268s) # [3, 5000] loss: 1.226 # [3,", "[2, 35000] loss: 1.333 # [2, 40000] loss: 1.280 #", "download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root=root,", "# [2, 40000] loss: 1.280 # [2, 45000] loss: 1.296", "(107.18255376815796s) # [2, 5000] loss: 1.413 # [2, 10000] loss:", "# [1, 20000] loss: 1.754 # [1, 25000] loss: 1.658", "25000] loss: 1.358 # [2, 30000] loss: 1.324 # [2,", "1.043 # [5, 30000] loss: 1.049 # [5, 35000] loss:", "torch.utils.data.DataLoader(testset, shuffle=False, num_workers=2) import torch.nn as nn import torch.nn.functional as", "5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2", "epochs=5) # [1, 5000] loss: 2.293 # [1, 10000] loss:", "# [5, 50000] loss: 1.027 # 5/5 6178/10000 61.78% (109.75669193267822s)", "10000] loss: 1.024 # [5, 15000] loss: 1.040 # [5,", "self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1", "loss: 1.027 # [5, 25000] loss: 1.043 # [5, 30000]", "84]) # torch.Size([1, 100]) model = Net() import torch.optim as", "loss: 1.413 # [2, 10000] loss: 1.398 # [2, 15000]", "= optim.SGD(model.parameters(), lr=0.0002, momentum=0.9) from util import train_eval train_eval(model, criterion,", "* 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84,", "40000] loss: 1.280 # [2, 45000] loss: 1.296 # [2,", "[1, 20000] loss: 1.754 # [1, 25000] loss: 1.658 #", "self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5", "import torch import torchvision import torchvision.transforms as transforms import os.path", "35000] loss: 1.024 # [5, 40000] loss: 1.042 # [5,", "[2, 25000] loss: 1.358 # [2, 30000] loss: 1.324 #", "1.120 # [4, 35000] loss: 1.124 # [4, 40000] loss:", "2.293 # [1, 10000] loss: 2.075 # [1, 15000] loss:", "# [2, 25000] loss: 1.358 # [2, 30000] loss: 1.324", "1.194 # [3, 45000] loss: 1.196 # [3, 50000] loss:", "# [4, 5000] loss: 1.117 # [4, 10000] loss: 1.096", "[5, 45000] loss: 1.027 # [5, 50000] loss: 1.027 #", "# [2, 20000] loss: 1.379 # [2, 25000] loss: 1.358", "# torch.Size([1, 400]) # torch.Size([1, 120]) # torch.Size([1, 84]) #", "model = Net() import torch.optim as optim criterion = nn.CrossEntropyLoss()", "14]) # torch.Size([1, 16, 5, 5]) # torch.Size([1, 400]) #", "[2, 40000] loss: 1.280 # [2, 45000] loss: 1.296 #", "optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.0002, momentum=0.9) from", "[4, 15000] loss: 1.121 # [4, 20000] loss: 1.123 #", "torch.Size([1, 84]) # torch.Size([1, 100]) model = Net() import torch.optim", "= transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) root", "= nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x):", "torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1", "1.121 # [4, 20000] loss: 1.123 # [4, 25000] loss:", "loss: 1.658 # [1, 30000] loss: 1.625 # [1, 35000]", "self.pool(F.relu(self.conv1(x))) # print(x.shape) x = self.pool(F.relu(self.conv2(x))) # print(x.shape) x =", "# torch.Size([1, 6, 14, 14]) # torch.Size([1, 16, 5, 5])", "= F.relu(self.fc2(x)) # print(x.shape) x = self.fc3(x) # print(x.shape) return", "loss: 1.049 # [5, 35000] loss: 1.024 # [5, 40000]", "# [5, 40000] loss: 1.042 # [5, 45000] loss: 1.027", "= torchvision.datasets.CIFAR10(root=root, train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, shuffle=False, num_workers=2)", "5000] loss: 1.413 # [2, 10000] loss: 1.398 # [2,", "35000] loss: 1.192 # [3, 40000] loss: 1.194 # [3,", "[5, 15000] loss: 1.040 # [5, 20000] loss: 1.027 #", "1.658 # [1, 30000] loss: 1.625 # [1, 35000] loss:" ]
[ "res_kep_0['Mean Julian Date'][0] != res_kep_1['Mean Julian Date'][0] assert len(res_eq_0['Equinoctial State", "21 assert res_kep_0['Mean Julian Date'][0] != res_kep_1['Mean Julian Date'][0] assert", "= neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=1) res_eq_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\",", "= neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=1) assert len(res_kep_0['Keplerian State Vector']) ==", "res_kep_1['Mean Julian Date'][0] assert len(res_eq_0['Equinoctial State Vector']) == 6 assert", "== 21 assert len(res_eq_0['Keplerian Correlation Matrix']) == 0 assert res_eq_0['Mean", "neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=1) assert len(res_kep_0['Keplerian State Vector']) == 6", "len(res_kep_0['Keplerian State Vector']) == 6 assert len(res_kep_0['Covariance Matrix']) == 21", "State Vector']) == 6 assert len(res_kep_0['Covariance Matrix']) == 21 assert", "epoch_near_present=0) res_eq_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=1) assert len(res_kep_0['Keplerian State", "test_object, orbital_element_type=\"ke\", epoch_near_present=0) res_kep_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=1) res_eq_0", "assert len(res_eq_0['Equinoctial State Vector']) == 6 assert len(res_eq_0['Covariance Matrix']) ==", "len(res_eq_0['Equinoctial State Vector']) == 6 assert len(res_eq_0['Covariance Matrix']) == 21", "Vector']) == 6 assert len(res_eq_0['Covariance Matrix']) == 21 assert len(res_eq_0['Keplerian", "test_object, orbital_element_type=\"ke\", epoch_near_present=1) res_eq_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=0) res_eq_1", "== 6 assert len(res_eq_0['Covariance Matrix']) == 21 assert len(res_eq_0['Keplerian Correlation", "Matrix']) == 0 assert res_eq_0['Mean Julian Date'][0] != res_eq_1['Mean Julian", "assert len(res_eq_0['Covariance Matrix']) == 21 assert len(res_eq_0['Keplerian Correlation Matrix']) ==", "len(res_kep_0['Covariance Matrix']) == 21 assert res_kep_0['Mean Julian Date'][0] != res_kep_1['Mean", "6 assert len(res_kep_0['Covariance Matrix']) == 21 assert res_kep_0['Mean Julian Date'][0]", "... import neodys def test_neodys_query(): test_object = \"2018VP1\" res_kep_0 =", "21 assert len(res_eq_0['Keplerian Correlation Matrix']) == 0 assert res_eq_0['Mean Julian", "6 assert len(res_eq_0['Covariance Matrix']) == 21 assert len(res_eq_0['Keplerian Correlation Matrix'])", "orbital_element_type=\"eq\", epoch_near_present=1) assert len(res_kep_0['Keplerian State Vector']) == 6 assert len(res_kep_0['Covariance", "= neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=0) res_eq_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\",", "Correlation Matrix']) == 0 assert res_eq_0['Mean Julian Date'][0] != res_eq_1['Mean", "= \"2018VP1\" res_kep_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=0) res_kep_1 =", "== 6 assert len(res_kep_0['Covariance Matrix']) == 21 assert res_kep_0['Mean Julian", "assert len(res_kep_0['Keplerian State Vector']) == 6 assert len(res_kep_0['Covariance Matrix']) ==", "res_kep_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=0) res_kep_1 = neodys.core.NEODyS.query_object( test_object,", "epoch_near_present=1) assert len(res_kep_0['Keplerian State Vector']) == 6 assert len(res_kep_0['Covariance Matrix'])", "State Vector']) == 6 assert len(res_eq_0['Covariance Matrix']) == 21 assert", "len(res_eq_0['Keplerian Correlation Matrix']) == 0 assert res_eq_0['Mean Julian Date'][0] !=", "res_eq_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=1) assert len(res_kep_0['Keplerian State Vector'])", "Julian Date'][0] assert len(res_eq_0['Equinoctial State Vector']) == 6 assert len(res_eq_0['Covariance", "res_kep_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=1) res_eq_0 = neodys.core.NEODyS.query_object( test_object,", "test_neodys_query(): test_object = \"2018VP1\" res_kep_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=0)", "orbital_element_type=\"ke\", epoch_near_present=1) res_eq_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=0) res_eq_1 =", "res_eq_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=0) res_eq_1 = neodys.core.NEODyS.query_object( test_object,", "Matrix']) == 21 assert len(res_eq_0['Keplerian Correlation Matrix']) == 0 assert", "epoch_near_present=0) res_kep_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=1) res_eq_0 = neodys.core.NEODyS.query_object(", "test_object = \"2018VP1\" res_kep_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=0) res_kep_1", "Julian Date'][0] != res_kep_1['Mean Julian Date'][0] assert len(res_eq_0['Equinoctial State Vector'])", "test_object, orbital_element_type=\"eq\", epoch_near_present=0) res_eq_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=1) assert", "def test_neodys_query(): test_object = \"2018VP1\" res_kep_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\",", "epoch_near_present=1) res_eq_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=0) res_eq_1 = neodys.core.NEODyS.query_object(", "neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=1) res_eq_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=0)", "== 0 assert res_eq_0['Mean Julian Date'][0] != res_eq_1['Mean Julian Date'][0]", "orbital_element_type=\"ke\", epoch_near_present=0) res_kep_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=1) res_eq_0 =", "len(res_eq_0['Covariance Matrix']) == 21 assert len(res_eq_0['Keplerian Correlation Matrix']) == 0", "assert len(res_eq_0['Keplerian Correlation Matrix']) == 0 assert res_eq_0['Mean Julian Date'][0]", "Matrix']) == 21 assert res_kep_0['Mean Julian Date'][0] != res_kep_1['Mean Julian", "!= res_kep_1['Mean Julian Date'][0] assert len(res_eq_0['Equinoctial State Vector']) == 6", "import neodys def test_neodys_query(): test_object = \"2018VP1\" res_kep_0 = neodys.core.NEODyS.query_object(", "Date'][0] != res_kep_1['Mean Julian Date'][0] assert len(res_eq_0['Equinoctial State Vector']) ==", "from ... import neodys def test_neodys_query(): test_object = \"2018VP1\" res_kep_0", "assert res_kep_0['Mean Julian Date'][0] != res_kep_1['Mean Julian Date'][0] assert len(res_eq_0['Equinoctial", "\"2018VP1\" res_kep_0 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=0) res_kep_1 = neodys.core.NEODyS.query_object(", "orbital_element_type=\"eq\", epoch_near_present=0) res_eq_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=1) assert len(res_kep_0['Keplerian", "neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=0) res_kep_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=1)", "Vector']) == 6 assert len(res_kep_0['Covariance Matrix']) == 21 assert res_kep_0['Mean", "Date'][0] assert len(res_eq_0['Equinoctial State Vector']) == 6 assert len(res_eq_0['Covariance Matrix'])", "neodys def test_neodys_query(): test_object = \"2018VP1\" res_kep_0 = neodys.core.NEODyS.query_object( test_object,", "= neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\", epoch_near_present=0) res_kep_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"ke\",", "test_object, orbital_element_type=\"eq\", epoch_near_present=1) assert len(res_kep_0['Keplerian State Vector']) == 6 assert", "assert len(res_kep_0['Covariance Matrix']) == 21 assert res_kep_0['Mean Julian Date'][0] !=", "neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=0) res_eq_1 = neodys.core.NEODyS.query_object( test_object, orbital_element_type=\"eq\", epoch_near_present=1)", "== 21 assert res_kep_0['Mean Julian Date'][0] != res_kep_1['Mean Julian Date'][0]" ]
[ "19:56 from __future__ import unicode_literals from __future__ import absolute_import from", "from __future__ import unicode_literals from __future__ import absolute_import from django.db", "import migrations def noop(*args, **kwargs): pass def _convert_emailed_to_array_field(apps, schema_editor): BillingRecord", "noop(*args, **kwargs): pass def _convert_emailed_to_array_field(apps, schema_editor): BillingRecord = apps.get_model('accounting', 'BillingRecord')", "= apps.get_model('accounting', 'BillingRecord') for record in BillingRecord.objects.all(): if record.emailed_to !=", "record in BillingRecord.objects.all(): if record.emailed_to != '': record.emailed_to_list = record.emailed_to.split(',')", "record.emailed_to_list = record.emailed_to.split(',') record.save() WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord') for wirerecord", "wirerecord.save() class Migration(migrations.Migration): dependencies = [ ('accounting', '0025_auto_20180508_1952'), ] operations", "on 2018-05-08 19:56 from __future__ import unicode_literals from __future__ import", "unicode_literals from __future__ import absolute_import from django.db import migrations def", "schema_editor): BillingRecord = apps.get_model('accounting', 'BillingRecord') for record in BillingRecord.objects.all(): if", "from __future__ import absolute_import from django.db import migrations def noop(*args,", "wirerecord in WireBillingRecord.objects.all(): if wirerecord.emailed_to != '': wirerecord.emailed_to_list = wirerecord.emailed_to.split(',')", "BillingRecord = apps.get_model('accounting', 'BillingRecord') for record in BillingRecord.objects.all(): if record.emailed_to", "def noop(*args, **kwargs): pass def _convert_emailed_to_array_field(apps, schema_editor): BillingRecord = apps.get_model('accounting',", "utf-8 -*- # Generated by Django 1.11.13 on 2018-05-08 19:56", "apps.get_model('accounting', 'WireBillingRecord') for wirerecord in WireBillingRecord.objects.all(): if wirerecord.emailed_to != '':", "'BillingRecord') for record in BillingRecord.objects.all(): if record.emailed_to != '': record.emailed_to_list", "record.emailed_to.split(',') record.save() WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord') for wirerecord in WireBillingRecord.objects.all():", "= apps.get_model('accounting', 'WireBillingRecord') for wirerecord in WireBillingRecord.objects.all(): if wirerecord.emailed_to !=", "-*- # Generated by Django 1.11.13 on 2018-05-08 19:56 from", "Django 1.11.13 on 2018-05-08 19:56 from __future__ import unicode_literals from", "'': record.emailed_to_list = record.emailed_to.split(',') record.save() WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord') for", "**kwargs): pass def _convert_emailed_to_array_field(apps, schema_editor): BillingRecord = apps.get_model('accounting', 'BillingRecord') for", "-*- coding: utf-8 -*- # Generated by Django 1.11.13 on", "wirerecord.emailed_to_list = wirerecord.emailed_to.split(',') wirerecord.save() class Migration(migrations.Migration): dependencies = [ ('accounting',", "= wirerecord.emailed_to.split(',') wirerecord.save() class Migration(migrations.Migration): dependencies = [ ('accounting', '0025_auto_20180508_1952'),", "import absolute_import from django.db import migrations def noop(*args, **kwargs): pass", "absolute_import from django.db import migrations def noop(*args, **kwargs): pass def", "record.emailed_to != '': record.emailed_to_list = record.emailed_to.split(',') record.save() WireBillingRecord = apps.get_model('accounting',", "if wirerecord.emailed_to != '': wirerecord.emailed_to_list = wirerecord.emailed_to.split(',') wirerecord.save() class Migration(migrations.Migration):", "!= '': record.emailed_to_list = record.emailed_to.split(',') record.save() WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord')", "Generated by Django 1.11.13 on 2018-05-08 19:56 from __future__ import", "# -*- coding: utf-8 -*- # Generated by Django 1.11.13", "1.11.13 on 2018-05-08 19:56 from __future__ import unicode_literals from __future__", "in BillingRecord.objects.all(): if record.emailed_to != '': record.emailed_to_list = record.emailed_to.split(',') record.save()", "if record.emailed_to != '': record.emailed_to_list = record.emailed_to.split(',') record.save() WireBillingRecord =", "= record.emailed_to.split(',') record.save() WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord') for wirerecord in", "for record in BillingRecord.objects.all(): if record.emailed_to != '': record.emailed_to_list =", "wirerecord.emailed_to != '': wirerecord.emailed_to_list = wirerecord.emailed_to.split(',') wirerecord.save() class Migration(migrations.Migration): dependencies", "= [ ('accounting', '0025_auto_20180508_1952'), ] operations = [ migrations.RunPython(_convert_emailed_to_array_field, reverse_code=noop)", "__future__ import absolute_import from django.db import migrations def noop(*args, **kwargs):", "record.save() WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord') for wirerecord in WireBillingRecord.objects.all(): if", "__future__ import unicode_literals from __future__ import absolute_import from django.db import", "apps.get_model('accounting', 'BillingRecord') for record in BillingRecord.objects.all(): if record.emailed_to != '':", "_convert_emailed_to_array_field(apps, schema_editor): BillingRecord = apps.get_model('accounting', 'BillingRecord') for record in BillingRecord.objects.all():", "BillingRecord.objects.all(): if record.emailed_to != '': record.emailed_to_list = record.emailed_to.split(',') record.save() WireBillingRecord", "import unicode_literals from __future__ import absolute_import from django.db import migrations", "'': wirerecord.emailed_to_list = wirerecord.emailed_to.split(',') wirerecord.save() class Migration(migrations.Migration): dependencies = [", "!= '': wirerecord.emailed_to_list = wirerecord.emailed_to.split(',') wirerecord.save() class Migration(migrations.Migration): dependencies =", "class Migration(migrations.Migration): dependencies = [ ('accounting', '0025_auto_20180508_1952'), ] operations =", "by Django 1.11.13 on 2018-05-08 19:56 from __future__ import unicode_literals", "from django.db import migrations def noop(*args, **kwargs): pass def _convert_emailed_to_array_field(apps,", "django.db import migrations def noop(*args, **kwargs): pass def _convert_emailed_to_array_field(apps, schema_editor):", "pass def _convert_emailed_to_array_field(apps, schema_editor): BillingRecord = apps.get_model('accounting', 'BillingRecord') for record", "Migration(migrations.Migration): dependencies = [ ('accounting', '0025_auto_20180508_1952'), ] operations = [", "# Generated by Django 1.11.13 on 2018-05-08 19:56 from __future__", "2018-05-08 19:56 from __future__ import unicode_literals from __future__ import absolute_import", "wirerecord.emailed_to.split(',') wirerecord.save() class Migration(migrations.Migration): dependencies = [ ('accounting', '0025_auto_20180508_1952'), ]", "<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django", "dependencies = [ ('accounting', '0025_auto_20180508_1952'), ] operations = [ migrations.RunPython(_convert_emailed_to_array_field,", "for wirerecord in WireBillingRecord.objects.all(): if wirerecord.emailed_to != '': wirerecord.emailed_to_list =", "in WireBillingRecord.objects.all(): if wirerecord.emailed_to != '': wirerecord.emailed_to_list = wirerecord.emailed_to.split(',') wirerecord.save()", "[ ('accounting', '0025_auto_20180508_1952'), ] operations = [ migrations.RunPython(_convert_emailed_to_array_field, reverse_code=noop) ]", "def _convert_emailed_to_array_field(apps, schema_editor): BillingRecord = apps.get_model('accounting', 'BillingRecord') for record in", "migrations def noop(*args, **kwargs): pass def _convert_emailed_to_array_field(apps, schema_editor): BillingRecord =", "WireBillingRecord.objects.all(): if wirerecord.emailed_to != '': wirerecord.emailed_to_list = wirerecord.emailed_to.split(',') wirerecord.save() class", "'WireBillingRecord') for wirerecord in WireBillingRecord.objects.all(): if wirerecord.emailed_to != '': wirerecord.emailed_to_list", "coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-05-08", "WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord') for wirerecord in WireBillingRecord.objects.all(): if wirerecord.emailed_to" ]
[ "\"agent\", \"policy\", [\"random\", \"policy\", \"planner\"], \"Agent type to use.\" )", "for the given worker (directory) id.\"\"\" if map_name == \"v100unfriendly\":", "flags.DEFINE_integer( \"log_every_steps\", 20, \"Log every how many environment steps.\" )", "2.0 (the \"License\"); # you may not use this file", "planner_hparams.planning_horizon, planner_hparams.rollout_agent_type, num_rollouts=planner_hparams.num_rollouts, inner_batch_size=planner_hparams.batch_size, video_writer=video_writer, env_type=planner_hparams.env_type ) rl_utils.run_rollouts( env, agent,", "# pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space ), \"policy\": lambda: rl_utils.PolicyAgent(", "make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs, loop_hparams.frame_stack_size, planner_hparams.planning_horizon, planner_hparams.rollout_agent_type,", "file_format=\"avi\") kwargs[\"eval_fn\"] = make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=log_every_steps, video_writer=video_writer )", "FLAGS = flags.FLAGS flags.DEFINE_string(\"output_dir\", \"\", \"Main directory for multi-runs.\") flags.DEFINE_integer(\"total_num_workers\",", "loop_hparams = trainer_lib.create_hparams( FLAGS.loop_hparams_set, FLAGS.loop_hparams ) if FLAGS.worker_to_game_map and FLAGS.total_num_workers", "to %s.\" % loop_hparams.game) if FLAGS.full_eval: loop_hparams.eval_rl_env_max_episode_steps = -1 planner_hparams", "the timestep limit.\") flags.DEFINE_enum( \"agent\", \"policy\", [\"random\", \"policy\", \"planner\"], \"Agent", "\"debug_video_path\", \"\", \"Path to save the planner debug video at.\"", "env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs, loop_hparams.frame_stack_size, planner_hparams.planning_horizon, planner_hparams.rollout_agent_type, num_rollouts=planner_hparams.num_rollouts, inner_batch_size=planner_hparams.batch_size,", "with --agent=policy.\" ) flags.DEFINE_string( \"planner_hparams_set\", \"planner_small\", \"Planner hparam set.\" )", "env_type=planner_hparams.env_type ) rl_utils.run_rollouts( env, agent, env.reset(), log_every_steps=log_every_steps ) assert len(base_env.current_epoch_rollouts())", "flags.DEFINE_bool(\"autotune\", False, \"Unused here.\") flags.DEFINE_string(\"objective\", \"\", \"Unused here.\") flags.DEFINE_string(\"client_handle\", \"client_0\",", "env env = rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size) sim_env_kwargs = rl.make_simulated_env_kwargs( base_env, loop_hparams,", "discount_factor=policy_hparams.gae_gamma, video_writer=video_writer ), }[agent_type]() def make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=None,", "games.sort() game_id = (directory_id - 1) // worker_per_game tf.logging.info(\"Getting game", "disable=g-long-lambda batch_size, make_agent( rollout_agent_type, env, policy_hparams, policy_dir, sampling_temp, batch_size=inner_batch_size ),", "\"Whether to ignore the timestep limit.\") flags.DEFINE_enum( \"agent\", \"policy\", [\"random\",", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "r\"\"\"Evaluation script for RL agents. Example invocation: python -m tensor2tensor.rl.evaluator", "how many environment steps.\" ) flags.DEFINE_string( \"debug_video_path\", \"\", \"Path to", "registry from tensor2tensor.utils import trainer_lib import tensorflow as tf flags", "= FLAGS.model_dir eval_metrics_dir = FLAGS.eval_metrics_dir if FLAGS.output_dir: cur_dir = FLAGS.output_dir", "def evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, agent_type, eval_with_learner, log_every_steps,", "tf.summary.FileWriter(eval_metrics_dir) video_writer = None kwargs = {} if not eval_with_learner:", "disable=unused-import from tensor2tensor.utils import registry from tensor2tensor.utils import trainer_lib import", "= trainer_lib.create_hparams( FLAGS.loop_hparams_set, FLAGS.loop_hparams ) if FLAGS.worker_to_game_map and FLAGS.total_num_workers >", "gym_env from tensor2tensor.layers import common_video from tensor2tensor.models.research import rl #", "\"evaluator_\" + now_tag) tf.logging.info(\"Writing metrics to %s.\" % eval_metrics_dir) if", "invocation: python -m tensor2tensor.rl.evaluator \\ --policy_dir=$HOME/t2t/rl_v1/policy \\ --eval_metrics_dir=$HOME/t2t/rl_v1/full_eval_metrics \\ --hparams_set=rlmb_base", "\"\", \"Directory with model checkpoints.\") flags.DEFINE_string( \"eval_metrics_dir\", \"\", \"Directory to", "os.path.join(cur_dir, \"world_model\") eval_metrics_dir = os.path.join(cur_dir, \"evaluator_\" + now_tag) tf.logging.info(\"Writing metrics", "policy_dir = os.path.join(cur_dir, \"policy\") model_dir = os.path.join(cur_dir, \"world_model\") eval_metrics_dir =", "envs.\"\"\" return { \"real\": lambda: real_env.new_like( # pylint: disable=g-long-lambda batch_size=sim_env_kwargs[\"batch_size\"],", "\"boxing\", \"asterix\", \"seaquest\"] worker_per_game = 5 elif map_name == \"human_nice\":", "- 1) // worker_per_game tf.logging.info(\"Getting game %d from %s.\" %", "if FLAGS.log_every_steps > 0 else None, debug_video_path=FLAGS.debug_video_path ) if __name__", "disable=g-long-lambda batch_size, env.observation_space, env.action_space, policy_hparams, policy_dir, sampling_temp ), \"planner\": lambda:", "use this file except in compliance with the License. #", "[\"chopper_command\", \"boxing\", \"asterix\", \"seaquest\"] worker_per_game = 5 elif map_name ==", "if map_name == \"v100unfriendly\": games = [\"chopper_command\", \"boxing\", \"asterix\", \"seaquest\"]", "eval_with_learner, log_every_steps, debug_video_path, report_fn=None, report_metric=None ): \"\"\"Evaluate.\"\"\" if eval_with_learner: assert", "model_dir, log_every_steps=log_every_steps, video_writer=video_writer ) eval_metrics = rl_utils.evaluate_all_configs( loop_hparams, policy_dir, **kwargs", "game for the given worker (directory) id.\"\"\" if map_name ==", "infrastructure. flags.DEFINE_bool(\"autotune\", False, \"Unused here.\") flags.DEFINE_string(\"objective\", \"\", \"Unused here.\") flags.DEFINE_string(\"client_handle\",", "import gym_env from tensor2tensor.layers import common_video from tensor2tensor.models.research import rl", "tf.logging.info(\"Set game to %s.\" % loop_hparams.game) if FLAGS.full_eval: loop_hparams.eval_rl_env_max_episode_steps =", "from tensor2tensor.utils import trainer_lib import tensorflow as tf flags =", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "def planner_small(): return tf.contrib.training.HParams( num_rollouts=64, planning_horizon=16, rollout_agent_type=\"policy\", batch_size=64, env_type=\"simulated\", )", "return tf.contrib.training.HParams( num_rollouts=64, planning_horizon=16, rollout_agent_type=\"policy\", batch_size=64, env_type=\"simulated\", ) def make_env(env_type,", "env.env, sim_env_kwargs), lambda env: rl_utils.BatchStackWrapper(env, frame_stack_size), num_rollouts, planning_horizon, discount_factor=policy_hparams.gae_gamma, video_writer=video_writer", "rl_utils.get_metric_name( sampling_temp=loop_hparams.eval_sampling_temps[0], max_num_noops=loop_hparams.eval_max_num_noops, clipped=False ) report_fn(eval_metrics[metric_name], 0) else: report_fn(eval_metrics[report_metric], 0)", "License. # You may obtain a copy of the License", "debug video at.\" ) # Unused flags needed to pass", "env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs=None, frame_stack_size=None, planning_horizon=None, rollout_agent_type=None, batch_size=None, num_rollouts=None,", "\"\"\"Evaluate.\"\"\" if eval_with_learner: assert agent_type == \"policy\" if report_fn: assert", "> 1: loop_hparams.game = get_game_for_worker( FLAGS.worker_to_game_map, FLAGS.worker_id + 1) tf.logging.info(\"Set", "multi-run infrastructure. flags.DEFINE_bool(\"autotune\", False, \"Unused here.\") flags.DEFINE_string(\"objective\", \"\", \"Unused here.\")", "return { \"real\": lambda: real_env.new_like( # pylint: disable=g-long-lambda batch_size=sim_env_kwargs[\"batch_size\"], store_rollouts=False,", "sim_env_kwargs = rl.make_simulated_env_kwargs( base_env, loop_hparams, batch_size=planner_hparams.batch_size, model_dir=model_dir ) agent =", "under the License is distributed on an \"AS IS\" BASIS,", "from tensor2tensor.data_generators import gym_env from tensor2tensor.layers import common_video from tensor2tensor.models.research", "tf.flags FLAGS = flags.FLAGS flags.DEFINE_string(\"output_dir\", \"\", \"Main directory for multi-runs.\")", "\"\", \"Planner hparam overrides.\") flags.DEFINE_integer( \"log_every_steps\", 20, \"Log every how", "\"planner_hparams_set\", \"planner_small\", \"Planner hparam set.\" ) flags.DEFINE_string(\"planner_hparams\", \"\", \"Planner hparam", "License for the specific language governing permissions and # limitations", "game_id = (directory_id - 1) // worker_per_game tf.logging.info(\"Getting game %d", "= (directory_id - 1) // worker_per_game tf.logging.info(\"Getting game %d from", "checkpoints.\") flags.DEFINE_string( \"eval_metrics_dir\", \"\", \"Directory to output the eval metrics", "\"v100unfriendly\": games = [\"chopper_command\", \"boxing\", \"asterix\", \"seaquest\"] worker_per_game = 5", "Agents.\"\"\" if batch_size is None: batch_size = env.batch_size return {", "= common_video.WholeVideoWriter( fps=10, output_path=debug_video_path, file_format=\"avi\") kwargs[\"eval_fn\"] = make_eval_fn_with_agent( agent_type, planner_hparams,", "planner debug video at.\" ) # Unused flags needed to", "= [\"chopper_command\", \"boxing\", \"asterix\", \"seaquest\"] worker_per_game = 5 elif map_name", "\"Main directory for multi-runs.\") flags.DEFINE_integer(\"total_num_workers\", 1, \"How many workers in", "if FLAGS.total_num_workers > 1: cur_dir = os.path.join(cur_dir, \"%d\" % (FLAGS.worker_id", "policy_dir, sampling_temp, sim_env_kwargs, loop_hparams.frame_stack_size, planner_hparams.planning_horizon, planner_hparams.rollout_agent_type, num_rollouts=planner_hparams.num_rollouts, inner_batch_size=planner_hparams.batch_size, video_writer=video_writer, env_type=planner_hparams.env_type", "of an \" \"out-of-graph one. Works only with --agent=policy.\" )", "return eval_metrics def get_game_for_worker(map_name, directory_id): \"\"\"Get game for the given", "env.reset(), log_every_steps=log_every_steps ) assert len(base_env.current_epoch_rollouts()) == env.batch_size return eval_fn def", ") # Unused flags needed to pass for multi-run infrastructure.", "function for Agents.\"\"\" if batch_size is None: batch_size = env.batch_size", "= gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE worker_per_game = 5 else: raise ValueError(\"Unknown worker to", "make_env(env_type, real_env, sim_env_kwargs): \"\"\"Factory function for envs.\"\"\" return { \"real\":", "if FLAGS.full_eval: loop_hparams.eval_rl_env_max_episode_steps = -1 planner_hparams = trainer_lib.create_hparams( FLAGS.planner_hparams_set, FLAGS.planner_hparams", "= rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size) sim_env_kwargs = rl.make_simulated_env_kwargs( base_env, loop_hparams, batch_size=planner_hparams.batch_size, model_dir=model_dir", "The Tensor2Tensor Authors. # # Licensed under the Apache License,", "kwargs = {} if not eval_with_learner: if debug_video_path: video_writer =", "import print_function import datetime import os from tensor2tensor.data_generators import gym_env", "agents. Example invocation: python -m tensor2tensor.rl.evaluator \\ --policy_dir=$HOME/t2t/rl_v1/policy \\ --eval_metrics_dir=$HOME/t2t/rl_v1/full_eval_metrics", "if FLAGS.output_dir: cur_dir = FLAGS.output_dir if FLAGS.total_num_workers > 1: cur_dir", "--hparams_set=rlmb_base \\ --hparams='batch_size=64' \"\"\" from __future__ import absolute_import from __future__", "to pass for multi-run infrastructure. flags.DEFINE_bool(\"autotune\", False, \"Unused here.\") flags.DEFINE_string(\"objective\",", "env.batch_size return { \"random\": lambda: rl_utils.RandomAgent( # pylint: disable=g-long-lambda batch_size,", "= FLAGS.policy_dir model_dir = FLAGS.model_dir eval_metrics_dir = FLAGS.eval_metrics_dir if FLAGS.output_dir:", "from __future__ import absolute_import from __future__ import division from __future__", "in compliance with the License. # You may obtain a", "type to use.\" ) flags.DEFINE_bool( \"eval_with_learner\", True, \"Whether to use", "inner_batch_size=None, video_writer=None, env_type=None): \"\"\"Factory function for Agents.\"\"\" if batch_size is", "lambda: rl_utils.RandomAgent( # pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space ), \"policy\":", "True, \"Whether to use the PolicyLearner.evaluate function instead of an", "(directory_id - 1) // worker_per_game tf.logging.info(\"Getting game %d from %s.\"", "software # distributed under the License is distributed on an", "\"\"\"Factory function for Agents.\"\"\" if batch_size is None: batch_size =", "None: batch_size = env.batch_size return { \"random\": lambda: rl_utils.RandomAgent( #", "FLAGS.log_every_steps if FLAGS.log_every_steps > 0 else None, debug_video_path=FLAGS.debug_video_path ) if", "0) return eval_metrics def get_game_for_worker(map_name, directory_id): \"\"\"Get game for the", "Agent API.\"\"\" def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp): \"\"\"Eval function.\"\"\"", "\"\"\"Get game for the given worker (directory) id.\"\"\" if map_name", "flags.DEFINE_string(\"model_dir\", \"\", \"Directory with model checkpoints.\") flags.DEFINE_string( \"eval_metrics_dir\", \"\", \"Directory", "common_video.WholeVideoWriter( fps=10, output_path=debug_video_path, file_format=\"avi\") kwargs[\"eval_fn\"] = make_eval_fn_with_agent( agent_type, planner_hparams, model_dir,", "from tensor2tensor.models.research import rl # pylint: disable=unused-import from tensor2tensor.rl import", "\"Planner hparam set.\" ) flags.DEFINE_string(\"planner_hparams\", \"\", \"Planner hparam overrides.\") flags.DEFINE_integer(", "if not eval_with_learner: if debug_video_path: video_writer = common_video.WholeVideoWriter( fps=10, output_path=debug_video_path,", "games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE worker_per_game = 5 else: raise ValueError(\"Unknown worker", "make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs=None, frame_stack_size=None, planning_horizon=None, rollout_agent_type=None,", "agent = make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs, loop_hparams.frame_stack_size,", "now = datetime.datetime.now() now_tag = now.strftime(\"%Y_%m_%d_%H_%M\") loop_hparams = trainer_lib.create_hparams( FLAGS.loop_hparams_set,", "\\ --eval_metrics_dir=$HOME/t2t/rl_v1/full_eval_metrics \\ --hparams_set=rlmb_base \\ --hparams='batch_size=64' \"\"\" from __future__ import", ") rl_utils.summarize_metrics(eval_metrics_writer, eval_metrics, 0) if video_writer is not None: video_writer.finish_to_disk()", "if batch_size is None: batch_size = env.batch_size return { \"random\":", "if not tf.gfile.Exists(eval_metrics_dir): tf.gfile.MkDir(eval_metrics_dir) evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir,", "\"policy\", \"planner\"], \"Agent type to use.\" ) flags.DEFINE_bool( \"eval_with_learner\", True,", "0) if video_writer is not None: video_writer.finish_to_disk() # Report metrics", ") rl_utils.run_rollouts( env, agent, env.reset(), log_every_steps=log_every_steps ) assert len(base_env.current_epoch_rollouts()) ==", "**kwargs ) rl_utils.summarize_metrics(eval_metrics_writer, eval_metrics, 0) if video_writer is not None:", "\"policy\" if report_fn: assert report_metric is not None eval_metrics_writer =", "metrics if report_fn: if report_metric == \"mean_reward\": metric_name = rl_utils.get_metric_name(", "# pylint: disable=g-long-lambda batch_size=sim_env_kwargs[\"batch_size\"], store_rollouts=False, ), \"simulated\": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames( #", "agent_type, eval_with_learner, log_every_steps, debug_video_path, report_fn=None, report_metric=None ): \"\"\"Evaluate.\"\"\" if eval_with_learner:", "\"%d\" % (FLAGS.worker_id + 1)) policy_dir = os.path.join(cur_dir, \"policy\") model_dir", "== env.batch_size return eval_fn def evaluate( loop_hparams, planner_hparams, policy_dir, model_dir,", "\\ --hparams='batch_size=64' \"\"\" from __future__ import absolute_import from __future__ import", "policy_hparams, policy_dir, sampling_temp): \"\"\"Eval function.\"\"\" base_env = env env =", "datetime import os from tensor2tensor.data_generators import gym_env from tensor2tensor.layers import", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"Directory with model checkpoints.\") flags.DEFINE_string( \"eval_metrics_dir\", \"\", \"Directory to output", "Report metrics if report_fn: if report_metric == \"mean_reward\": metric_name =", "batch_size, env.observation_space, env.action_space ), \"policy\": lambda: rl_utils.PolicyAgent( # pylint: disable=g-long-lambda", "now_tag = now.strftime(\"%Y_%m_%d_%H_%M\") loop_hparams = trainer_lib.create_hparams( FLAGS.loop_hparams_set, FLAGS.loop_hparams ) if", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "os.path.join(cur_dir, \"%d\" % (FLAGS.worker_id + 1)) policy_dir = os.path.join(cur_dir, \"policy\")", "if debug_video_path: video_writer = common_video.WholeVideoWriter( fps=10, output_path=debug_video_path, file_format=\"avi\") kwargs[\"eval_fn\"] =", "%s.\" % eval_metrics_dir) if not tf.gfile.Exists(eval_metrics_dir): tf.gfile.MkDir(eval_metrics_dir) evaluate( loop_hparams, planner_hparams,", "planner_hparams.rollout_agent_type, num_rollouts=planner_hparams.num_rollouts, inner_batch_size=planner_hparams.batch_size, video_writer=video_writer, env_type=planner_hparams.env_type ) rl_utils.run_rollouts( env, agent, env.reset(),", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "to in writing, software # distributed under the License is", "\"\"\"Returns an out-of-graph eval_fn using the Agent API.\"\"\" def eval_fn(env,", "rl_utils.PolicyAgent( # pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space, policy_hparams, policy_dir, sampling_temp", "# See the License for the specific language governing permissions", ") flags.DEFINE_bool( \"eval_with_learner\", True, \"Whether to use the PolicyLearner.evaluate function", "--agent=policy.\" ) flags.DEFINE_string( \"planner_hparams_set\", \"planner_small\", \"Planner hparam set.\" ) flags.DEFINE_string(\"planner_hparams\",", "env_type=\"simulated\", ) def make_env(env_type, real_env, sim_env_kwargs): \"\"\"Factory function for envs.\"\"\"", "or agreed to in writing, software # distributed under the", "else: report_fn(eval_metrics[report_metric], 0) return eval_metrics def get_game_for_worker(map_name, directory_id): \"\"\"Get game", "= FLAGS.output_dir if FLAGS.total_num_workers > 1: cur_dir = os.path.join(cur_dir, \"%d\"", "eval_metrics, 0) if video_writer is not None: video_writer.finish_to_disk() # Report", "required by applicable law or agreed to in writing, software", "env = rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size) sim_env_kwargs = rl.make_simulated_env_kwargs( base_env, loop_hparams, batch_size=planner_hparams.batch_size,", "), make_env(env_type, env.env, sim_env_kwargs), lambda env: rl_utils.BatchStackWrapper(env, frame_stack_size), num_rollouts, planning_horizon,", "get_game_for_worker( FLAGS.worker_to_game_map, FLAGS.worker_id + 1) tf.logging.info(\"Set game to %s.\" %", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "\"real\": lambda: real_env.new_like( # pylint: disable=g-long-lambda batch_size=sim_env_kwargs[\"batch_size\"], store_rollouts=False, ), \"simulated\":", "assert len(base_env.current_epoch_rollouts()) == env.batch_size return eval_fn def evaluate( loop_hparams, planner_hparams,", "with the License. # You may obtain a copy of", "an \" \"out-of-graph one. Works only with --agent=policy.\" ) flags.DEFINE_string(", "batch_size=inner_batch_size ), make_env(env_type, env.env, sim_env_kwargs), lambda env: rl_utils.BatchStackWrapper(env, frame_stack_size), num_rollouts,", "pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space ), \"policy\": lambda: rl_utils.PolicyAgent( #", "# pylint: disable=g-long-lambda batch_size, make_agent( rollout_agent_type, env, policy_hparams, policy_dir, sampling_temp,", "= tf.flags FLAGS = flags.FLAGS flags.DEFINE_string(\"output_dir\", \"\", \"Main directory for", "hparam set.\" ) flags.DEFINE_string(\"planner_hparams\", \"\", \"Planner hparam overrides.\") flags.DEFINE_integer( \"log_every_steps\",", "at.\" ) flags.DEFINE_bool(\"full_eval\", True, \"Whether to ignore the timestep limit.\")", "Example invocation: python -m tensor2tensor.rl.evaluator \\ --policy_dir=$HOME/t2t/rl_v1/policy \\ --eval_metrics_dir=$HOME/t2t/rl_v1/full_eval_metrics \\", "None: video_writer.finish_to_disk() # Report metrics if report_fn: if report_metric ==", "compliance with the License. # You may obtain a copy", "eval_with_learner: if debug_video_path: video_writer = common_video.WholeVideoWriter( fps=10, output_path=debug_video_path, file_format=\"avi\") kwargs[\"eval_fn\"]", "agreed to in writing, software # distributed under the License", "eval_fn using the Agent API.\"\"\" def eval_fn(env, loop_hparams, policy_hparams, policy_dir,", "to use.\" ) flags.DEFINE_bool( \"eval_with_learner\", True, \"Whether to use the", "\"planner\"], \"Agent type to use.\" ) flags.DEFINE_bool( \"eval_with_learner\", True, \"Whether", "\"policy\": lambda: rl_utils.PolicyAgent( # pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space, policy_hparams,", "distributed under the License is distributed on an \"AS IS\"", "the given worker (directory) id.\"\"\" if map_name == \"v100unfriendly\": games", "None kwargs = {} if not eval_with_learner: if debug_video_path: video_writer", "an out-of-graph eval_fn using the Agent API.\"\"\" def eval_fn(env, loop_hparams,", "\"How to map workers to games.\") flags.DEFINE_string(\"policy_dir\", \"\", \"Directory with", "# limitations under the License. r\"\"\"Evaluation script for RL agents.", "rollout_agent_type=\"policy\", batch_size=64, env_type=\"simulated\", ) def make_env(env_type, real_env, sim_env_kwargs): \"\"\"Factory function", "else: raise ValueError(\"Unknown worker to game map name: %s\" %", "\"Unused here.\") flags.DEFINE_string(\"objective\", \"\", \"Unused here.\") flags.DEFINE_string(\"client_handle\", \"client_0\", \"Unused.\") flags.DEFINE_bool(\"maximize_tuner_objective\",", "report_metric == \"mean_reward\": metric_name = rl_utils.get_metric_name( sampling_temp=loop_hparams.eval_sampling_temps[0], max_num_noops=loop_hparams.eval_max_num_noops, clipped=False )", "with model checkpoints.\") flags.DEFINE_string( \"eval_metrics_dir\", \"\", \"Directory to output the", "to output the eval metrics at.\" ) flags.DEFINE_bool(\"full_eval\", True, \"Whether", "tensor2tensor.layers import common_video from tensor2tensor.models.research import rl # pylint: disable=unused-import", "common_video from tensor2tensor.models.research import rl # pylint: disable=unused-import from tensor2tensor.rl", "express or implied. # See the License for the specific", "frame_stack_size=None, planning_horizon=None, rollout_agent_type=None, batch_size=None, num_rollouts=None, inner_batch_size=None, video_writer=None, env_type=None): \"\"\"Factory function", "except in compliance with the License. # You may obtain", "worker_per_game = 5 elif map_name == \"human_nice\": games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE", "as t2t_flags # pylint: disable=unused-import from tensor2tensor.utils import registry from", "eval metrics at.\" ) flags.DEFINE_bool(\"full_eval\", True, \"Whether to ignore the", "tf.logging.info(\"Writing metrics to %s.\" % eval_metrics_dir) if not tf.gfile.Exists(eval_metrics_dir): tf.gfile.MkDir(eval_metrics_dir)", "eval_metrics_dir) if not tf.gfile.Exists(eval_metrics_dir): tf.gfile.MkDir(eval_metrics_dir) evaluate( loop_hparams, planner_hparams, policy_dir, model_dir,", "sim_env_kwargs=None, frame_stack_size=None, planning_horizon=None, rollout_agent_type=None, batch_size=None, num_rollouts=None, inner_batch_size=None, video_writer=None, env_type=None): \"\"\"Factory", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "planning_horizon, discount_factor=policy_hparams.gae_gamma, video_writer=video_writer ), }[agent_type]() def make_eval_fn_with_agent( agent_type, planner_hparams, model_dir,", "not use this file except in compliance with the License.", "def main(_): now = datetime.datetime.now() now_tag = now.strftime(\"%Y_%m_%d_%H_%M\") loop_hparams =", "Works only with --agent=policy.\" ) flags.DEFINE_string( \"planner_hparams_set\", \"planner_small\", \"Planner hparam", "batch_size=1, env_type=\"simulated\", ) @registry.register_hparams def planner_small(): return tf.contrib.training.HParams( num_rollouts=64, planning_horizon=16,", "\"policy\", [\"random\", \"policy\", \"planner\"], \"Agent type to use.\" ) flags.DEFINE_bool(", "= flags.FLAGS flags.DEFINE_string(\"output_dir\", \"\", \"Main directory for multi-runs.\") flags.DEFINE_integer(\"total_num_workers\", 1,", "to map workers to games.\") flags.DEFINE_string(\"policy_dir\", \"\", \"Directory with policy", "make_agent( rollout_agent_type, env, policy_hparams, policy_dir, sampling_temp, batch_size=inner_batch_size ), make_env(env_type, env.env,", "writing, software # distributed under the License is distributed on", "\\ --policy_dir=$HOME/t2t/rl_v1/policy \\ --eval_metrics_dir=$HOME/t2t/rl_v1/full_eval_metrics \\ --hparams_set=rlmb_base \\ --hparams='batch_size=64' \"\"\" from", "pylint: disable=unused-import from tensor2tensor.rl import rl_utils from tensor2tensor.rl import trainer_model_based_params", "0, \"Unused.\") @registry.register_hparams def planner_tiny(): return tf.contrib.training.HParams( num_rollouts=1, planning_horizon=2, rollout_agent_type=\"random\",", "you may not use this file except in compliance with", "Tensor2Tensor Authors. # # Licensed under the Apache License, Version", "to game map name: %s\" % map_name) games.sort() game_id =", "not eval_with_learner: if debug_video_path: video_writer = common_video.WholeVideoWriter( fps=10, output_path=debug_video_path, file_format=\"avi\")", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "video_writer=video_writer ), }[agent_type]() def make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=None, video_writer=None", "log_every_steps=log_every_steps ) assert len(base_env.current_epoch_rollouts()) == env.batch_size return eval_fn def evaluate(", "> 1: cur_dir = os.path.join(cur_dir, \"%d\" % (FLAGS.worker_id + 1))", "sampling_temp=loop_hparams.eval_sampling_temps[0], max_num_noops=loop_hparams.eval_max_num_noops, clipped=False ) report_fn(eval_metrics[metric_name], 0) else: report_fn(eval_metrics[report_metric], 0) return", "directory for multi-runs.\") flags.DEFINE_integer(\"total_num_workers\", 1, \"How many workers in total.\")", "loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, FLAGS.agent, FLAGS.eval_with_learner, FLAGS.log_every_steps if FLAGS.log_every_steps", "pylint: disable=g-long-lambda batch_size, make_agent( rollout_agent_type, env, policy_hparams, policy_dir, sampling_temp, batch_size=inner_batch_size", "eval_metrics def get_game_for_worker(map_name, directory_id): \"\"\"Get game for the given worker", "% (FLAGS.worker_id + 1)) policy_dir = os.path.join(cur_dir, \"policy\") model_dir =", "\"client_0\", \"Unused.\") flags.DEFINE_bool(\"maximize_tuner_objective\", True, \"Unused.\") flags.DEFINE_integer(\"vizier_search_algorithm\", 0, \"Unused.\") @registry.register_hparams def", "rollout_agent_type=\"random\", batch_size=1, env_type=\"simulated\", ) @registry.register_hparams def planner_small(): return tf.contrib.training.HParams( num_rollouts=64,", "batch_size=planner_hparams.batch_size, model_dir=model_dir ) agent = make_agent( agent_type, env, policy_hparams, policy_dir,", ") def make_env(env_type, real_env, sim_env_kwargs): \"\"\"Factory function for envs.\"\"\" return", "pylint: disable=unused-import from tensor2tensor.utils import registry from tensor2tensor.utils import trainer_lib", "CONDITIONS OF ANY KIND, either express or implied. # See", "the PolicyLearner.evaluate function instead of an \" \"out-of-graph one. Works", "timestep limit.\") flags.DEFINE_enum( \"agent\", \"policy\", [\"random\", \"policy\", \"planner\"], \"Agent type", "total.\") flags.DEFINE_string(\"worker_to_game_map\", \"\", \"How to map workers to games.\") flags.DEFINE_string(\"policy_dir\",", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "num_rollouts=64, planning_horizon=16, rollout_agent_type=\"policy\", batch_size=64, env_type=\"simulated\", ) def make_env(env_type, real_env, sim_env_kwargs):", "20, \"Log every how many environment steps.\" ) flags.DEFINE_string( \"debug_video_path\",", "env: rl_utils.BatchStackWrapper(env, frame_stack_size), num_rollouts, planning_horizon, discount_factor=policy_hparams.gae_gamma, video_writer=video_writer ), }[agent_type]() def", "eval_fn def evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, agent_type, eval_with_learner,", "if report_metric == \"mean_reward\": metric_name = rl_utils.get_metric_name( sampling_temp=loop_hparams.eval_sampling_temps[0], max_num_noops=loop_hparams.eval_max_num_noops, clipped=False", "trainer_lib.create_hparams( FLAGS.planner_hparams_set, FLAGS.planner_hparams ) policy_dir = FLAGS.policy_dir model_dir = FLAGS.model_dir", "save the planner debug video at.\" ) # Unused flags", "env, policy_hparams, policy_dir, sampling_temp, batch_size=inner_batch_size ), make_env(env_type, env.env, sim_env_kwargs), lambda", "map_name) games.sort() game_id = (directory_id - 1) // worker_per_game tf.logging.info(\"Getting", "Unused flags needed to pass for multi-run infrastructure. flags.DEFINE_bool(\"autotune\", False,", "Copyright 2018 The Tensor2Tensor Authors. # # Licensed under the", "model checkpoints.\") flags.DEFINE_string( \"eval_metrics_dir\", \"\", \"Directory to output the eval", "eval_metrics_dir = FLAGS.eval_metrics_dir if FLAGS.output_dir: cur_dir = FLAGS.output_dir if FLAGS.total_num_workers", "agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs=None, frame_stack_size=None, planning_horizon=None, rollout_agent_type=None, batch_size=None,", "model_dir, eval_metrics_dir, FLAGS.agent, FLAGS.eval_with_learner, FLAGS.log_every_steps if FLAGS.log_every_steps > 0 else", "eval_metrics_dir, agent_type, eval_with_learner, log_every_steps, debug_video_path, report_fn=None, report_metric=None ): \"\"\"Evaluate.\"\"\" if", "= now.strftime(\"%Y_%m_%d_%H_%M\") loop_hparams = trainer_lib.create_hparams( FLAGS.loop_hparams_set, FLAGS.loop_hparams ) if FLAGS.worker_to_game_map", "= os.path.join(cur_dir, \"policy\") model_dir = os.path.join(cur_dir, \"world_model\") eval_metrics_dir = os.path.join(cur_dir,", "policy_dir = FLAGS.policy_dir model_dir = FLAGS.model_dir eval_metrics_dir = FLAGS.eval_metrics_dir if", "tf flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string(\"output_dir\", \"\", \"Main", "from tensor2tensor.utils import flags as t2t_flags # pylint: disable=unused-import from", "to ignore the timestep limit.\") flags.DEFINE_enum( \"agent\", \"policy\", [\"random\", \"policy\",", "loop_hparams, policy_hparams, policy_dir, sampling_temp): \"\"\"Eval function.\"\"\" base_env = env env", "\"asterix\", \"seaquest\"] worker_per_game = 5 elif map_name == \"human_nice\": games", "planner_hparams = trainer_lib.create_hparams( FLAGS.planner_hparams_set, FLAGS.planner_hparams ) policy_dir = FLAGS.policy_dir model_dir", "= trainer_lib.create_hparams( FLAGS.planner_hparams_set, FLAGS.planner_hparams ) policy_dir = FLAGS.policy_dir model_dir =", "True, \"Whether to ignore the timestep limit.\") flags.DEFINE_enum( \"agent\", \"policy\",", "def make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs=None, frame_stack_size=None, planning_horizon=None,", "only with --agent=policy.\" ) flags.DEFINE_string( \"planner_hparams_set\", \"planner_small\", \"Planner hparam set.\"", "main(_): now = datetime.datetime.now() now_tag = now.strftime(\"%Y_%m_%d_%H_%M\") loop_hparams = trainer_lib.create_hparams(", "FLAGS.planner_hparams ) policy_dir = FLAGS.policy_dir model_dir = FLAGS.model_dir eval_metrics_dir =", "real_env, sim_env_kwargs): \"\"\"Factory function for envs.\"\"\" return { \"real\": lambda:", "metrics at.\" ) flags.DEFINE_bool(\"full_eval\", True, \"Whether to ignore the timestep", "> 0 else None, debug_video_path=FLAGS.debug_video_path ) if __name__ == \"__main__\":", "env.action_space, policy_hparams, policy_dir, sampling_temp ), \"planner\": lambda: rl_utils.PlannerAgent( # pylint:", "0) else: report_fn(eval_metrics[report_metric], 0) return eval_metrics def get_game_for_worker(map_name, directory_id): \"\"\"Get", "env.batch_size return eval_fn def evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir,", "tensor2tensor.rl.evaluator \\ --policy_dir=$HOME/t2t/rl_v1/policy \\ --eval_metrics_dir=$HOME/t2t/rl_v1/full_eval_metrics \\ --hparams_set=rlmb_base \\ --hparams='batch_size=64' \"\"\"", ") flags.DEFINE_string(\"planner_hparams\", \"\", \"Planner hparam overrides.\") flags.DEFINE_integer( \"log_every_steps\", 20, \"Log", "sampling_temp, batch_size=inner_batch_size ), make_env(env_type, env.env, sim_env_kwargs), lambda env: rl_utils.BatchStackWrapper(env, frame_stack_size),", "= get_game_for_worker( FLAGS.worker_to_game_map, FLAGS.worker_id + 1) tf.logging.info(\"Set game to %s.\"", "function for envs.\"\"\" return { \"real\": lambda: real_env.new_like( # pylint:", "(FLAGS.worker_id + 1)) policy_dir = os.path.join(cur_dir, \"policy\") model_dir = os.path.join(cur_dir,", "tf.logging.info(\"Getting game %d from %s.\" % (game_id, games)) return games[game_id]", "OR CONDITIONS OF ANY KIND, either express or implied. #", "make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=log_every_steps, video_writer=video_writer ) eval_metrics = rl_utils.evaluate_all_configs(", "FLAGS.loop_hparams ) if FLAGS.worker_to_game_map and FLAGS.total_num_workers > 1: loop_hparams.game =", "tf.gfile.Exists(eval_metrics_dir): tf.gfile.MkDir(eval_metrics_dir) evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, FLAGS.agent, FLAGS.eval_with_learner,", "map workers to games.\") flags.DEFINE_string(\"policy_dir\", \"\", \"Directory with policy checkpoints.\")", "the License is distributed on an \"AS IS\" BASIS, #", "flags.DEFINE_bool(\"full_eval\", True, \"Whether to ignore the timestep limit.\") flags.DEFINE_enum( \"agent\",", "policy_hparams, policy_dir, sampling_temp ), \"planner\": lambda: rl_utils.PlannerAgent( # pylint: disable=g-long-lambda", "worker to game map name: %s\" % map_name) games.sort() game_id", "= os.path.join(cur_dir, \"world_model\") eval_metrics_dir = os.path.join(cur_dir, \"evaluator_\" + now_tag) tf.logging.info(\"Writing", "as tf flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string(\"output_dir\", \"\",", "instead of an \" \"out-of-graph one. Works only with --agent=policy.\"", "eval_metrics = rl_utils.evaluate_all_configs( loop_hparams, policy_dir, **kwargs ) rl_utils.summarize_metrics(eval_metrics_writer, eval_metrics, 0)", "flags.DEFINE_bool( \"eval_with_learner\", True, \"Whether to use the PolicyLearner.evaluate function instead", "import trainer_model_based_params # pylint: disable=unused-import from tensor2tensor.utils import flags as", ") flags.DEFINE_string( \"debug_video_path\", \"\", \"Path to save the planner debug", "base_env = env env = rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size) sim_env_kwargs = rl.make_simulated_env_kwargs(", "video_writer=None, env_type=None): \"\"\"Factory function for Agents.\"\"\" if batch_size is None:", "worker_per_game = 5 else: raise ValueError(\"Unknown worker to game map", "env_type=None): \"\"\"Factory function for Agents.\"\"\" if batch_size is None: batch_size", "rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames( # pylint: disable=g-long-lambda **sim_env_kwargs ), }[env_type]() def make_agent( agent_type,", "rl_utils.summarize_metrics(eval_metrics_writer, eval_metrics, 0) if video_writer is not None: video_writer.finish_to_disk() #", "games)) return games[game_id] def main(_): now = datetime.datetime.now() now_tag =", "not tf.gfile.Exists(eval_metrics_dir): tf.gfile.MkDir(eval_metrics_dir) evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, FLAGS.agent,", "env.observation_space, env.action_space, policy_hparams, policy_dir, sampling_temp ), \"planner\": lambda: rl_utils.PlannerAgent( #", "return tf.contrib.training.HParams( num_rollouts=1, planning_horizon=2, rollout_agent_type=\"random\", batch_size=1, env_type=\"simulated\", ) @registry.register_hparams def", "and # limitations under the License. r\"\"\"Evaluation script for RL", "rl_utils.evaluate_all_configs( loop_hparams, policy_dir, **kwargs ) rl_utils.summarize_metrics(eval_metrics_writer, eval_metrics, 0) if video_writer", "# pylint: disable=unused-import from tensor2tensor.utils import registry from tensor2tensor.utils import", "games[game_id] def main(_): now = datetime.datetime.now() now_tag = now.strftime(\"%Y_%m_%d_%H_%M\") loop_hparams", "{} if not eval_with_learner: if debug_video_path: video_writer = common_video.WholeVideoWriter( fps=10,", "flags.DEFINE_integer(\"total_num_workers\", 1, \"How many workers in total.\") flags.DEFINE_string(\"worker_to_game_map\", \"\", \"How", "num_rollouts, planning_horizon, discount_factor=policy_hparams.gae_gamma, video_writer=video_writer ), }[agent_type]() def make_eval_fn_with_agent( agent_type, planner_hparams,", "\"planner_small\", \"Planner hparam set.\" ) flags.DEFINE_string(\"planner_hparams\", \"\", \"Planner hparam overrides.\")", "law or agreed to in writing, software # distributed under", "batch_size, make_agent( rollout_agent_type, env, policy_hparams, policy_dir, sampling_temp, batch_size=inner_batch_size ), make_env(env_type,", "\"\"\" from __future__ import absolute_import from __future__ import division from", "tensor2tensor.data_generators import gym_env from tensor2tensor.layers import common_video from tensor2tensor.models.research import", "at.\" ) # Unused flags needed to pass for multi-run", "tensor2tensor.rl import rl_utils from tensor2tensor.rl import trainer_model_based_params # pylint: disable=unused-import", "\"\"\"Eval function.\"\"\" base_env = env env = rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size) sim_env_kwargs", "function instead of an \" \"out-of-graph one. Works only with", "hparam overrides.\") flags.DEFINE_integer( \"log_every_steps\", 20, \"Log every how many environment", "import tensorflow as tf flags = tf.flags FLAGS = flags.FLAGS", "), \"planner\": lambda: rl_utils.PlannerAgent( # pylint: disable=g-long-lambda batch_size, make_agent( rollout_agent_type,", "5 else: raise ValueError(\"Unknown worker to game map name: %s\"", "elif map_name == \"human_nice\": games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE worker_per_game = 5", ") policy_dir = FLAGS.policy_dir model_dir = FLAGS.model_dir eval_metrics_dir = FLAGS.eval_metrics_dir", "flags.DEFINE_string(\"worker_to_game_map\", \"\", \"How to map workers to games.\") flags.DEFINE_string(\"policy_dir\", \"\",", "rl_utils.BatchStackWrapper(env, frame_stack_size), num_rollouts, planning_horizon, discount_factor=policy_hparams.gae_gamma, video_writer=video_writer ), }[agent_type]() def make_eval_fn_with_agent(", "loop_hparams, policy_dir, **kwargs ) rl_utils.summarize_metrics(eval_metrics_writer, eval_metrics, 0) if video_writer is", "\"eval_metrics_dir\", \"\", \"Directory to output the eval metrics at.\" )", "2018 The Tensor2Tensor Authors. # # Licensed under the Apache", "# Unused flags needed to pass for multi-run infrastructure. flags.DEFINE_bool(\"autotune\",", "+ now_tag) tf.logging.info(\"Writing metrics to %s.\" % eval_metrics_dir) if not", "import trainer_lib import tensorflow as tf flags = tf.flags FLAGS", "video_writer=video_writer ) eval_metrics = rl_utils.evaluate_all_configs( loop_hparams, policy_dir, **kwargs ) rl_utils.summarize_metrics(eval_metrics_writer,", "may obtain a copy of the License at # #", "= {} if not eval_with_learner: if debug_video_path: video_writer = common_video.WholeVideoWriter(", "the planner debug video at.\" ) # Unused flags needed", "rl_utils.run_rollouts( env, agent, env.reset(), log_every_steps=log_every_steps ) assert len(base_env.current_epoch_rollouts()) == env.batch_size", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "[\"random\", \"policy\", \"planner\"], \"Agent type to use.\" ) flags.DEFINE_bool( \"eval_with_learner\",", "not None: video_writer.finish_to_disk() # Report metrics if report_fn: if report_metric", "}[env_type]() def make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs=None, frame_stack_size=None,", "agent_type == \"policy\" if report_fn: assert report_metric is not None", "sim_env_kwargs), lambda env: rl_utils.BatchStackWrapper(env, frame_stack_size), num_rollouts, planning_horizon, discount_factor=policy_hparams.gae_gamma, video_writer=video_writer ),", "from __future__ import division from __future__ import print_function import datetime", "= None kwargs = {} if not eval_with_learner: if debug_video_path:", "may not use this file except in compliance with the", "report_fn: if report_metric == \"mean_reward\": metric_name = rl_utils.get_metric_name( sampling_temp=loop_hparams.eval_sampling_temps[0], max_num_noops=loop_hparams.eval_max_num_noops,", "gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE worker_per_game = 5 else: raise ValueError(\"Unknown worker to game", "lambda: rl_utils.PolicyAgent( # pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space, policy_hparams, policy_dir,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "import common_video from tensor2tensor.models.research import rl # pylint: disable=unused-import from", "model_dir=model_dir ) agent = make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp,", "this file except in compliance with the License. # You", "planner_small(): return tf.contrib.training.HParams( num_rollouts=64, planning_horizon=16, rollout_agent_type=\"policy\", batch_size=64, env_type=\"simulated\", ) def", "\"How many workers in total.\") flags.DEFINE_string(\"worker_to_game_map\", \"\", \"How to map", "import absolute_import from __future__ import division from __future__ import print_function", "video_writer=video_writer, env_type=planner_hparams.env_type ) rl_utils.run_rollouts( env, agent, env.reset(), log_every_steps=log_every_steps ) assert", "import datetime import os from tensor2tensor.data_generators import gym_env from tensor2tensor.layers", "rl # pylint: disable=unused-import from tensor2tensor.rl import rl_utils from tensor2tensor.rl", "def planner_tiny(): return tf.contrib.training.HParams( num_rollouts=1, planning_horizon=2, rollout_agent_type=\"random\", batch_size=1, env_type=\"simulated\", )", "every how many environment steps.\" ) flags.DEFINE_string( \"debug_video_path\", \"\", \"Path", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "game %d from %s.\" % (game_id, games)) return games[game_id] def", "= FLAGS.eval_metrics_dir if FLAGS.output_dir: cur_dir = FLAGS.output_dir if FLAGS.total_num_workers >", ") assert len(base_env.current_epoch_rollouts()) == env.batch_size return eval_fn def evaluate( loop_hparams,", "# # Licensed under the Apache License, Version 2.0 (the", "disable=unused-import from tensor2tensor.utils import flags as t2t_flags # pylint: disable=unused-import", "is not None eval_metrics_writer = tf.summary.FileWriter(eval_metrics_dir) video_writer = None kwargs", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "many environment steps.\" ) flags.DEFINE_string( \"debug_video_path\", \"\", \"Path to save", "get_game_for_worker(map_name, directory_id): \"\"\"Get game for the given worker (directory) id.\"\"\"", "policy_dir, **kwargs ) rl_utils.summarize_metrics(eval_metrics_writer, eval_metrics, 0) if video_writer is not", "environment steps.\" ) flags.DEFINE_string( \"debug_video_path\", \"\", \"Path to save the", "use the PolicyLearner.evaluate function instead of an \" \"out-of-graph one.", "map_name == \"v100unfriendly\": games = [\"chopper_command\", \"boxing\", \"asterix\", \"seaquest\"] worker_per_game", "policy_dir, sampling_temp): \"\"\"Eval function.\"\"\" base_env = env env = rl_utils.BatchStackWrapper(env,", "+ 1)) policy_dir = os.path.join(cur_dir, \"policy\") model_dir = os.path.join(cur_dir, \"world_model\")", "disable=g-long-lambda batch_size=sim_env_kwargs[\"batch_size\"], store_rollouts=False, ), \"simulated\": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames( # pylint: disable=g-long-lambda", "from %s.\" % (game_id, games)) return games[game_id] def main(_): now", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "True, \"Unused.\") flags.DEFINE_integer(\"vizier_search_algorithm\", 0, \"Unused.\") @registry.register_hparams def planner_tiny(): return tf.contrib.training.HParams(", "1, \"How many workers in total.\") flags.DEFINE_string(\"worker_to_game_map\", \"\", \"How to", "None eval_metrics_writer = tf.summary.FileWriter(eval_metrics_dir) video_writer = None kwargs = {}", "checkpoints.\") flags.DEFINE_string(\"model_dir\", \"\", \"Directory with model checkpoints.\") flags.DEFINE_string( \"eval_metrics_dir\", \"\",", "FLAGS.worker_to_game_map, FLAGS.worker_id + 1) tf.logging.info(\"Set game to %s.\" % loop_hparams.game)", "# Copyright 2018 The Tensor2Tensor Authors. # # Licensed under", "policy_dir, sampling_temp, sim_env_kwargs=None, frame_stack_size=None, planning_horizon=None, rollout_agent_type=None, batch_size=None, num_rollouts=None, inner_batch_size=None, video_writer=None,", "map name: %s\" % map_name) games.sort() game_id = (directory_id -", "cur_dir = FLAGS.output_dir if FLAGS.total_num_workers > 1: cur_dir = os.path.join(cur_dir,", "trainer_lib.create_hparams( FLAGS.loop_hparams_set, FLAGS.loop_hparams ) if FLAGS.worker_to_game_map and FLAGS.total_num_workers > 1:", "the Agent API.\"\"\" def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp): \"\"\"Eval", "evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, FLAGS.agent, FLAGS.eval_with_learner, FLAGS.log_every_steps if", "from tensor2tensor.rl import trainer_model_based_params # pylint: disable=unused-import from tensor2tensor.utils import", "\"Unused.\") flags.DEFINE_bool(\"maximize_tuner_objective\", True, \"Unused.\") flags.DEFINE_integer(\"vizier_search_algorithm\", 0, \"Unused.\") @registry.register_hparams def planner_tiny():", "from tensor2tensor.rl import rl_utils from tensor2tensor.rl import trainer_model_based_params # pylint:", "flags.DEFINE_string( \"planner_hparams_set\", \"planner_small\", \"Planner hparam set.\" ) flags.DEFINE_string(\"planner_hparams\", \"\", \"Planner", "if FLAGS.worker_to_game_map and FLAGS.total_num_workers > 1: loop_hparams.game = get_game_for_worker( FLAGS.worker_to_game_map,", "loop_hparams.game = get_game_for_worker( FLAGS.worker_to_game_map, FLAGS.worker_id + 1) tf.logging.info(\"Set game to", "import flags as t2t_flags # pylint: disable=unused-import from tensor2tensor.utils import", "batch_size=64, env_type=\"simulated\", ) def make_env(env_type, real_env, sim_env_kwargs): \"\"\"Factory function for", "workers in total.\") flags.DEFINE_string(\"worker_to_game_map\", \"\", \"How to map workers to", "FLAGS.planner_hparams_set, FLAGS.planner_hparams ) policy_dir = FLAGS.policy_dir model_dir = FLAGS.model_dir eval_metrics_dir", "video_writer=None ): \"\"\"Returns an out-of-graph eval_fn using the Agent API.\"\"\"", "os from tensor2tensor.data_generators import gym_env from tensor2tensor.layers import common_video from", "return { \"random\": lambda: rl_utils.RandomAgent( # pylint: disable=g-long-lambda batch_size, env.observation_space,", "return games[game_id] def main(_): now = datetime.datetime.now() now_tag = now.strftime(\"%Y_%m_%d_%H_%M\")", "flags.DEFINE_string( \"debug_video_path\", \"\", \"Path to save the planner debug video", "FLAGS.output_dir: cur_dir = FLAGS.output_dir if FLAGS.total_num_workers > 1: cur_dir =", "= env.batch_size return { \"random\": lambda: rl_utils.RandomAgent( # pylint: disable=g-long-lambda", "planner_hparams, policy_dir, model_dir, eval_metrics_dir, FLAGS.agent, FLAGS.eval_with_learner, FLAGS.log_every_steps if FLAGS.log_every_steps >", "= 5 else: raise ValueError(\"Unknown worker to game map name:", "planning_horizon=2, rollout_agent_type=\"random\", batch_size=1, env_type=\"simulated\", ) @registry.register_hparams def planner_small(): return tf.contrib.training.HParams(", "games.\") flags.DEFINE_string(\"policy_dir\", \"\", \"Directory with policy checkpoints.\") flags.DEFINE_string(\"model_dir\", \"\", \"Directory", "%d from %s.\" % (game_id, games)) return games[game_id] def main(_):", "FLAGS.total_num_workers > 1: cur_dir = os.path.join(cur_dir, \"%d\" % (FLAGS.worker_id +", "fps=10, output_path=debug_video_path, file_format=\"avi\") kwargs[\"eval_fn\"] = make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=log_every_steps,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "): \"\"\"Returns an out-of-graph eval_fn using the Agent API.\"\"\" def", "%s.\" % loop_hparams.game) if FLAGS.full_eval: loop_hparams.eval_rl_env_max_episode_steps = -1 planner_hparams =", "policy_dir, model_dir, eval_metrics_dir, agent_type, eval_with_learner, log_every_steps, debug_video_path, report_fn=None, report_metric=None ):", "here.\") flags.DEFINE_string(\"client_handle\", \"client_0\", \"Unused.\") flags.DEFINE_bool(\"maximize_tuner_objective\", True, \"Unused.\") flags.DEFINE_integer(\"vizier_search_algorithm\", 0, \"Unused.\")", "os.path.join(cur_dir, \"policy\") model_dir = os.path.join(cur_dir, \"world_model\") eval_metrics_dir = os.path.join(cur_dir, \"evaluator_\"", "report_metric=None ): \"\"\"Evaluate.\"\"\" if eval_with_learner: assert agent_type == \"policy\" if", "lambda env: rl_utils.BatchStackWrapper(env, frame_stack_size), num_rollouts, planning_horizon, discount_factor=policy_hparams.gae_gamma, video_writer=video_writer ), }[agent_type]()", "report_fn(eval_metrics[report_metric], 0) return eval_metrics def get_game_for_worker(map_name, directory_id): \"\"\"Get game for", "%s\" % map_name) games.sort() game_id = (directory_id - 1) //", "FLAGS.log_every_steps > 0 else None, debug_video_path=FLAGS.debug_video_path ) if __name__ ==", "tf.contrib.training.HParams( num_rollouts=64, planning_horizon=16, rollout_agent_type=\"policy\", batch_size=64, env_type=\"simulated\", ) def make_env(env_type, real_env,", "rollout_agent_type, env, policy_hparams, policy_dir, sampling_temp, batch_size=inner_batch_size ), make_env(env_type, env.env, sim_env_kwargs),", "model_dir = os.path.join(cur_dir, \"world_model\") eval_metrics_dir = os.path.join(cur_dir, \"evaluator_\" + now_tag)", "or implied. # See the License for the specific language", "lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames( # pylint: disable=g-long-lambda **sim_env_kwargs ), }[env_type]() def make_agent(", "with policy checkpoints.\") flags.DEFINE_string(\"model_dir\", \"\", \"Directory with model checkpoints.\") flags.DEFINE_string(", "eval_with_learner: assert agent_type == \"policy\" if report_fn: assert report_metric is", "-1 planner_hparams = trainer_lib.create_hparams( FLAGS.planner_hparams_set, FLAGS.planner_hparams ) policy_dir = FLAGS.policy_dir", "pylint: disable=unused-import from tensor2tensor.utils import flags as t2t_flags # pylint:", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "\"seaquest\"] worker_per_game = 5 elif map_name == \"human_nice\": games =", "), }[agent_type]() def make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=None, video_writer=None ):", "= rl_utils.evaluate_all_configs( loop_hparams, policy_dir, **kwargs ) rl_utils.summarize_metrics(eval_metrics_writer, eval_metrics, 0) if", "\"mean_reward\": metric_name = rl_utils.get_metric_name( sampling_temp=loop_hparams.eval_sampling_temps[0], max_num_noops=loop_hparams.eval_max_num_noops, clipped=False ) report_fn(eval_metrics[metric_name], 0)", "5 elif map_name == \"human_nice\": games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE worker_per_game =", "__future__ import print_function import datetime import os from tensor2tensor.data_generators import", "tensor2tensor.models.research import rl # pylint: disable=unused-import from tensor2tensor.rl import rl_utils", "\"out-of-graph one. Works only with --agent=policy.\" ) flags.DEFINE_string( \"planner_hparams_set\", \"planner_small\",", "\"Unused here.\") flags.DEFINE_string(\"client_handle\", \"client_0\", \"Unused.\") flags.DEFINE_bool(\"maximize_tuner_objective\", True, \"Unused.\") flags.DEFINE_integer(\"vizier_search_algorithm\", 0,", "debug_video_path, report_fn=None, report_metric=None ): \"\"\"Evaluate.\"\"\" if eval_with_learner: assert agent_type ==", "= -1 planner_hparams = trainer_lib.create_hparams( FLAGS.planner_hparams_set, FLAGS.planner_hparams ) policy_dir =", "t2t_flags # pylint: disable=unused-import from tensor2tensor.utils import registry from tensor2tensor.utils", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "\"Whether to use the PolicyLearner.evaluate function instead of an \"", "\"random\": lambda: rl_utils.RandomAgent( # pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space ),", "loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, agent_type, eval_with_learner, log_every_steps, debug_video_path, report_fn=None,", "\"human_nice\": games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE worker_per_game = 5 else: raise ValueError(\"Unknown", "to %s.\" % eval_metrics_dir) if not tf.gfile.Exists(eval_metrics_dir): tf.gfile.MkDir(eval_metrics_dir) evaluate( loop_hparams,", "division from __future__ import print_function import datetime import os from", "pylint: disable=g-long-lambda batch_size=sim_env_kwargs[\"batch_size\"], store_rollouts=False, ), \"simulated\": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames( # pylint:", "real_env.new_like( # pylint: disable=g-long-lambda batch_size=sim_env_kwargs[\"batch_size\"], store_rollouts=False, ), \"simulated\": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames(", "# pylint: disable=unused-import from tensor2tensor.utils import flags as t2t_flags #", "flags.DEFINE_string(\"policy_dir\", \"\", \"Directory with policy checkpoints.\") flags.DEFINE_string(\"model_dir\", \"\", \"Directory with", "\"\", \"Directory with policy checkpoints.\") flags.DEFINE_string(\"model_dir\", \"\", \"Directory with model", "(directory) id.\"\"\" if map_name == \"v100unfriendly\": games = [\"chopper_command\", \"boxing\",", "loop_hparams.frame_stack_size) sim_env_kwargs = rl.make_simulated_env_kwargs( base_env, loop_hparams, batch_size=planner_hparams.batch_size, model_dir=model_dir ) agent", "flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string(\"output_dir\", \"\", \"Main directory", "\"policy\") model_dir = os.path.join(cur_dir, \"world_model\") eval_metrics_dir = os.path.join(cur_dir, \"evaluator_\" +", "(the \"License\"); # you may not use this file except", "# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # #", "# you may not use this file except in compliance", ") agent = make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs,", "output_path=debug_video_path, file_format=\"avi\") kwargs[\"eval_fn\"] = make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=log_every_steps, video_writer=video_writer", "import registry from tensor2tensor.utils import trainer_lib import tensorflow as tf", "tf.contrib.training.HParams( num_rollouts=1, planning_horizon=2, rollout_agent_type=\"random\", batch_size=1, env_type=\"simulated\", ) @registry.register_hparams def planner_small():", "batch_size = env.batch_size return { \"random\": lambda: rl_utils.RandomAgent( # pylint:", "is None: batch_size = env.batch_size return { \"random\": lambda: rl_utils.RandomAgent(", "policy_dir, model_dir, eval_metrics_dir, FLAGS.agent, FLAGS.eval_with_learner, FLAGS.log_every_steps if FLAGS.log_every_steps > 0", "= 5 elif map_name == \"human_nice\": games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE worker_per_game", "len(base_env.current_epoch_rollouts()) == env.batch_size return eval_fn def evaluate( loop_hparams, planner_hparams, policy_dir,", "1: cur_dir = os.path.join(cur_dir, \"%d\" % (FLAGS.worker_id + 1)) policy_dir", "log_every_steps=log_every_steps, video_writer=video_writer ) eval_metrics = rl_utils.evaluate_all_configs( loop_hparams, policy_dir, **kwargs )", "import os from tensor2tensor.data_generators import gym_env from tensor2tensor.layers import common_video", "{ \"real\": lambda: real_env.new_like( # pylint: disable=g-long-lambda batch_size=sim_env_kwargs[\"batch_size\"], store_rollouts=False, ),", "flags.DEFINE_bool(\"maximize_tuner_objective\", True, \"Unused.\") flags.DEFINE_integer(\"vizier_search_algorithm\", 0, \"Unused.\") @registry.register_hparams def planner_tiny(): return", "from tensor2tensor.utils import registry from tensor2tensor.utils import trainer_lib import tensorflow", "License. r\"\"\"Evaluation script for RL agents. Example invocation: python -m", "policy_hparams, policy_dir, sampling_temp, batch_size=inner_batch_size ), make_env(env_type, env.env, sim_env_kwargs), lambda env:", "\" \"out-of-graph one. Works only with --agent=policy.\" ) flags.DEFINE_string( \"planner_hparams_set\",", "assert agent_type == \"policy\" if report_fn: assert report_metric is not", "the eval metrics at.\" ) flags.DEFINE_bool(\"full_eval\", True, \"Whether to ignore", "0 else None, debug_video_path=FLAGS.debug_video_path ) if __name__ == \"__main__\": tf.logging.set_verbosity(tf.logging.INFO)", "sampling_temp): \"\"\"Eval function.\"\"\" base_env = env env = rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size)", "\"Planner hparam overrides.\") flags.DEFINE_integer( \"log_every_steps\", 20, \"Log every how many", "tensor2tensor.rl import trainer_model_based_params # pylint: disable=unused-import from tensor2tensor.utils import flags", ") @registry.register_hparams def planner_small(): return tf.contrib.training.HParams( num_rollouts=64, planning_horizon=16, rollout_agent_type=\"policy\", batch_size=64,", "def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp): \"\"\"Eval function.\"\"\" base_env =", "@registry.register_hparams def planner_small(): return tf.contrib.training.HParams( num_rollouts=64, planning_horizon=16, rollout_agent_type=\"policy\", batch_size=64, env_type=\"simulated\",", "# # Unless required by applicable law or agreed to", "= make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs, loop_hparams.frame_stack_size, planner_hparams.planning_horizon,", "return eval_fn def evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, agent_type,", "== \"policy\" if report_fn: assert report_metric is not None eval_metrics_writer", "FLAGS.worker_id + 1) tf.logging.info(\"Set game to %s.\" % loop_hparams.game) if", "--eval_metrics_dir=$HOME/t2t/rl_v1/full_eval_metrics \\ --hparams_set=rlmb_base \\ --hparams='batch_size=64' \"\"\" from __future__ import absolute_import", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "tensor2tensor.utils import trainer_lib import tensorflow as tf flags = tf.flags", "multi-runs.\") flags.DEFINE_integer(\"total_num_workers\", 1, \"How many workers in total.\") flags.DEFINE_string(\"worker_to_game_map\", \"\",", "\"\"\"Factory function for envs.\"\"\" return { \"real\": lambda: real_env.new_like( #", "make_env(env_type, env.env, sim_env_kwargs), lambda env: rl_utils.BatchStackWrapper(env, frame_stack_size), num_rollouts, planning_horizon, discount_factor=policy_hparams.gae_gamma,", "steps.\" ) flags.DEFINE_string( \"debug_video_path\", \"\", \"Path to save the planner", "rl_utils.RandomAgent( # pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space ), \"policy\": lambda:", "Version 2.0 (the \"License\"); # you may not use this", "-m tensor2tensor.rl.evaluator \\ --policy_dir=$HOME/t2t/rl_v1/policy \\ --eval_metrics_dir=$HOME/t2t/rl_v1/full_eval_metrics \\ --hparams_set=rlmb_base \\ --hparams='batch_size=64'", "def get_game_for_worker(map_name, directory_id): \"\"\"Get game for the given worker (directory)", "lambda: rl_utils.PlannerAgent( # pylint: disable=g-long-lambda batch_size, make_agent( rollout_agent_type, env, policy_hparams,", "import division from __future__ import print_function import datetime import os", "\"Directory to output the eval metrics at.\" ) flags.DEFINE_bool(\"full_eval\", True,", "out-of-graph eval_fn using the Agent API.\"\"\" def eval_fn(env, loop_hparams, policy_hparams,", "print_function import datetime import os from tensor2tensor.data_generators import gym_env from", "lambda: real_env.new_like( # pylint: disable=g-long-lambda batch_size=sim_env_kwargs[\"batch_size\"], store_rollouts=False, ), \"simulated\": lambda:", "def make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=None, video_writer=None ): \"\"\"Returns an", "agent_type, planner_hparams, model_dir, log_every_steps=None, video_writer=None ): \"\"\"Returns an out-of-graph eval_fn", "1) tf.logging.info(\"Set game to %s.\" % loop_hparams.game) if FLAGS.full_eval: loop_hparams.eval_rl_env_max_episode_steps", "batch_size=sim_env_kwargs[\"batch_size\"], store_rollouts=False, ), \"simulated\": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames( # pylint: disable=g-long-lambda **sim_env_kwargs", "\"planner\": lambda: rl_utils.PlannerAgent( # pylint: disable=g-long-lambda batch_size, make_agent( rollout_agent_type, env,", "if report_fn: assert report_metric is not None eval_metrics_writer = tf.summary.FileWriter(eval_metrics_dir)", "video_writer = common_video.WholeVideoWriter( fps=10, output_path=debug_video_path, file_format=\"avi\") kwargs[\"eval_fn\"] = make_eval_fn_with_agent( agent_type,", "__future__ import absolute_import from __future__ import division from __future__ import", ") eval_metrics = rl_utils.evaluate_all_configs( loop_hparams, policy_dir, **kwargs ) rl_utils.summarize_metrics(eval_metrics_writer, eval_metrics,", "pass for multi-run infrastructure. flags.DEFINE_bool(\"autotune\", False, \"Unused here.\") flags.DEFINE_string(\"objective\", \"\",", "\"Unused.\") flags.DEFINE_integer(\"vizier_search_algorithm\", 0, \"Unused.\") @registry.register_hparams def planner_tiny(): return tf.contrib.training.HParams( num_rollouts=1,", "implied. # See the License for the specific language governing", "tf.gfile.MkDir(eval_metrics_dir) evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, FLAGS.agent, FLAGS.eval_with_learner, FLAGS.log_every_steps", "under the Apache License, Version 2.0 (the \"License\"); # you", "to save the planner debug video at.\" ) # Unused", "planner_hparams, model_dir, log_every_steps=log_every_steps, video_writer=video_writer ) eval_metrics = rl_utils.evaluate_all_configs( loop_hparams, policy_dir,", "policy_dir, sampling_temp, batch_size=inner_batch_size ), make_env(env_type, env.env, sim_env_kwargs), lambda env: rl_utils.BatchStackWrapper(env,", "\"Unused.\") @registry.register_hparams def planner_tiny(): return tf.contrib.training.HParams( num_rollouts=1, planning_horizon=2, rollout_agent_type=\"random\", batch_size=1,", "= os.path.join(cur_dir, \"evaluator_\" + now_tag) tf.logging.info(\"Writing metrics to %s.\" %", "needed to pass for multi-run infrastructure. flags.DEFINE_bool(\"autotune\", False, \"Unused here.\")", "metrics to %s.\" % eval_metrics_dir) if not tf.gfile.Exists(eval_metrics_dir): tf.gfile.MkDir(eval_metrics_dir) evaluate(", "limit.\") flags.DEFINE_enum( \"agent\", \"policy\", [\"random\", \"policy\", \"planner\"], \"Agent type to", "loop_hparams, batch_size=planner_hparams.batch_size, model_dir=model_dir ) agent = make_agent( agent_type, env, policy_hparams,", "@registry.register_hparams def planner_tiny(): return tf.contrib.training.HParams( num_rollouts=1, planning_horizon=2, rollout_agent_type=\"random\", batch_size=1, env_type=\"simulated\",", "**sim_env_kwargs ), }[env_type]() def make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp,", "env, agent, env.reset(), log_every_steps=log_every_steps ) assert len(base_env.current_epoch_rollouts()) == env.batch_size return", "by applicable law or agreed to in writing, software #", "trainer_model_based_params # pylint: disable=unused-import from tensor2tensor.utils import flags as t2t_flags", ") report_fn(eval_metrics[metric_name], 0) else: report_fn(eval_metrics[report_metric], 0) return eval_metrics def get_game_for_worker(map_name,", "in total.\") flags.DEFINE_string(\"worker_to_game_map\", \"\", \"How to map workers to games.\")", "\"simulated\": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames( # pylint: disable=g-long-lambda **sim_env_kwargs ), }[env_type]() def", "rollout_agent_type=None, batch_size=None, num_rollouts=None, inner_batch_size=None, video_writer=None, env_type=None): \"\"\"Factory function for Agents.\"\"\"", "rl_utils.PlannerAgent( # pylint: disable=g-long-lambda batch_size, make_agent( rollout_agent_type, env, policy_hparams, policy_dir,", "model_dir = FLAGS.model_dir eval_metrics_dir = FLAGS.eval_metrics_dir if FLAGS.output_dir: cur_dir =", "under the License. r\"\"\"Evaluation script for RL agents. Example invocation:", "env.action_space ), \"policy\": lambda: rl_utils.PolicyAgent( # pylint: disable=g-long-lambda batch_size, env.observation_space,", "sim_env_kwargs, loop_hparams.frame_stack_size, planner_hparams.planning_horizon, planner_hparams.rollout_agent_type, num_rollouts=planner_hparams.num_rollouts, inner_batch_size=planner_hparams.batch_size, video_writer=video_writer, env_type=planner_hparams.env_type ) rl_utils.run_rollouts(", "env.observation_space, env.action_space ), \"policy\": lambda: rl_utils.PolicyAgent( # pylint: disable=g-long-lambda batch_size,", "script for RL agents. Example invocation: python -m tensor2tensor.rl.evaluator \\", "id.\"\"\" if map_name == \"v100unfriendly\": games = [\"chopper_command\", \"boxing\", \"asterix\",", "num_rollouts=planner_hparams.num_rollouts, inner_batch_size=planner_hparams.batch_size, video_writer=video_writer, env_type=planner_hparams.env_type ) rl_utils.run_rollouts( env, agent, env.reset(), log_every_steps=log_every_steps", "frame_stack_size), num_rollouts, planning_horizon, discount_factor=policy_hparams.gae_gamma, video_writer=video_writer ), }[agent_type]() def make_eval_fn_with_agent( agent_type,", "False, \"Unused here.\") flags.DEFINE_string(\"objective\", \"\", \"Unused here.\") flags.DEFINE_string(\"client_handle\", \"client_0\", \"Unused.\")", "FLAGS.worker_to_game_map and FLAGS.total_num_workers > 1: loop_hparams.game = get_game_for_worker( FLAGS.worker_to_game_map, FLAGS.worker_id", "many workers in total.\") flags.DEFINE_string(\"worker_to_game_map\", \"\", \"How to map workers", "the License. r\"\"\"Evaluation script for RL agents. Example invocation: python", "# pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space, policy_hparams, policy_dir, sampling_temp ),", "model_dir, log_every_steps=None, video_writer=None ): \"\"\"Returns an out-of-graph eval_fn using the", "def make_env(env_type, real_env, sim_env_kwargs): \"\"\"Factory function for envs.\"\"\" return {", "loop_hparams.eval_rl_env_max_episode_steps = -1 planner_hparams = trainer_lib.create_hparams( FLAGS.planner_hparams_set, FLAGS.planner_hparams ) policy_dir", "batch_size is None: batch_size = env.batch_size return { \"random\": lambda:", "worker_per_game tf.logging.info(\"Getting game %d from %s.\" % (game_id, games)) return", ") flags.DEFINE_bool(\"full_eval\", True, \"Whether to ignore the timestep limit.\") flags.DEFINE_enum(", "make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=None, video_writer=None ): \"\"\"Returns an out-of-graph", "given worker (directory) id.\"\"\" if map_name == \"v100unfriendly\": games =", "for multi-runs.\") flags.DEFINE_integer(\"total_num_workers\", 1, \"How many workers in total.\") flags.DEFINE_string(\"worker_to_game_map\",", "planner_hparams, model_dir, log_every_steps=None, video_writer=None ): \"\"\"Returns an out-of-graph eval_fn using", "1)) policy_dir = os.path.join(cur_dir, \"policy\") model_dir = os.path.join(cur_dir, \"world_model\") eval_metrics_dir", "use.\" ) flags.DEFINE_bool( \"eval_with_learner\", True, \"Whether to use the PolicyLearner.evaluate", "(game_id, games)) return games[game_id] def main(_): now = datetime.datetime.now() now_tag", "and FLAGS.total_num_workers > 1: loop_hparams.game = get_game_for_worker( FLAGS.worker_to_game_map, FLAGS.worker_id +", "{ \"random\": lambda: rl_utils.RandomAgent( # pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space", "sampling_temp ), \"planner\": lambda: rl_utils.PlannerAgent( # pylint: disable=g-long-lambda batch_size, make_agent(", "}[agent_type]() def make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=None, video_writer=None ): \"\"\"Returns", "for RL agents. Example invocation: python -m tensor2tensor.rl.evaluator \\ --policy_dir=$HOME/t2t/rl_v1/policy", "max_num_noops=loop_hparams.eval_max_num_noops, clipped=False ) report_fn(eval_metrics[metric_name], 0) else: report_fn(eval_metrics[report_metric], 0) return eval_metrics", "else None, debug_video_path=FLAGS.debug_video_path ) if __name__ == \"__main__\": tf.logging.set_verbosity(tf.logging.INFO) tf.app.run()", "# Report metrics if report_fn: if report_metric == \"mean_reward\": metric_name", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "batch_size=None, num_rollouts=None, inner_batch_size=None, video_writer=None, env_type=None): \"\"\"Factory function for Agents.\"\"\" if", "Unless required by applicable law or agreed to in writing,", "FLAGS.loop_hparams_set, FLAGS.loop_hparams ) if FLAGS.worker_to_game_map and FLAGS.total_num_workers > 1: loop_hparams.game", "policy_hparams, policy_dir, sampling_temp, sim_env_kwargs=None, frame_stack_size=None, planning_horizon=None, rollout_agent_type=None, batch_size=None, num_rollouts=None, inner_batch_size=None,", "policy checkpoints.\") flags.DEFINE_string(\"model_dir\", \"\", \"Directory with model checkpoints.\") flags.DEFINE_string( \"eval_metrics_dir\",", "import rl_utils from tensor2tensor.rl import trainer_model_based_params # pylint: disable=unused-import from", "log_every_steps, debug_video_path, report_fn=None, report_metric=None ): \"\"\"Evaluate.\"\"\" if eval_with_learner: assert agent_type", "eval_metrics_writer = tf.summary.FileWriter(eval_metrics_dir) video_writer = None kwargs = {} if", "python -m tensor2tensor.rl.evaluator \\ --policy_dir=$HOME/t2t/rl_v1/policy \\ --eval_metrics_dir=$HOME/t2t/rl_v1/full_eval_metrics \\ --hparams_set=rlmb_base \\", "the specific language governing permissions and # limitations under the", "kwargs[\"eval_fn\"] = make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=log_every_steps, video_writer=video_writer ) eval_metrics", "policy_dir, sampling_temp ), \"planner\": lambda: rl_utils.PlannerAgent( # pylint: disable=g-long-lambda batch_size,", "FLAGS.full_eval: loop_hparams.eval_rl_env_max_episode_steps = -1 planner_hparams = trainer_lib.create_hparams( FLAGS.planner_hparams_set, FLAGS.planner_hparams )", "language governing permissions and # limitations under the License. r\"\"\"Evaluation", "flags.DEFINE_string(\"objective\", \"\", \"Unused here.\") flags.DEFINE_string(\"client_handle\", \"client_0\", \"Unused.\") flags.DEFINE_bool(\"maximize_tuner_objective\", True, \"Unused.\")", "applicable law or agreed to in writing, software # distributed", "PolicyLearner.evaluate function instead of an \" \"out-of-graph one. Works only", "map_name == \"human_nice\": games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE worker_per_game = 5 else:", "): \"\"\"Evaluate.\"\"\" if eval_with_learner: assert agent_type == \"policy\" if report_fn:", "agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs, loop_hparams.frame_stack_size, planner_hparams.planning_horizon, planner_hparams.rollout_agent_type, num_rollouts=planner_hparams.num_rollouts,", "), }[env_type]() def make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs=None,", "report_fn=None, report_metric=None ): \"\"\"Evaluate.\"\"\" if eval_with_learner: assert agent_type == \"policy\"", "--hparams='batch_size=64' \"\"\" from __future__ import absolute_import from __future__ import division", "tensorflow as tf flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string(\"output_dir\",", "name: %s\" % map_name) games.sort() game_id = (directory_id - 1)", "in writing, software # distributed under the License is distributed", "flags.DEFINE_string(\"client_handle\", \"client_0\", \"Unused.\") flags.DEFINE_bool(\"maximize_tuner_objective\", True, \"Unused.\") flags.DEFINE_integer(\"vizier_search_algorithm\", 0, \"Unused.\") @registry.register_hparams", "--policy_dir=$HOME/t2t/rl_v1/policy \\ --eval_metrics_dir=$HOME/t2t/rl_v1/full_eval_metrics \\ --hparams_set=rlmb_base \\ --hparams='batch_size=64' \"\"\" from __future__", "datetime.datetime.now() now_tag = now.strftime(\"%Y_%m_%d_%H_%M\") loop_hparams = trainer_lib.create_hparams( FLAGS.loop_hparams_set, FLAGS.loop_hparams )", "store_rollouts=False, ), \"simulated\": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames( # pylint: disable=g-long-lambda **sim_env_kwargs ),", "planning_horizon=None, rollout_agent_type=None, batch_size=None, num_rollouts=None, inner_batch_size=None, video_writer=None, env_type=None): \"\"\"Factory function for", "# pylint: disable=g-long-lambda **sim_env_kwargs ), }[env_type]() def make_agent( agent_type, env,", "sampling_temp, sim_env_kwargs, loop_hparams.frame_stack_size, planner_hparams.planning_horizon, planner_hparams.rollout_agent_type, num_rollouts=planner_hparams.num_rollouts, inner_batch_size=planner_hparams.batch_size, video_writer=video_writer, env_type=planner_hparams.env_type )", "== \"mean_reward\": metric_name = rl_utils.get_metric_name( sampling_temp=loop_hparams.eval_sampling_temps[0], max_num_noops=loop_hparams.eval_max_num_noops, clipped=False ) report_fn(eval_metrics[metric_name],", "planning_horizon=16, rollout_agent_type=\"policy\", batch_size=64, env_type=\"simulated\", ) def make_env(env_type, real_env, sim_env_kwargs): \"\"\"Factory", "flags.DEFINE_string( \"eval_metrics_dir\", \"\", \"Directory to output the eval metrics at.\"", "API.\"\"\" def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp): \"\"\"Eval function.\"\"\" base_env", "directory_id): \"\"\"Get game for the given worker (directory) id.\"\"\" if", "policy_hparams, policy_dir, sampling_temp, sim_env_kwargs, loop_hparams.frame_stack_size, planner_hparams.planning_horizon, planner_hparams.rollout_agent_type, num_rollouts=planner_hparams.num_rollouts, inner_batch_size=planner_hparams.batch_size, video_writer=video_writer,", "// worker_per_game tf.logging.info(\"Getting game %d from %s.\" % (game_id, games))", "flags.DEFINE_string(\"output_dir\", \"\", \"Main directory for multi-runs.\") flags.DEFINE_integer(\"total_num_workers\", 1, \"How many", "pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space, policy_hparams, policy_dir, sampling_temp ), \"planner\":", "1: loop_hparams.game = get_game_for_worker( FLAGS.worker_to_game_map, FLAGS.worker_id + 1) tf.logging.info(\"Set game", "debug_video_path: video_writer = common_video.WholeVideoWriter( fps=10, output_path=debug_video_path, file_format=\"avi\") kwargs[\"eval_fn\"] = make_eval_fn_with_agent(", "Authors. # # Licensed under the Apache License, Version 2.0", "rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size) sim_env_kwargs = rl.make_simulated_env_kwargs( base_env, loop_hparams, batch_size=planner_hparams.batch_size, model_dir=model_dir )", "tensor2tensor.utils import flags as t2t_flags # pylint: disable=unused-import from tensor2tensor.utils", "disable=g-long-lambda **sim_env_kwargs ), }[env_type]() def make_agent( agent_type, env, policy_hparams, policy_dir,", "assert report_metric is not None eval_metrics_writer = tf.summary.FileWriter(eval_metrics_dir) video_writer =", "% map_name) games.sort() game_id = (directory_id - 1) // worker_per_game", "planner_hparams, policy_dir, model_dir, eval_metrics_dir, agent_type, eval_with_learner, log_every_steps, debug_video_path, report_fn=None, report_metric=None", "to use the PolicyLearner.evaluate function instead of an \" \"out-of-graph", "eval_metrics_dir, FLAGS.agent, FLAGS.eval_with_learner, FLAGS.log_every_steps if FLAGS.log_every_steps > 0 else None,", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "flags.FLAGS flags.DEFINE_string(\"output_dir\", \"\", \"Main directory for multi-runs.\") flags.DEFINE_integer(\"total_num_workers\", 1, \"How", "output the eval metrics at.\" ) flags.DEFINE_bool(\"full_eval\", True, \"Whether to", "planner_tiny(): return tf.contrib.training.HParams( num_rollouts=1, planning_horizon=2, rollout_agent_type=\"random\", batch_size=1, env_type=\"simulated\", ) @registry.register_hparams", "# You may obtain a copy of the License at", "\"Path to save the planner debug video at.\" ) #", "rl.make_simulated_env_kwargs( base_env, loop_hparams, batch_size=planner_hparams.batch_size, model_dir=model_dir ) agent = make_agent( agent_type,", "evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, agent_type, eval_with_learner, log_every_steps, debug_video_path,", "= tf.summary.FileWriter(eval_metrics_dir) video_writer = None kwargs = {} if not", "FLAGS.eval_with_learner, FLAGS.log_every_steps if FLAGS.log_every_steps > 0 else None, debug_video_path=FLAGS.debug_video_path )", "if report_fn: if report_metric == \"mean_reward\": metric_name = rl_utils.get_metric_name( sampling_temp=loop_hparams.eval_sampling_temps[0],", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "trainer_lib import tensorflow as tf flags = tf.flags FLAGS =", "), \"policy\": lambda: rl_utils.PolicyAgent( # pylint: disable=g-long-lambda batch_size, env.observation_space, env.action_space,", "== \"human_nice\": games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE worker_per_game = 5 else: raise", "= os.path.join(cur_dir, \"%d\" % (FLAGS.worker_id + 1)) policy_dir = os.path.join(cur_dir,", "to games.\") flags.DEFINE_string(\"policy_dir\", \"\", \"Directory with policy checkpoints.\") flags.DEFINE_string(\"model_dir\", \"\",", "flags as t2t_flags # pylint: disable=unused-import from tensor2tensor.utils import registry", "% (game_id, games)) return games[game_id] def main(_): now = datetime.datetime.now()", "FLAGS.agent, FLAGS.eval_with_learner, FLAGS.log_every_steps if FLAGS.log_every_steps > 0 else None, debug_video_path=FLAGS.debug_video_path", "if eval_with_learner: assert agent_type == \"policy\" if report_fn: assert report_metric", "FLAGS.model_dir eval_metrics_dir = FLAGS.eval_metrics_dir if FLAGS.output_dir: cur_dir = FLAGS.output_dir if", "# pylint: disable=unused-import from tensor2tensor.rl import rl_utils from tensor2tensor.rl import", "clipped=False ) report_fn(eval_metrics[metric_name], 0) else: report_fn(eval_metrics[report_metric], 0) return eval_metrics def", "= rl.make_simulated_env_kwargs( base_env, loop_hparams, batch_size=planner_hparams.batch_size, model_dir=model_dir ) agent = make_agent(", "now.strftime(\"%Y_%m_%d_%H_%M\") loop_hparams = trainer_lib.create_hparams( FLAGS.loop_hparams_set, FLAGS.loop_hparams ) if FLAGS.worker_to_game_map and", "one. Works only with --agent=policy.\" ) flags.DEFINE_string( \"planner_hparams_set\", \"planner_small\", \"Planner", "permissions and # limitations under the License. r\"\"\"Evaluation script for", "the License for the specific language governing permissions and #", "here.\") flags.DEFINE_string(\"objective\", \"\", \"Unused here.\") flags.DEFINE_string(\"client_handle\", \"client_0\", \"Unused.\") flags.DEFINE_bool(\"maximize_tuner_objective\", True,", "for Agents.\"\"\" if batch_size is None: batch_size = env.batch_size return", "using the Agent API.\"\"\" def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp):", "Apache License, Version 2.0 (the \"License\"); # you may not", "loop_hparams.game) if FLAGS.full_eval: loop_hparams.eval_rl_env_max_episode_steps = -1 planner_hparams = trainer_lib.create_hparams( FLAGS.planner_hparams_set,", "% eval_metrics_dir) if not tf.gfile.Exists(eval_metrics_dir): tf.gfile.MkDir(eval_metrics_dir) evaluate( loop_hparams, planner_hparams, policy_dir,", "either express or implied. # See the License for the", "report_fn: assert report_metric is not None eval_metrics_writer = tf.summary.FileWriter(eval_metrics_dir) video_writer", "tensor2tensor.utils import registry from tensor2tensor.utils import trainer_lib import tensorflow as", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "agent, env.reset(), log_every_steps=log_every_steps ) assert len(base_env.current_epoch_rollouts()) == env.batch_size return eval_fn", "agent_type, planner_hparams, model_dir, log_every_steps=log_every_steps, video_writer=video_writer ) eval_metrics = rl_utils.evaluate_all_configs( loop_hparams,", "from tensor2tensor.layers import common_video from tensor2tensor.models.research import rl # pylint:", "\"eval_with_learner\", True, \"Whether to use the PolicyLearner.evaluate function instead of", "eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp): \"\"\"Eval function.\"\"\" base_env = env", "\"Agent type to use.\" ) flags.DEFINE_bool( \"eval_with_learner\", True, \"Whether to", "= make_eval_fn_with_agent( agent_type, planner_hparams, model_dir, log_every_steps=log_every_steps, video_writer=video_writer ) eval_metrics =", "batch_size, env.observation_space, env.action_space, policy_hparams, policy_dir, sampling_temp ), \"planner\": lambda: rl_utils.PlannerAgent(", "coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # Licensed", "__future__ import division from __future__ import print_function import datetime import", "flags.DEFINE_string(\"planner_hparams\", \"\", \"Planner hparam overrides.\") flags.DEFINE_integer( \"log_every_steps\", 20, \"Log every", "\"world_model\") eval_metrics_dir = os.path.join(cur_dir, \"evaluator_\" + now_tag) tf.logging.info(\"Writing metrics to", "base_env, loop_hparams, batch_size=planner_hparams.batch_size, model_dir=model_dir ) agent = make_agent( agent_type, env,", "overrides.\") flags.DEFINE_integer( \"log_every_steps\", 20, \"Log every how many environment steps.\"", "limitations under the License. r\"\"\"Evaluation script for RL agents. Example", "), \"simulated\": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames( # pylint: disable=g-long-lambda **sim_env_kwargs ), }[env_type]()", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "report_metric is not None eval_metrics_writer = tf.summary.FileWriter(eval_metrics_dir) video_writer = None", "sampling_temp, sim_env_kwargs=None, frame_stack_size=None, planning_horizon=None, rollout_agent_type=None, batch_size=None, num_rollouts=None, inner_batch_size=None, video_writer=None, env_type=None):", "+ 1) tf.logging.info(\"Set game to %s.\" % loop_hparams.game) if FLAGS.full_eval:", "from __future__ import print_function import datetime import os from tensor2tensor.data_generators", "disable=unused-import from tensor2tensor.rl import rl_utils from tensor2tensor.rl import trainer_model_based_params #", "workers to games.\") flags.DEFINE_string(\"policy_dir\", \"\", \"Directory with policy checkpoints.\") flags.DEFINE_string(\"model_dir\",", "report_fn(eval_metrics[metric_name], 0) else: report_fn(eval_metrics[report_metric], 0) return eval_metrics def get_game_for_worker(map_name, directory_id):", "%s.\" % (game_id, games)) return games[game_id] def main(_): now =", "eval_metrics_dir = os.path.join(cur_dir, \"evaluator_\" + now_tag) tf.logging.info(\"Writing metrics to %s.\"", "flags needed to pass for multi-run infrastructure. flags.DEFINE_bool(\"autotune\", False, \"Unused", "video_writer = None kwargs = {} if not eval_with_learner: if", "\"\", \"Path to save the planner debug video at.\" )", "ValueError(\"Unknown worker to game map name: %s\" % map_name) games.sort()", "absolute_import from __future__ import division from __future__ import print_function import", "cur_dir = os.path.join(cur_dir, \"%d\" % (FLAGS.worker_id + 1)) policy_dir =", "metric_name = rl_utils.get_metric_name( sampling_temp=loop_hparams.eval_sampling_temps[0], max_num_noops=loop_hparams.eval_max_num_noops, clipped=False ) report_fn(eval_metrics[metric_name], 0) else:", "= env env = rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size) sim_env_kwargs = rl.make_simulated_env_kwargs( base_env,", "not None eval_metrics_writer = tf.summary.FileWriter(eval_metrics_dir) video_writer = None kwargs =", "import rl # pylint: disable=unused-import from tensor2tensor.rl import rl_utils from", "RL agents. Example invocation: python -m tensor2tensor.rl.evaluator \\ --policy_dir=$HOME/t2t/rl_v1/policy \\", "\"log_every_steps\", 20, \"Log every how many environment steps.\" ) flags.DEFINE_string(", "rl_utils from tensor2tensor.rl import trainer_model_based_params # pylint: disable=unused-import from tensor2tensor.utils", "for multi-run infrastructure. flags.DEFINE_bool(\"autotune\", False, \"Unused here.\") flags.DEFINE_string(\"objective\", \"\", \"Unused", "\"License\"); # you may not use this file except in", "loop_hparams.frame_stack_size, planner_hparams.planning_horizon, planner_hparams.rollout_agent_type, num_rollouts=planner_hparams.num_rollouts, inner_batch_size=planner_hparams.batch_size, video_writer=video_writer, env_type=planner_hparams.env_type ) rl_utils.run_rollouts( env,", "games = [\"chopper_command\", \"boxing\", \"asterix\", \"seaquest\"] worker_per_game = 5 elif", "flags.DEFINE_integer(\"vizier_search_algorithm\", 0, \"Unused.\") @registry.register_hparams def planner_tiny(): return tf.contrib.training.HParams( num_rollouts=1, planning_horizon=2,", "model_dir, eval_metrics_dir, agent_type, eval_with_learner, log_every_steps, debug_video_path, report_fn=None, report_metric=None ): \"\"\"Evaluate.\"\"\"", ") if FLAGS.worker_to_game_map and FLAGS.total_num_workers > 1: loop_hparams.game = get_game_for_worker(", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "\"\", \"How to map workers to games.\") flags.DEFINE_string(\"policy_dir\", \"\", \"Directory", "pylint: disable=g-long-lambda **sim_env_kwargs ), }[env_type]() def make_agent( agent_type, env, policy_hparams,", "\"Directory with policy checkpoints.\") flags.DEFINE_string(\"model_dir\", \"\", \"Directory with model checkpoints.\")", "sim_env_kwargs): \"\"\"Factory function for envs.\"\"\" return { \"real\": lambda: real_env.new_like(", "if video_writer is not None: video_writer.finish_to_disk() # Report metrics if", "video_writer is not None: video_writer.finish_to_disk() # Report metrics if report_fn:", "# distributed under the License is distributed on an \"AS", "ignore the timestep limit.\") flags.DEFINE_enum( \"agent\", \"policy\", [\"random\", \"policy\", \"planner\"],", "== \"v100unfriendly\": games = [\"chopper_command\", \"boxing\", \"asterix\", \"seaquest\"] worker_per_game =", "\"Log every how many environment steps.\" ) flags.DEFINE_string( \"debug_video_path\", \"\",", "FLAGS.policy_dir model_dir = FLAGS.model_dir eval_metrics_dir = FLAGS.eval_metrics_dir if FLAGS.output_dir: cur_dir", "# Unless required by applicable law or agreed to in", "\\ --hparams_set=rlmb_base \\ --hparams='batch_size=64' \"\"\" from __future__ import absolute_import from", "FLAGS.output_dir if FLAGS.total_num_workers > 1: cur_dir = os.path.join(cur_dir, \"%d\" %", "now_tag) tf.logging.info(\"Writing metrics to %s.\" % eval_metrics_dir) if not tf.gfile.Exists(eval_metrics_dir):", "disable=g-long-lambda batch_size, env.observation_space, env.action_space ), \"policy\": lambda: rl_utils.PolicyAgent( # pylint:", "% loop_hparams.game) if FLAGS.full_eval: loop_hparams.eval_rl_env_max_episode_steps = -1 planner_hparams = trainer_lib.create_hparams(", "is not None: video_writer.finish_to_disk() # Report metrics if report_fn: if", "inner_batch_size=planner_hparams.batch_size, video_writer=video_writer, env_type=planner_hparams.env_type ) rl_utils.run_rollouts( env, agent, env.reset(), log_every_steps=log_every_steps )", "governing permissions and # limitations under the License. r\"\"\"Evaluation script", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "= rl_utils.get_metric_name( sampling_temp=loop_hparams.eval_sampling_temps[0], max_num_noops=loop_hparams.eval_max_num_noops, clipped=False ) report_fn(eval_metrics[metric_name], 0) else: report_fn(eval_metrics[report_metric],", "num_rollouts=None, inner_batch_size=None, video_writer=None, env_type=None): \"\"\"Factory function for Agents.\"\"\" if batch_size", "video_writer.finish_to_disk() # Report metrics if report_fn: if report_metric == \"mean_reward\":", "worker (directory) id.\"\"\" if map_name == \"v100unfriendly\": games = [\"chopper_command\",", "env_type=\"simulated\", ) @registry.register_hparams def planner_small(): return tf.contrib.training.HParams( num_rollouts=64, planning_horizon=16, rollout_agent_type=\"policy\",", "You may obtain a copy of the License at #", "for envs.\"\"\" return { \"real\": lambda: real_env.new_like( # pylint: disable=g-long-lambda", "\"\", \"Directory to output the eval metrics at.\" ) flags.DEFINE_bool(\"full_eval\",", "num_rollouts=1, planning_horizon=2, rollout_agent_type=\"random\", batch_size=1, env_type=\"simulated\", ) @registry.register_hparams def planner_small(): return", "= datetime.datetime.now() now_tag = now.strftime(\"%Y_%m_%d_%H_%M\") loop_hparams = trainer_lib.create_hparams( FLAGS.loop_hparams_set, FLAGS.loop_hparams", "game map name: %s\" % map_name) games.sort() game_id = (directory_id", "video at.\" ) # Unused flags needed to pass for", "function.\"\"\" base_env = env env = rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size) sim_env_kwargs =", "FLAGS.eval_metrics_dir if FLAGS.output_dir: cur_dir = FLAGS.output_dir if FLAGS.total_num_workers > 1:", "os.path.join(cur_dir, \"evaluator_\" + now_tag) tf.logging.info(\"Writing metrics to %s.\" % eval_metrics_dir)", "\"\", \"Unused here.\") flags.DEFINE_string(\"client_handle\", \"client_0\", \"Unused.\") flags.DEFINE_bool(\"maximize_tuner_objective\", True, \"Unused.\") flags.DEFINE_integer(\"vizier_search_algorithm\",", "the Apache License, Version 2.0 (the \"License\"); # you may", ") flags.DEFINE_string( \"planner_hparams_set\", \"planner_small\", \"Planner hparam set.\" ) flags.DEFINE_string(\"planner_hparams\", \"\",", "flags.DEFINE_enum( \"agent\", \"policy\", [\"random\", \"policy\", \"planner\"], \"Agent type to use.\"", "game to %s.\" % loop_hparams.game) if FLAGS.full_eval: loop_hparams.eval_rl_env_max_episode_steps = -1", "set.\" ) flags.DEFINE_string(\"planner_hparams\", \"\", \"Planner hparam overrides.\") flags.DEFINE_integer( \"log_every_steps\", 20,", "log_every_steps=None, video_writer=None ): \"\"\"Returns an out-of-graph eval_fn using the Agent", "1) // worker_per_game tf.logging.info(\"Getting game %d from %s.\" % (game_id,", "FLAGS.total_num_workers > 1: loop_hparams.game = get_game_for_worker( FLAGS.worker_to_game_map, FLAGS.worker_id + 1)", "raise ValueError(\"Unknown worker to game map name: %s\" % map_name)", "\"\", \"Main directory for multi-runs.\") flags.DEFINE_integer(\"total_num_workers\", 1, \"How many workers" ]
[ "from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities", "DesiredCapabilities class TestTest1(): def setup_method(self, method): self.driver = webdriver.Chrome() self.vars", "import json from selenium import webdriver from selenium.webdriver.common.by import By", "selenium.webdriver.common.desired_capabilities import DesiredCapabilities class TestTest1(): def setup_method(self, method): self.driver =", "selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import", "import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait", "ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from", "Selenium IDE import pytest import time import json from selenium", "from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support", "selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import", "Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class TestTest1(): def setup_method(self, method):", "import DesiredCapabilities class TestTest1(): def setup_method(self, method): self.driver = webdriver.Chrome()", "def test_test1(self): self.driver.get(\"https://www.wikipedia.org/\") self.driver.set_window_size(1920, 1040) self.driver.find_element(By.ID, \"searchInput\").click() self.driver.find_element(By.ID, \"searchInput\").send_keys(\"Romania\") self.driver.find_element(By.ID,", "by Selenium IDE import pytest import time import json from", "time import json from selenium import webdriver from selenium.webdriver.common.by import", "method): self.driver.quit() def test_test1(self): self.driver.get(\"https://www.wikipedia.org/\") self.driver.set_window_size(1920, 1040) self.driver.find_element(By.ID, \"searchInput\").click() self.driver.find_element(By.ID,", "pytest import time import json from selenium import webdriver from", "from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys", "setup_method(self, method): self.driver = webdriver.Chrome() self.vars = {} def teardown_method(self,", "self.driver.find_element(By.ID, \"searchInput\").send_keys(Keys.ENTER) self.driver.find_element(By.CSS_SELECTOR, \".tocsection-21 .toctext\").click() self.driver.execute_script(\"window.scrollTo(0,10634)\") self.driver.find_element(By.CSS_SELECTOR, \".thumb:nth-child(30) .thumbimage\").click() self.driver.execute_script(\"window.scrollTo(0,0)\")", "{} def teardown_method(self, method): self.driver.quit() def test_test1(self): self.driver.get(\"https://www.wikipedia.org/\") self.driver.set_window_size(1920, 1040)", "webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from", "self.vars = {} def teardown_method(self, method): self.driver.quit() def test_test1(self): self.driver.get(\"https://www.wikipedia.org/\")", "class TestTest1(): def setup_method(self, method): self.driver = webdriver.Chrome() self.vars =", "def teardown_method(self, method): self.driver.quit() def test_test1(self): self.driver.get(\"https://www.wikipedia.org/\") self.driver.set_window_size(1920, 1040) self.driver.find_element(By.ID,", "method): self.driver = webdriver.Chrome() self.vars = {} def teardown_method(self, method):", "self.driver.set_window_size(1920, 1040) self.driver.find_element(By.ID, \"searchInput\").click() self.driver.find_element(By.ID, \"searchInput\").send_keys(\"Romania\") self.driver.find_element(By.ID, \"searchInput\").send_keys(Keys.ENTER) self.driver.find_element(By.CSS_SELECTOR, \".tocsection-21", "IDE import pytest import time import json from selenium import", "= webdriver.Chrome() self.vars = {} def teardown_method(self, method): self.driver.quit() def", "selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import", "from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait", "self.driver = webdriver.Chrome() self.vars = {} def teardown_method(self, method): self.driver.quit()", "TestTest1(): def setup_method(self, method): self.driver = webdriver.Chrome() self.vars = {}", "# Generated by Selenium IDE import pytest import time import", "\"searchInput\").send_keys(\"Romania\") self.driver.find_element(By.ID, \"searchInput\").send_keys(Keys.ENTER) self.driver.find_element(By.CSS_SELECTOR, \".tocsection-21 .toctext\").click() self.driver.execute_script(\"window.scrollTo(0,10634)\") self.driver.find_element(By.CSS_SELECTOR, \".thumb:nth-child(30) .thumbimage\").click()", "Generated by Selenium IDE import pytest import time import json", "from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class TestTest1(): def setup_method(self, method): self.driver", "selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class TestTest1(): def", "= {} def teardown_method(self, method): self.driver.quit() def test_test1(self): self.driver.get(\"https://www.wikipedia.org/\") self.driver.set_window_size(1920,", "<reponame>AndreiHustiuc/IT_Factory_Course # Generated by Selenium IDE import pytest import time", "webdriver.Chrome() self.vars = {} def teardown_method(self, method): self.driver.quit() def test_test1(self):", "self.driver.get(\"https://www.wikipedia.org/\") self.driver.set_window_size(1920, 1040) self.driver.find_element(By.ID, \"searchInput\").click() self.driver.find_element(By.ID, \"searchInput\").send_keys(\"Romania\") self.driver.find_element(By.ID, \"searchInput\").send_keys(Keys.ENTER) self.driver.find_element(By.CSS_SELECTOR,", "import time import json from selenium import webdriver from selenium.webdriver.common.by", "import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions", "1040) self.driver.find_element(By.ID, \"searchInput\").click() self.driver.find_element(By.ID, \"searchInput\").send_keys(\"Romania\") self.driver.find_element(By.ID, \"searchInput\").send_keys(Keys.ENTER) self.driver.find_element(By.CSS_SELECTOR, \".tocsection-21 .toctext\").click()", "test_test1(self): self.driver.get(\"https://www.wikipedia.org/\") self.driver.set_window_size(1920, 1040) self.driver.find_element(By.ID, \"searchInput\").click() self.driver.find_element(By.ID, \"searchInput\").send_keys(\"Romania\") self.driver.find_element(By.ID, \"searchInput\").send_keys(Keys.ENTER)", "import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys", "self.driver.find_element(By.ID, \"searchInput\").send_keys(\"Romania\") self.driver.find_element(By.ID, \"searchInput\").send_keys(Keys.ENTER) self.driver.find_element(By.CSS_SELECTOR, \".tocsection-21 .toctext\").click() self.driver.execute_script(\"window.scrollTo(0,10634)\") self.driver.find_element(By.CSS_SELECTOR, \".thumb:nth-child(30)", "selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import", "teardown_method(self, method): self.driver.quit() def test_test1(self): self.driver.get(\"https://www.wikipedia.org/\") self.driver.set_window_size(1920, 1040) self.driver.find_element(By.ID, \"searchInput\").click()", "import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities", "self.driver.find_element(By.ID, \"searchInput\").click() self.driver.find_element(By.ID, \"searchInput\").send_keys(\"Romania\") self.driver.find_element(By.ID, \"searchInput\").send_keys(Keys.ENTER) self.driver.find_element(By.CSS_SELECTOR, \".tocsection-21 .toctext\").click() self.driver.execute_script(\"window.scrollTo(0,10634)\")", "json from selenium import webdriver from selenium.webdriver.common.by import By from", "from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains", "\"searchInput\").click() self.driver.find_element(By.ID, \"searchInput\").send_keys(\"Romania\") self.driver.find_element(By.ID, \"searchInput\").send_keys(Keys.ENTER) self.driver.find_element(By.CSS_SELECTOR, \".tocsection-21 .toctext\").click() self.driver.execute_script(\"window.scrollTo(0,10634)\") self.driver.find_element(By.CSS_SELECTOR,", "self.driver.quit() def test_test1(self): self.driver.get(\"https://www.wikipedia.org/\") self.driver.set_window_size(1920, 1040) self.driver.find_element(By.ID, \"searchInput\").click() self.driver.find_element(By.ID, \"searchInput\").send_keys(\"Romania\")", "selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import", "By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from", "WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class", "from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class TestTest1():", "def setup_method(self, method): self.driver = webdriver.Chrome() self.vars = {} def", "expected_conditions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys from", "import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains", "import pytest import time import json from selenium import webdriver", "import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class TestTest1(): def setup_method(self," ]
[ "class ComponentInterfaceAdmin(admin.ModelAdmin): list_display = ( \"pk\", \"title\", \"slug\", \"kind\", \"default_value\",", "admin from grandchallenge.components.models import ( ComponentInterface, ComponentInterfaceValue, ) class ComponentInterfaceAdmin(admin.ModelAdmin):", "\"slug\", \"kind\", \"default_value\", \"relative_path\", ) readonly_fields = ( \"default_value\", \"relative_path\",", "= (\"pk\", \"interface\", \"value\", \"file\", \"image\") readonly_fields = (\"interface\", \"value\",", "= ( \"default_value\", \"relative_path\", ) class ComponentInterfaceValueAdmin(admin.ModelAdmin): list_display = (\"pk\",", "\"interface\", \"value\", \"file\", \"image\") readonly_fields = (\"interface\", \"value\", \"file\", \"image\")", "readonly_fields = (\"interface\", \"value\", \"file\", \"image\") admin.site.register(ComponentInterface, ComponentInterfaceAdmin) admin.site.register(ComponentInterfaceValue, ComponentInterfaceValueAdmin)", "ComponentInterface, ComponentInterfaceValue, ) class ComponentInterfaceAdmin(admin.ModelAdmin): list_display = ( \"pk\", \"title\",", "list_display = (\"pk\", \"interface\", \"value\", \"file\", \"image\") readonly_fields = (\"interface\",", "\"default_value\", \"relative_path\", ) class ComponentInterfaceValueAdmin(admin.ModelAdmin): list_display = (\"pk\", \"interface\", \"value\",", ") class ComponentInterfaceAdmin(admin.ModelAdmin): list_display = ( \"pk\", \"title\", \"slug\", \"kind\",", "\"relative_path\", ) class ComponentInterfaceValueAdmin(admin.ModelAdmin): list_display = (\"pk\", \"interface\", \"value\", \"file\",", "\"pk\", \"title\", \"slug\", \"kind\", \"default_value\", \"relative_path\", ) readonly_fields = (", "ComponentInterfaceAdmin(admin.ModelAdmin): list_display = ( \"pk\", \"title\", \"slug\", \"kind\", \"default_value\", \"relative_path\",", "( \"pk\", \"title\", \"slug\", \"kind\", \"default_value\", \"relative_path\", ) readonly_fields =", "\"default_value\", \"relative_path\", ) readonly_fields = ( \"default_value\", \"relative_path\", ) class", "\"title\", \"slug\", \"kind\", \"default_value\", \"relative_path\", ) readonly_fields = ( \"default_value\",", ") readonly_fields = ( \"default_value\", \"relative_path\", ) class ComponentInterfaceValueAdmin(admin.ModelAdmin): list_display", "ComponentInterfaceValue, ) class ComponentInterfaceAdmin(admin.ModelAdmin): list_display = ( \"pk\", \"title\", \"slug\",", "django.contrib import admin from grandchallenge.components.models import ( ComponentInterface, ComponentInterfaceValue, )", "\"file\", \"image\") readonly_fields = (\"interface\", \"value\", \"file\", \"image\") admin.site.register(ComponentInterface, ComponentInterfaceAdmin)", "( ComponentInterface, ComponentInterfaceValue, ) class ComponentInterfaceAdmin(admin.ModelAdmin): list_display = ( \"pk\",", "grandchallenge.components.models import ( ComponentInterface, ComponentInterfaceValue, ) class ComponentInterfaceAdmin(admin.ModelAdmin): list_display =", "list_display = ( \"pk\", \"title\", \"slug\", \"kind\", \"default_value\", \"relative_path\", )", "= ( \"pk\", \"title\", \"slug\", \"kind\", \"default_value\", \"relative_path\", ) readonly_fields", "ComponentInterfaceValueAdmin(admin.ModelAdmin): list_display = (\"pk\", \"interface\", \"value\", \"file\", \"image\") readonly_fields =", "from django.contrib import admin from grandchallenge.components.models import ( ComponentInterface, ComponentInterfaceValue,", "\"image\") readonly_fields = (\"interface\", \"value\", \"file\", \"image\") admin.site.register(ComponentInterface, ComponentInterfaceAdmin) admin.site.register(ComponentInterfaceValue,", "(\"pk\", \"interface\", \"value\", \"file\", \"image\") readonly_fields = (\"interface\", \"value\", \"file\",", "import admin from grandchallenge.components.models import ( ComponentInterface, ComponentInterfaceValue, ) class", "\"relative_path\", ) readonly_fields = ( \"default_value\", \"relative_path\", ) class ComponentInterfaceValueAdmin(admin.ModelAdmin):", "\"value\", \"file\", \"image\") readonly_fields = (\"interface\", \"value\", \"file\", \"image\") admin.site.register(ComponentInterface,", ") class ComponentInterfaceValueAdmin(admin.ModelAdmin): list_display = (\"pk\", \"interface\", \"value\", \"file\", \"image\")", "( \"default_value\", \"relative_path\", ) class ComponentInterfaceValueAdmin(admin.ModelAdmin): list_display = (\"pk\", \"interface\",", "class ComponentInterfaceValueAdmin(admin.ModelAdmin): list_display = (\"pk\", \"interface\", \"value\", \"file\", \"image\") readonly_fields", "from grandchallenge.components.models import ( ComponentInterface, ComponentInterfaceValue, ) class ComponentInterfaceAdmin(admin.ModelAdmin): list_display", "\"kind\", \"default_value\", \"relative_path\", ) readonly_fields = ( \"default_value\", \"relative_path\", )", "import ( ComponentInterface, ComponentInterfaceValue, ) class ComponentInterfaceAdmin(admin.ModelAdmin): list_display = (", "readonly_fields = ( \"default_value\", \"relative_path\", ) class ComponentInterfaceValueAdmin(admin.ModelAdmin): list_display =" ]
[ "-*- \"\"\" Created on Mon Mar 28 15:28:24 2016 @author:", "# -*- coding: utf-8 -*- \"\"\" Created on Mon Mar", "-*- coding: utf-8 -*- \"\"\" Created on Mon Mar 28", "utf-8 -*- \"\"\" Created on Mon Mar 28 15:28:24 2016", "15:28:24 2016 @author: <NAME>, <EMAIL> \"\"\" from .helpers import setup_env", "Mar 28 15:28:24 2016 @author: <NAME>, <EMAIL> \"\"\" from .helpers", "@author: <NAME>, <EMAIL> \"\"\" from .helpers import setup_env done =", "<NAME>, <EMAIL> \"\"\" from .helpers import setup_env done = setup_env()", "coding: utf-8 -*- \"\"\" Created on Mon Mar 28 15:28:24", "Created on Mon Mar 28 15:28:24 2016 @author: <NAME>, <EMAIL>", "28 15:28:24 2016 @author: <NAME>, <EMAIL> \"\"\" from .helpers import", "on Mon Mar 28 15:28:24 2016 @author: <NAME>, <EMAIL> \"\"\"", "Mon Mar 28 15:28:24 2016 @author: <NAME>, <EMAIL> \"\"\" from", "2016 @author: <NAME>, <EMAIL> \"\"\" from .helpers import setup_env done", "\"\"\" Created on Mon Mar 28 15:28:24 2016 @author: <NAME>," ]
[ "devices.\"\"\" from . import MDNSDiscoverable class Discoverable(MDNSDiscoverable): \"\"\"Add support for", "from . import MDNSDiscoverable class Discoverable(MDNSDiscoverable): \"\"\"Add support for discovering", "MDNSDiscoverable class Discoverable(MDNSDiscoverable): \"\"\"Add support for discovering Nanoleaf Aurora devices.\"\"\"", "\"\"\"Discover Nanoleaf Aurora devices.\"\"\" from . import MDNSDiscoverable class Discoverable(MDNSDiscoverable):", "\"\"\"Add support for discovering Nanoleaf Aurora devices.\"\"\" def __init__(self, nd):", "<reponame>jjlawren/netdisco<filename>netdisco/discoverables/nanoleaf_aurora.py \"\"\"Discover Nanoleaf Aurora devices.\"\"\" from . import MDNSDiscoverable class", "for discovering Nanoleaf Aurora devices.\"\"\" def __init__(self, nd): super(Discoverable, self).__init__(nd,", ". import MDNSDiscoverable class Discoverable(MDNSDiscoverable): \"\"\"Add support for discovering Nanoleaf", "discovering Nanoleaf Aurora devices.\"\"\" def __init__(self, nd): super(Discoverable, self).__init__(nd, '_nanoleafapi._tcp.local.')", "class Discoverable(MDNSDiscoverable): \"\"\"Add support for discovering Nanoleaf Aurora devices.\"\"\" def", "Discoverable(MDNSDiscoverable): \"\"\"Add support for discovering Nanoleaf Aurora devices.\"\"\" def __init__(self,", "Nanoleaf Aurora devices.\"\"\" from . import MDNSDiscoverable class Discoverable(MDNSDiscoverable): \"\"\"Add", "import MDNSDiscoverable class Discoverable(MDNSDiscoverable): \"\"\"Add support for discovering Nanoleaf Aurora", "support for discovering Nanoleaf Aurora devices.\"\"\" def __init__(self, nd): super(Discoverable,", "Aurora devices.\"\"\" from . import MDNSDiscoverable class Discoverable(MDNSDiscoverable): \"\"\"Add support" ]
[ "for sub in range(n_sub): for fb in range(n_fb): covs_proj[sub, fb]", "sklearn.pipeline import make_pipeline from sklearn.linear_model import RidgeCV from sklearn.preprocessing import", "TangentSpace(metric=\"wasserstein\").fit( covs[:, fb, :, :]).transform(covs[:, fb, :, :]) return covs_ts", ":]) return covs_ts file_covs = op.join(cfg.path_outputs, 'covs_allch_oas.float32.h5') covs_allch = mne.externals.h5io.read_hdf5(file_covs)", "covs_ts file_covs = op.join(cfg.path_outputs, 'covs_allch_oas.float32.h5') covs_allch = mne.externals.h5io.read_hdf5(file_covs) # (sub,", "= [d['subject'] for d in covs_allch if 'subject' in d]", "n_ch, n_ch = covs.shape # covs2 = covs.reshape(n_sub*n_fb, n_ch, n_ch)", "in d] y = info.set_index('Observations').age.loc[subjects] ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 5,", "np import pandas as pd from sklearn.pipeline import make_pipeline from", "= d[::-1] V = V[:, ::-1] proj_mat = V[:, :rank].T", "sklearn.preprocessing import StandardScaler from sklearn.model_selection import KFold, cross_val_score import mne", "axis=0) covs_avg = covs.mean(axis=1).mean(axis=0) d, V = np.linalg.eigh(covs_avg) d =", "= np.zeros((n_sub, n_fb, (p*(p+1))//2)) for fb in range(n_fb): covs_ts[:, fb,", "= 42 n_jobs = 10 cv = KFold(n_splits=n_jobs, shuffle=True, random_state=seed)", "# covs_avg = np.mean(covs2, axis=0) covs_avg = covs.mean(axis=1).mean(axis=0) d, V", "n_sub, n_fb, n_ch, n_ch = covs.shape # covs2 = covs.reshape(n_sub*n_fb,", "(p*(p+1))//2)) for fb in range(n_fb): covs_ts[:, fb, :] = TangentSpace(metric=\"wasserstein\").fit(", "covs_ts[:, fb, :] = TangentSpace(metric=\"wasserstein\").fit( covs[:, fb, :, :]).transform(covs[:, fb,", "proj_covs_ts(covs) X = X.reshape(len(X), -1) info = pd.read_csv(op.join(cfg.path_data, 'participants.csv')) subjects", "ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 5, 100))) score = - cross_val_score(ridge,", "d in covs if 'subject' in d] covs = scale", "def proj_covs_common(covs, picks, scale=scale, rank=rank, reg=reg): covs = [d['covs'][:, picks][:,", "= 65 reg = 1e-6 seed = 42 n_jobs =", "import RidgeCV from sklearn.preprocessing import StandardScaler from sklearn.model_selection import KFold,", "= covs.shape # covs2 = covs.reshape(n_sub*n_fb, n_ch, n_ch) # covs_avg", "KFold(n_splits=n_jobs, shuffle=True, random_state=seed) def proj_covs_common(covs, picks, scale=scale, rank=rank, reg=reg): covs", "= proj_mat @ covs[sub, fb] @ proj_mat.T covs_proj[sub, fb] +=", "np.zeros((n_sub, n_fb, (p*(p+1))//2)) for fb in range(n_fb): covs_ts[:, fb, :]", "= scale * np.array(covs) n_sub, n_fb, n_ch, n_ch = covs.shape", "n_ch = covs.shape # covs2 = covs.reshape(n_sub*n_fb, n_ch, n_ch) #", "'info_allch.npy')).item() picks = mne.pick_types(info, meg=meg) covs = proj_covs_common(covs_allch, picks, scale=scale,", "* np.array(covs) n_sub, n_fb, n_ch, n_ch = covs.shape # covs2", "X = proj_covs_ts(covs) X = X.reshape(len(X), -1) info = pd.read_csv(op.join(cfg.path_data,", "np.linalg.eigh(covs_avg) d = d[::-1] V = V[:, ::-1] proj_mat =", "= make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 5, 100))) score = - cross_val_score(ridge, X,", "covs[:, fb, :, :]).transform(covs[:, fb, :, :]) return covs_ts file_covs", "covs = proj_covs_common(covs_allch, picks, scale=scale, rank=rank, reg=reg) X = proj_covs_ts(covs)", "scale=scale, rank=rank, reg=reg) X = proj_covs_ts(covs) X = X.reshape(len(X), -1)", "import KFold, cross_val_score import mne from pyriemann.tangentspace import TangentSpace import", "proj_mat = V[:, :rank].T covs_proj = np.zeros((n_sub, n_fb, rank, rank))", "= V[:, :rank].T covs_proj = np.zeros((n_sub, n_fb, rank, rank)) for", "= TangentSpace(metric=\"wasserstein\").fit( covs[:, fb, :, :]).transform(covs[:, fb, :, :]) return", "picks] for d in covs if 'subject' in d] covs", "'subject' in d] covs = scale * np.array(covs) n_sub, n_fb,", "rank = 65 reg = 1e-6 seed = 42 n_jobs", "rank)) for sub in range(n_sub): for fb in range(n_fb): covs_proj[sub,", "file_covs = op.join(cfg.path_outputs, 'covs_allch_oas.float32.h5') covs_allch = mne.externals.h5io.read_hdf5(file_covs) # (sub, fb,", "as pd from sklearn.pipeline import make_pipeline from sklearn.linear_model import RidgeCV", "X.reshape(len(X), -1) info = pd.read_csv(op.join(cfg.path_data, 'participants.csv')) subjects = [d['subject'] for", "np.array(covs) n_sub, n_fb, n_ch, n_ch = covs.shape # covs2 =", "picks = mne.pick_types(info, meg=meg) covs = proj_covs_common(covs_allch, picks, scale=scale, rank=rank,", "fb, :, :]) return covs_ts file_covs = op.join(cfg.path_outputs, 'covs_allch_oas.float32.h5') covs_allch", "1e22 rank = 65 reg = 1e-6 seed = 42", "covs_proj[sub, fb] += reg * np.eye(rank) return covs_proj def proj_covs_ts(covs):", "seed = 42 n_jobs = 10 cv = KFold(n_splits=n_jobs, shuffle=True,", "d = d[::-1] V = V[:, ::-1] proj_mat = V[:,", "= mne.externals.h5io.read_hdf5(file_covs) # (sub, fb, ch, ch) info = np.load(op.join(cfg.path_data,", "-1) info = pd.read_csv(op.join(cfg.path_data, 'participants.csv')) subjects = [d['subject'] for d", "proj_mat.T covs_proj[sub, fb] += reg * np.eye(rank) return covs_proj def", "ch, ch) info = np.load(op.join(cfg.path_data, 'info_allch.npy')).item() picks = mne.pick_types(info, meg=meg)", "1e-6 seed = 42 n_jobs = 10 cv = KFold(n_splits=n_jobs,", "fb] += reg * np.eye(rank) return covs_proj def proj_covs_ts(covs): n_sub,", "= 1e22 rank = 65 reg = 1e-6 seed =", "covs = [d['covs'][:, picks][:, :, picks] for d in covs", "make_pipeline from sklearn.linear_model import RidgeCV from sklearn.preprocessing import StandardScaler from", "n_jobs = 10 cv = KFold(n_splits=n_jobs, shuffle=True, random_state=seed) def proj_covs_common(covs,", "as np import pandas as pd from sklearn.pipeline import make_pipeline", "in d] covs = scale * np.array(covs) n_sub, n_fb, n_ch,", "= KFold(n_splits=n_jobs, shuffle=True, random_state=seed) def proj_covs_common(covs, picks, scale=scale, rank=rank, reg=reg):", "= X.reshape(len(X), -1) info = pd.read_csv(op.join(cfg.path_data, 'participants.csv')) subjects = [d['subject']", "_ = covs.shape covs_ts = np.zeros((n_sub, n_fb, (p*(p+1))//2)) for fb", "= np.mean(covs2, axis=0) covs_avg = covs.mean(axis=1).mean(axis=0) d, V = np.linalg.eigh(covs_avg)", "np.eye(rank) return covs_proj def proj_covs_ts(covs): n_sub, n_fb, p, _ =", "covs_proj[sub, fb] = proj_mat @ covs[sub, fb] @ proj_mat.T covs_proj[sub,", "RidgeCV from sklearn.preprocessing import StandardScaler from sklearn.model_selection import KFold, cross_val_score", "sklearn.linear_model import RidgeCV from sklearn.preprocessing import StandardScaler from sklearn.model_selection import", "covs[sub, fb] @ proj_mat.T covs_proj[sub, fb] += reg * np.eye(rank)", "# covs2 = covs.reshape(n_sub*n_fb, n_ch, n_ch) # covs_avg = np.mean(covs2,", "for d in covs_allch if 'subject' in d] y =", "pd.read_csv(op.join(cfg.path_data, 'participants.csv')) subjects = [d['subject'] for d in covs_allch if", "range(n_sub): for fb in range(n_fb): covs_proj[sub, fb] = proj_mat @", "rank=rank, reg=reg): covs = [d['covs'][:, picks][:, :, picks] for d", "d] y = info.set_index('Observations').age.loc[subjects] ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 5, 100)))", "covs_proj def proj_covs_ts(covs): n_sub, n_fb, p, _ = covs.shape covs_ts", "@ covs[sub, fb] @ proj_mat.T covs_proj[sub, fb] += reg *", "for d in covs if 'subject' in d] covs =", "covs.reshape(n_sub*n_fb, n_ch, n_ch) # covs_avg = np.mean(covs2, axis=0) covs_avg =", "TangentSpace import config_drago as cfg meg = 'mag' scale =", "op.join(cfg.path_outputs, 'covs_allch_oas.float32.h5') covs_allch = mne.externals.h5io.read_hdf5(file_covs) # (sub, fb, ch, ch)", ":, picks] for d in covs if 'subject' in d]", "in covs if 'subject' in d] covs = scale *", "return covs_proj def proj_covs_ts(covs): n_sub, n_fb, p, _ = covs.shape", "import StandardScaler from sklearn.model_selection import KFold, cross_val_score import mne from", "proj_mat @ covs[sub, fb] @ proj_mat.T covs_proj[sub, fb] += reg", "n_sub, n_fb, p, _ = covs.shape covs_ts = np.zeros((n_sub, n_fb,", "ch) info = np.load(op.join(cfg.path_data, 'info_allch.npy')).item() picks = mne.pick_types(info, meg=meg) covs", "5, 100))) score = - cross_val_score(ridge, X, y, cv=cv, scoring=\"neg_mean_absolute_error\",", "mne from pyriemann.tangentspace import TangentSpace import config_drago as cfg meg", "covs if 'subject' in d] covs = scale * np.array(covs)", "d[::-1] V = V[:, ::-1] proj_mat = V[:, :rank].T covs_proj", "reg=reg) X = proj_covs_ts(covs) X = X.reshape(len(X), -1) info =", "= proj_covs_ts(covs) X = X.reshape(len(X), -1) info = pd.read_csv(op.join(cfg.path_data, 'participants.csv'))", "RidgeCV(alphas=np.logspace(-3, 5, 100))) score = - cross_val_score(ridge, X, y, cv=cv,", "os.path as op import numpy as np import pandas as", "import pandas as pd from sklearn.pipeline import make_pipeline from sklearn.linear_model", "config_drago as cfg meg = 'mag' scale = 1e22 rank", "range(n_fb): covs_proj[sub, fb] = proj_mat @ covs[sub, fb] @ proj_mat.T", ":, :]).transform(covs[:, fb, :, :]) return covs_ts file_covs = op.join(cfg.path_outputs,", ":, :]) return covs_ts file_covs = op.join(cfg.path_outputs, 'covs_allch_oas.float32.h5') covs_allch =", "covs_allch = mne.externals.h5io.read_hdf5(file_covs) # (sub, fb, ch, ch) info =", ":]).transform(covs[:, fb, :, :]) return covs_ts file_covs = op.join(cfg.path_outputs, 'covs_allch_oas.float32.h5')", "= np.load(op.join(cfg.path_data, 'info_allch.npy')).item() picks = mne.pick_types(info, meg=meg) covs = proj_covs_common(covs_allch,", "d, V = np.linalg.eigh(covs_avg) d = d[::-1] V = V[:,", "cv = KFold(n_splits=n_jobs, shuffle=True, random_state=seed) def proj_covs_common(covs, picks, scale=scale, rank=rank,", "n_ch, n_ch) # covs_avg = np.mean(covs2, axis=0) covs_avg = covs.mean(axis=1).mean(axis=0)", "StandardScaler from sklearn.model_selection import KFold, cross_val_score import mne from pyriemann.tangentspace", "[d['subject'] for d in covs_allch if 'subject' in d] y", "mne.externals.h5io.read_hdf5(file_covs) # (sub, fb, ch, ch) info = np.load(op.join(cfg.path_data, 'info_allch.npy')).item()", "np.zeros((n_sub, n_fb, rank, rank)) for sub in range(n_sub): for fb", "op import numpy as np import pandas as pd from", "in range(n_sub): for fb in range(n_fb): covs_proj[sub, fb] = proj_mat", "covs_avg = covs.mean(axis=1).mean(axis=0) d, V = np.linalg.eigh(covs_avg) d = d[::-1]", "subjects = [d['subject'] for d in covs_allch if 'subject' in", "from sklearn.linear_model import RidgeCV from sklearn.preprocessing import StandardScaler from sklearn.model_selection", "meg=meg) covs = proj_covs_common(covs_allch, picks, scale=scale, rank=rank, reg=reg) X =", "p, _ = covs.shape covs_ts = np.zeros((n_sub, n_fb, (p*(p+1))//2)) for", "[d['covs'][:, picks][:, :, picks] for d in covs if 'subject'", "proj_covs_common(covs_allch, picks, scale=scale, rank=rank, reg=reg) X = proj_covs_ts(covs) X =", "= np.linalg.eigh(covs_avg) d = d[::-1] V = V[:, ::-1] proj_mat", "10 cv = KFold(n_splits=n_jobs, shuffle=True, random_state=seed) def proj_covs_common(covs, picks, scale=scale,", "'covs_allch_oas.float32.h5') covs_allch = mne.externals.h5io.read_hdf5(file_covs) # (sub, fb, ch, ch) info", "= info.set_index('Observations').age.loc[subjects] ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 5, 100))) score =", "V = V[:, ::-1] proj_mat = V[:, :rank].T covs_proj =", "d] covs = scale * np.array(covs) n_sub, n_fb, n_ch, n_ch", "'participants.csv')) subjects = [d['subject'] for d in covs_allch if 'subject'", "reg * np.eye(rank) return covs_proj def proj_covs_ts(covs): n_sub, n_fb, p,", "info = pd.read_csv(op.join(cfg.path_data, 'participants.csv')) subjects = [d['subject'] for d in", "= [d['covs'][:, picks][:, :, picks] for d in covs if", "for fb in range(n_fb): covs_proj[sub, fb] = proj_mat @ covs[sub,", "reg = 1e-6 seed = 42 n_jobs = 10 cv", "scale=scale, rank=rank, reg=reg): covs = [d['covs'][:, picks][:, :, picks] for", "covs.shape # covs2 = covs.reshape(n_sub*n_fb, n_ch, n_ch) # covs_avg =", "fb in range(n_fb): covs_proj[sub, fb] = proj_mat @ covs[sub, fb]", "y = info.set_index('Observations').age.loc[subjects] ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 5, 100))) score", "cfg meg = 'mag' scale = 1e22 rank = 65", "in covs_allch if 'subject' in d] y = info.set_index('Observations').age.loc[subjects] ridge", "fb] @ proj_mat.T covs_proj[sub, fb] += reg * np.eye(rank) return", "fb, :, :]).transform(covs[:, fb, :, :]) return covs_ts file_covs =", "as op import numpy as np import pandas as pd", "covs_ts = np.zeros((n_sub, n_fb, (p*(p+1))//2)) for fb in range(n_fb): covs_ts[:,", "scale * np.array(covs) n_sub, n_fb, n_ch, n_ch = covs.shape #", "shuffle=True, random_state=seed) def proj_covs_common(covs, picks, scale=scale, rank=rank, reg=reg): covs =", "= pd.read_csv(op.join(cfg.path_data, 'participants.csv')) subjects = [d['subject'] for d in covs_allch", "n_ch) # covs_avg = np.mean(covs2, axis=0) covs_avg = covs.mean(axis=1).mean(axis=0) d,", "# (sub, fb, ch, ch) info = np.load(op.join(cfg.path_data, 'info_allch.npy')).item() picks", "= V[:, ::-1] proj_mat = V[:, :rank].T covs_proj = np.zeros((n_sub,", "covs_proj = np.zeros((n_sub, n_fb, rank, rank)) for sub in range(n_sub):", "picks, scale=scale, rank=rank, reg=reg) X = proj_covs_ts(covs) X = X.reshape(len(X),", "import mne from pyriemann.tangentspace import TangentSpace import config_drago as cfg", "'mag' scale = 1e22 rank = 65 reg = 1e-6", "(sub, fb, ch, ch) info = np.load(op.join(cfg.path_data, 'info_allch.npy')).item() picks =", "picks, scale=scale, rank=rank, reg=reg): covs = [d['covs'][:, picks][:, :, picks]", "mne.pick_types(info, meg=meg) covs = proj_covs_common(covs_allch, picks, scale=scale, rank=rank, reg=reg) X", "covs_avg = np.mean(covs2, axis=0) covs_avg = covs.mean(axis=1).mean(axis=0) d, V =", "if 'subject' in d] covs = scale * np.array(covs) n_sub,", "np.mean(covs2, axis=0) covs_avg = covs.mean(axis=1).mean(axis=0) d, V = np.linalg.eigh(covs_avg) d", "V = np.linalg.eigh(covs_avg) d = d[::-1] V = V[:, ::-1]", "pd from sklearn.pipeline import make_pipeline from sklearn.linear_model import RidgeCV from", "info.set_index('Observations').age.loc[subjects] ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 5, 100))) score = -", "numpy as np import pandas as pd from sklearn.pipeline import", "X = X.reshape(len(X), -1) info = pd.read_csv(op.join(cfg.path_data, 'participants.csv')) subjects =", "def proj_covs_ts(covs): n_sub, n_fb, p, _ = covs.shape covs_ts =", "fb, ch, ch) info = np.load(op.join(cfg.path_data, 'info_allch.npy')).item() picks = mne.pick_types(info,", "= 10 cv = KFold(n_splits=n_jobs, shuffle=True, random_state=seed) def proj_covs_common(covs, picks,", "n_fb, rank, rank)) for sub in range(n_sub): for fb in", "::-1] proj_mat = V[:, :rank].T covs_proj = np.zeros((n_sub, n_fb, rank,", ":rank].T covs_proj = np.zeros((n_sub, n_fb, rank, rank)) for sub in", "= proj_covs_common(covs_allch, picks, scale=scale, rank=rank, reg=reg) X = proj_covs_ts(covs) X", "import TangentSpace import config_drago as cfg meg = 'mag' scale", "covs.mean(axis=1).mean(axis=0) d, V = np.linalg.eigh(covs_avg) d = d[::-1] V =", "fb in range(n_fb): covs_ts[:, fb, :] = TangentSpace(metric=\"wasserstein\").fit( covs[:, fb,", "picks][:, :, picks] for d in covs if 'subject' in", "from sklearn.model_selection import KFold, cross_val_score import mne from pyriemann.tangentspace import", "score = - cross_val_score(ridge, X, y, cv=cv, scoring=\"neg_mean_absolute_error\", n_jobs=n_jobs, verbose=True)", "covs_allch if 'subject' in d] y = info.set_index('Observations').age.loc[subjects] ridge =", "fb] = proj_mat @ covs[sub, fb] @ proj_mat.T covs_proj[sub, fb]", "import os.path as op import numpy as np import pandas", "sklearn.model_selection import KFold, cross_val_score import mne from pyriemann.tangentspace import TangentSpace", "65 reg = 1e-6 seed = 42 n_jobs = 10", "42 n_jobs = 10 cv = KFold(n_splits=n_jobs, shuffle=True, random_state=seed) def", "V[:, ::-1] proj_mat = V[:, :rank].T covs_proj = np.zeros((n_sub, n_fb,", "= np.zeros((n_sub, n_fb, rank, rank)) for sub in range(n_sub): for", "d in covs_allch if 'subject' in d] y = info.set_index('Observations').age.loc[subjects]", "if 'subject' in d] y = info.set_index('Observations').age.loc[subjects] ridge = make_pipeline(StandardScaler(),", "'subject' in d] y = info.set_index('Observations').age.loc[subjects] ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3,", "= 1e-6 seed = 42 n_jobs = 10 cv =", "make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 5, 100))) score = - cross_val_score(ridge, X, y,", "return covs_ts file_covs = op.join(cfg.path_outputs, 'covs_allch_oas.float32.h5') covs_allch = mne.externals.h5io.read_hdf5(file_covs) #", "pyriemann.tangentspace import TangentSpace import config_drago as cfg meg = 'mag'", "+= reg * np.eye(rank) return covs_proj def proj_covs_ts(covs): n_sub, n_fb,", "covs = scale * np.array(covs) n_sub, n_fb, n_ch, n_ch =", "V[:, :rank].T covs_proj = np.zeros((n_sub, n_fb, rank, rank)) for sub", "sub in range(n_sub): for fb in range(n_fb): covs_proj[sub, fb] =", "fb, :] = TangentSpace(metric=\"wasserstein\").fit( covs[:, fb, :, :]).transform(covs[:, fb, :,", "pandas as pd from sklearn.pipeline import make_pipeline from sklearn.linear_model import", "from sklearn.pipeline import make_pipeline from sklearn.linear_model import RidgeCV from sklearn.preprocessing", "meg = 'mag' scale = 1e22 rank = 65 reg", "from sklearn.preprocessing import StandardScaler from sklearn.model_selection import KFold, cross_val_score import", "import config_drago as cfg meg = 'mag' scale = 1e22", "range(n_fb): covs_ts[:, fb, :] = TangentSpace(metric=\"wasserstein\").fit( covs[:, fb, :, :]).transform(covs[:,", "in range(n_fb): covs_proj[sub, fb] = proj_mat @ covs[sub, fb] @", "covs.shape covs_ts = np.zeros((n_sub, n_fb, (p*(p+1))//2)) for fb in range(n_fb):", "as cfg meg = 'mag' scale = 1e22 rank =", "= covs.mean(axis=1).mean(axis=0) d, V = np.linalg.eigh(covs_avg) d = d[::-1] V", "np.load(op.join(cfg.path_data, 'info_allch.npy')).item() picks = mne.pick_types(info, meg=meg) covs = proj_covs_common(covs_allch, picks,", "proj_covs_common(covs, picks, scale=scale, rank=rank, reg=reg): covs = [d['covs'][:, picks][:, :,", "100))) score = - cross_val_score(ridge, X, y, cv=cv, scoring=\"neg_mean_absolute_error\", n_jobs=n_jobs,", "n_fb, n_ch, n_ch = covs.shape # covs2 = covs.reshape(n_sub*n_fb, n_ch,", "= covs.reshape(n_sub*n_fb, n_ch, n_ch) # covs_avg = np.mean(covs2, axis=0) covs_avg", "n_fb, p, _ = covs.shape covs_ts = np.zeros((n_sub, n_fb, (p*(p+1))//2))", "rank=rank, reg=reg) X = proj_covs_ts(covs) X = X.reshape(len(X), -1) info", "import numpy as np import pandas as pd from sklearn.pipeline", "proj_covs_ts(covs): n_sub, n_fb, p, _ = covs.shape covs_ts = np.zeros((n_sub,", "= covs.shape covs_ts = np.zeros((n_sub, n_fb, (p*(p+1))//2)) for fb in", "for fb in range(n_fb): covs_ts[:, fb, :] = TangentSpace(metric=\"wasserstein\").fit( covs[:,", "reg=reg): covs = [d['covs'][:, picks][:, :, picks] for d in", "n_fb, (p*(p+1))//2)) for fb in range(n_fb): covs_ts[:, fb, :] =", ":] = TangentSpace(metric=\"wasserstein\").fit( covs[:, fb, :, :]).transform(covs[:, fb, :, :])", "= 'mag' scale = 1e22 rank = 65 reg =", "info = np.load(op.join(cfg.path_data, 'info_allch.npy')).item() picks = mne.pick_types(info, meg=meg) covs =", "= mne.pick_types(info, meg=meg) covs = proj_covs_common(covs_allch, picks, scale=scale, rank=rank, reg=reg)", "from pyriemann.tangentspace import TangentSpace import config_drago as cfg meg =", "import make_pipeline from sklearn.linear_model import RidgeCV from sklearn.preprocessing import StandardScaler", "KFold, cross_val_score import mne from pyriemann.tangentspace import TangentSpace import config_drago", "* np.eye(rank) return covs_proj def proj_covs_ts(covs): n_sub, n_fb, p, _", "random_state=seed) def proj_covs_common(covs, picks, scale=scale, rank=rank, reg=reg): covs = [d['covs'][:,", "cross_val_score import mne from pyriemann.tangentspace import TangentSpace import config_drago as", "covs2 = covs.reshape(n_sub*n_fb, n_ch, n_ch) # covs_avg = np.mean(covs2, axis=0)", "rank, rank)) for sub in range(n_sub): for fb in range(n_fb):", "@ proj_mat.T covs_proj[sub, fb] += reg * np.eye(rank) return covs_proj", "in range(n_fb): covs_ts[:, fb, :] = TangentSpace(metric=\"wasserstein\").fit( covs[:, fb, :,", "scale = 1e22 rank = 65 reg = 1e-6 seed", "= op.join(cfg.path_outputs, 'covs_allch_oas.float32.h5') covs_allch = mne.externals.h5io.read_hdf5(file_covs) # (sub, fb, ch," ]
[ "2017~ mengalong <<EMAIL>> # # Licensed under the Apache License,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "may obtain # a copy of the License at #", ":%s\" % str(parsed_url)) self.publish_driver = driver.DriverManager( 'bter.publisher', parsed_url.scheme, invoke_args=(self.conf,), invoke_on_load=True).driver", "# # Licensed under the Apache License, Version 2.0 (the", "agreed to in writing, software # distributed under the License", "# Copyright 2017~ mengalong <<EMAIL>> # # Licensed under the", "Unless required by applicable law or agreed to in writing,", "<filename>bter/publish.py # Copyright 2017~ mengalong <<EMAIL>> # # Licensed under", "distributed under the License is distributed on an \"AS IS\"", "parsed_url = urlparse.urlparse(url) logger.debug(\"The parsed url for publisher is :%s\"", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "stevedore import driver logger = daiquiri.getLogger(__name__) class PublisherManager(object): def __init__(self,", "obtain # a copy of the License at # #", "applicable law or agreed to in writing, software # distributed", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "= daiquiri.getLogger(__name__) class PublisherManager(object): def __init__(self, conf, url): self.conf =", "Version 2.0 (the \"License\"); you may # not use this", "specific language governing permissions and limitations # under the License.", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "def __init__(self, conf, url): self.conf = conf self.url = url", "Copyright 2017~ mengalong <<EMAIL>> # # Licensed under the Apache", "writing, software # distributed under the License is distributed on", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "under the License. import daiquiri from six.moves.urllib import parse as", "the License. You may obtain # a copy of the", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "You may obtain # a copy of the License at", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "daiquiri.getLogger(__name__) class PublisherManager(object): def __init__(self, conf, url): self.conf = conf", "# under the License. import daiquiri from six.moves.urllib import parse", "six.moves.urllib import parse as urlparse from stevedore import driver logger", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "= conf self.url = url parsed_url = urlparse.urlparse(url) logger.debug(\"The parsed", "class PublisherManager(object): def __init__(self, conf, url): self.conf = conf self.url", "either express or implied. See the # License for the", "under the License is distributed on an \"AS IS\" BASIS,", "url for publisher is :%s\" % str(parsed_url)) self.publish_driver = driver.DriverManager(", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "is :%s\" % str(parsed_url)) self.publish_driver = driver.DriverManager( 'bter.publisher', parsed_url.scheme, invoke_args=(self.conf,),", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "may # not use this file except in compliance with", "self.url = url parsed_url = urlparse.urlparse(url) logger.debug(\"The parsed url for", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "as urlparse from stevedore import driver logger = daiquiri.getLogger(__name__) class", "driver logger = daiquiri.getLogger(__name__) class PublisherManager(object): def __init__(self, conf, url):", "parse as urlparse from stevedore import driver logger = daiquiri.getLogger(__name__)", "you may # not use this file except in compliance", "\"License\"); you may # not use this file except in", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "publisher is :%s\" % str(parsed_url)) self.publish_driver = driver.DriverManager( 'bter.publisher', parsed_url.scheme,", "express or implied. See the # License for the specific", "this file except in compliance with the License. You may", "from six.moves.urllib import parse as urlparse from stevedore import driver", "compliance with the License. You may obtain # a copy", "conf, url): self.conf = conf self.url = url parsed_url =", "import driver logger = daiquiri.getLogger(__name__) class PublisherManager(object): def __init__(self, conf,", "the Apache License, Version 2.0 (the \"License\"); you may #", "the License. import daiquiri from six.moves.urllib import parse as urlparse", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "= urlparse.urlparse(url) logger.debug(\"The parsed url for publisher is :%s\" %", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "__init__(self, conf, url): self.conf = conf self.url = url parsed_url", "See the # License for the specific language governing permissions", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "the # License for the specific language governing permissions and", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "mengalong <<EMAIL>> # # Licensed under the Apache License, Version", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "file except in compliance with the License. You may obtain", "for the specific language governing permissions and limitations # under", "License. import daiquiri from six.moves.urllib import parse as urlparse from", "law or agreed to in writing, software # distributed under", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "limitations # under the License. import daiquiri from six.moves.urllib import", "daiquiri from six.moves.urllib import parse as urlparse from stevedore import", "under the Apache License, Version 2.0 (the \"License\"); you may", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "= url parsed_url = urlparse.urlparse(url) logger.debug(\"The parsed url for publisher", "implied. See the # License for the specific language governing", "permissions and limitations # under the License. import daiquiri from", "and limitations # under the License. import daiquiri from six.moves.urllib", "language governing permissions and limitations # under the License. import", "url parsed_url = urlparse.urlparse(url) logger.debug(\"The parsed url for publisher is", "License. You may obtain # a copy of the License", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "import daiquiri from six.moves.urllib import parse as urlparse from stevedore", "PublisherManager(object): def __init__(self, conf, url): self.conf = conf self.url =", "logger = daiquiri.getLogger(__name__) class PublisherManager(object): def __init__(self, conf, url): self.conf", "# Unless required by applicable law or agreed to in", "for publisher is :%s\" % str(parsed_url)) self.publish_driver = driver.DriverManager( 'bter.publisher',", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "urlparse from stevedore import driver logger = daiquiri.getLogger(__name__) class PublisherManager(object):", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "logger.debug(\"The parsed url for publisher is :%s\" % str(parsed_url)) self.publish_driver", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "governing permissions and limitations # under the License. import daiquiri", "conf self.url = url parsed_url = urlparse.urlparse(url) logger.debug(\"The parsed url", "from stevedore import driver logger = daiquiri.getLogger(__name__) class PublisherManager(object): def", "or agreed to in writing, software # distributed under the", "<<EMAIL>> # # Licensed under the Apache License, Version 2.0", "required by applicable law or agreed to in writing, software", "self.conf = conf self.url = url parsed_url = urlparse.urlparse(url) logger.debug(\"The", "import parse as urlparse from stevedore import driver logger =", "parsed url for publisher is :%s\" % str(parsed_url)) self.publish_driver =", "urlparse.urlparse(url) logger.debug(\"The parsed url for publisher is :%s\" % str(parsed_url))", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not", "url): self.conf = conf self.url = url parsed_url = urlparse.urlparse(url)" ]
[ "], \"type\": \"function\", }, { \"constant\": True, \"inputs\": [], \"name\":", "[], \"name\": \"counter\", \"outputs\": [ {\"name\": \"\", \"type\": \"uint256\"}, ],", "\"1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780\" \"63dcf537b11461014057610074565b005b610083600480505061016c565b60405180828152602001\" \"91505060405180910390f35b6100a6600480505061017f565b604051808281526020019150506040\" \"5180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191\" \"505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea\" \"<KEY>\" \"8082815260200191505060405180910390f35b610156600480803590602001909190505061021756\" \"5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90\" \"565b60006000505481565b6000816000600082828250540192505081905550600060005054905080\" \"507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082\"", "[ {\"name\": \"a\", \"type\": \"int256\"}, {\"name\": \"b\", \"type\": \"int256\"}, ],", "\"name\": \"counter\", \"outputs\": [ {\"name\": \"\", \"type\": \"uint256\"}, ], \"type\":", "{\"name\": \"\", \"type\": \"uint256\"}, ], \"type\": \"function\", }, { \"constant\":", "}, { \"constant\": False, \"inputs\": [ {\"name\": \"amt\", \"type\": \"uint256\"},", "\"inputs\": [], \"name\": \"counter\", \"outputs\": [ {\"name\": \"\", \"type\": \"uint256\"},", "\"constant\": False, \"inputs\": [], \"name\": \"increment\", \"outputs\": [ {\"name\": \"\",", "{ \"anonymous\": False, \"inputs\": [ {\"indexed\": False, \"name\": \"value\", \"type\":", "False, \"inputs\": [], \"name\": \"increment\", \"outputs\": [ {\"name\": \"\", \"type\":", "\"type\": \"function\" }, { \"constant\": False, \"inputs\": [ {\"name\": \"a\",", "\"return13\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"}, ], \"type\": \"function\",", "\"name\": \"multiply7\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"}, ], \"type\":", "False, \"inputs\": [ {\"name\": \"a\", \"type\": \"int256\"}, {\"name\": \"b\", \"type\":", "\"int256\"}, ], \"type\": \"function\", }, { \"constant\": False, \"inputs\": [],", "\"type\": \"function\", }, { \"constant\": True, \"inputs\": [], \"name\": \"counter\",", "[ {\"name\": \"amt\", \"type\": \"uint256\"}, ], \"name\": \"increment\", \"outputs\": [", "\"int256\"}, ], \"type\": \"function\", }, { \"anonymous\": False, \"inputs\": [", "\"multiply7\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"}, ], \"type\": \"function\",", "}, { \"constant\": True, \"inputs\": [], \"name\": \"counter\", \"outputs\": [", "\"type\": \"int256\"}, ], \"type\": \"function\", }, { \"anonymous\": False, \"inputs\":", "{\"name\": \"result\", \"type\": \"int256\"}, ], \"type\": \"function\", }, { \"constant\":", ") MATH_ABI = [ { \"constant\": False, \"inputs\": [], \"name\":", "{\"name\": \"a\", \"type\": \"int256\"}, {\"name\": \"b\", \"type\": \"int256\"}, ], \"name\":", "\"type\": \"function\", }, { \"constant\": False, \"inputs\": [ {\"name\": \"amt\",", "[ {\"name\": \"\", \"type\": \"uint256\"}, ], \"type\": \"function\" }, {", "[ {\"name\": \"result\", \"type\": \"uint256\"}, ], \"type\": \"function\", }, {", "\"type\": \"int256\"}, {\"name\": \"b\", \"type\": \"int256\"}, ], \"name\": \"add\", \"outputs\":", "{\"name\": \"b\", \"type\": \"int256\"}, ], \"name\": \"add\", \"outputs\": [ {\"name\":", "\"91505060405180910390f35b6100a6600480505061017f565b604051808281526020019150506040\" \"5180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191\" \"505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea\" \"<KEY>\" \"8082815260200191505060405180910390f35b610156600480803590602001909190505061021756\" \"5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90\" \"565b60006000505481565b6000816000600082828250540192505081905550600060005054905080\" \"507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082\" \"815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090\" \"506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202\"", "\"name\": \"increment\", \"outputs\": [ {\"name\": \"result\", \"type\": \"uint256\"}, ], \"type\":", "\"increment\", \"outputs\": [ {\"name\": \"\", \"type\": \"uint256\"}, ], \"type\": \"function\"", "\"5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90\" \"565b60006000505481565b6000816000600082828250540192505081905550600060005054905080\" \"507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082\" \"815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090\" \"506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202\" \"90508050809050610229565b91905056\" ) MATH_ABI = [", "\"constant\": False, \"inputs\": [], \"name\": \"return13\", \"outputs\": [ {\"name\": \"result\",", "}, { \"constant\": False, \"inputs\": [], \"name\": \"increment\", \"outputs\": [", "\"constant\": False, \"inputs\": [ {\"name\": \"a\", \"type\": \"int256\"}, ], \"name\":", "\"507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082\" \"815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090\" \"506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202\" \"90508050809050610229565b91905056\" ) MATH_ABI = [ { \"constant\":", "\"result\", \"type\": \"int256\"}, ], \"type\": \"function\", }, { \"anonymous\": False,", "[ {\"name\": \"a\", \"type\": \"int256\"}, ], \"name\": \"multiply7\", \"outputs\": [", "\"type\": \"function\", }, { \"constant\": False, \"inputs\": [ {\"name\": \"a\",", "\"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"}, ], \"type\": \"function\", },", "\"inputs\": [ {\"name\": \"a\", \"type\": \"int256\"}, {\"name\": \"b\", \"type\": \"int256\"},", "\"function\" }, { \"constant\": False, \"inputs\": [ {\"name\": \"a\", \"type\":", "\"increment\", \"outputs\": [ {\"name\": \"result\", \"type\": \"uint256\"}, ], \"type\": \"function\",", "\"8082815260200191505060405180910390f35b610156600480803590602001909190505061021756\" \"5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90\" \"565b60006000505481565b6000816000600082828250540192505081905550600060005054905080\" \"507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082\" \"815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090\" \"506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202\" \"90508050809050610229565b91905056\" ) MATH_ABI =", "\"inputs\": [ {\"name\": \"amt\", \"type\": \"uint256\"}, ], \"name\": \"increment\", \"outputs\":", "False, \"inputs\": [ {\"name\": \"a\", \"type\": \"int256\"}, ], \"name\": \"multiply7\",", "}, { \"anonymous\": False, \"inputs\": [ {\"indexed\": False, \"name\": \"value\",", "\"int256\"}, ], \"name\": \"add\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"},", "True, \"inputs\": [], \"name\": \"counter\", \"outputs\": [ {\"name\": \"\", \"type\":", "MATH_ABI = [ { \"constant\": False, \"inputs\": [], \"name\": \"return13\",", "], \"name\": \"increment\", \"outputs\": [ {\"name\": \"result\", \"type\": \"uint256\"}, ],", "\"constant\": True, \"inputs\": [], \"name\": \"counter\", \"outputs\": [ {\"name\": \"\",", "\"name\": \"return13\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"}, ], \"type\":", "{ \"constant\": False, \"inputs\": [], \"name\": \"return13\", \"outputs\": [ {\"name\":", "{ \"constant\": False, \"inputs\": [ {\"name\": \"a\", \"type\": \"int256\"}, ],", "\"<KEY>\" \"8082815260200191505060405180910390f35b610156600480803590602001909190505061021756\" \"5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90\" \"565b60006000505481565b6000816000600082828250540192505081905550600060005054905080\" \"507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082\" \"815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090\" \"506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202\" \"90508050809050610229565b91905056\" ) MATH_ABI", "\"function\", }, { \"constant\": True, \"inputs\": [], \"name\": \"counter\", \"outputs\":", "], \"type\": \"function\" }, { \"constant\": False, \"inputs\": [ {\"name\":", "\"815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090\" \"506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202\" \"90508050809050610229565b91905056\" ) MATH_ABI = [ { \"constant\": False,", "{\"indexed\": False, \"name\": \"value\", \"type\": \"uint256\"}, ], \"name\": \"Increased\", \"type\":", "\"inputs\": [ {\"name\": \"a\", \"type\": \"int256\"}, ], \"name\": \"multiply7\", \"outputs\":", "\"constant\": False, \"inputs\": [ {\"name\": \"a\", \"type\": \"int256\"}, {\"name\": \"b\",", "{\"name\": \"a\", \"type\": \"int256\"}, ], \"name\": \"multiply7\", \"outputs\": [ {\"name\":", "\"function\", }, { \"constant\": False, \"inputs\": [ {\"name\": \"amt\", \"type\":", "\"type\": \"uint256\"}, ], \"type\": \"function\", }, { \"constant\": False, \"inputs\":", "[], \"name\": \"return13\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"}, ],", "\"amt\", \"type\": \"uint256\"}, ], \"name\": \"increment\", \"outputs\": [ {\"name\": \"result\",", "False, \"name\": \"value\", \"type\": \"uint256\"}, ], \"name\": \"Increased\", \"type\": \"event\",", "\"anonymous\": False, \"inputs\": [ {\"indexed\": False, \"name\": \"value\", \"type\": \"uint256\"},", "\"a\", \"type\": \"int256\"}, ], \"name\": \"multiply7\", \"outputs\": [ {\"name\": \"result\",", "\"606060405261022e806100126000396000f360606040523615610074576000357c01000000000000\" \"000000000000000000000000000000000000000000009004806316216f391461007657806361bc22\" \"1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780\" \"63dcf537b11461014057610074565b005b610083600480505061016c565b60405180828152602001\" \"91505060405180910390f35b6100a6600480505061017f565b604051808281526020019150506040\" \"5180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191\" \"505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea\" \"<KEY>\" \"8082815260200191505060405180910390f35b610156600480803590602001909190505061021756\" \"5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90\"", "\"function\", }, { \"anonymous\": False, \"inputs\": [ {\"indexed\": False, \"name\":", "\"uint256\"}, ], \"type\": \"function\", }, { \"constant\": False, \"inputs\": [", "\"outputs\": [ {\"name\": \"\", \"type\": \"uint256\"}, ], \"type\": \"function\", },", "\"type\": \"int256\"}, ], \"type\": \"function\", }, { \"constant\": False, \"inputs\":", "\"90508050809050610229565b91905056\" ) MATH_ABI = [ { \"constant\": False, \"inputs\": [],", "False, \"inputs\": [], \"name\": \"return13\", \"outputs\": [ {\"name\": \"result\", \"type\":", "\"\", \"type\": \"uint256\"}, ], \"type\": \"function\" }, { \"constant\": False,", "\"type\": \"int256\"}, ], \"name\": \"add\", \"outputs\": [ {\"name\": \"result\", \"type\":", "{ \"constant\": False, \"inputs\": [], \"name\": \"increment\", \"outputs\": [ {\"name\":", "\"int256\"}, ], \"name\": \"multiply7\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"},", "{\"name\": \"\", \"type\": \"uint256\"}, ], \"type\": \"function\" }, { \"constant\":", "False, \"inputs\": [ {\"name\": \"amt\", \"type\": \"uint256\"}, ], \"name\": \"increment\",", "}, { \"constant\": False, \"inputs\": [ {\"name\": \"a\", \"type\": \"int256\"},", "[], \"name\": \"increment\", \"outputs\": [ {\"name\": \"\", \"type\": \"uint256\"}, ],", "{ \"constant\": True, \"inputs\": [], \"name\": \"counter\", \"outputs\": [ {\"name\":", "\"constant\": False, \"inputs\": [ {\"name\": \"amt\", \"type\": \"uint256\"}, ], \"name\":", "{ \"constant\": False, \"inputs\": [ {\"name\": \"amt\", \"type\": \"uint256\"}, ],", "\"uint256\"}, ], \"name\": \"increment\", \"outputs\": [ {\"name\": \"result\", \"type\": \"uint256\"},", "\"outputs\": [ {\"name\": \"\", \"type\": \"uint256\"}, ], \"type\": \"function\" },", "], \"name\": \"multiply7\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"}, ],", "\"63dcf537b11461014057610074565b005b610083600480505061016c565b60405180828152602001\" \"91505060405180910390f35b6100a6600480505061017f565b604051808281526020019150506040\" \"5180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191\" \"505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea\" \"<KEY>\" \"8082815260200191505060405180910390f35b610156600480803590602001909190505061021756\" \"5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90\" \"565b60006000505481565b6000816000600082828250540192505081905550600060005054905080\" \"507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082\" \"815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090\"", "( \"606060405261022e806100126000396000f360606040523615610074576000357c01000000000000\" \"000000000000000000000000000000000000000000009004806316216f391461007657806361bc22\" \"1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780\" \"63dcf537b11461014057610074565b005b610083600480505061016c565b60405180828152602001\" \"91505060405180910390f35b6100a6600480505061017f565b604051808281526020019150506040\" \"5180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191\" \"505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea\" \"<KEY>\" \"8082815260200191505060405180910390f35b610156600480803590602001909190505061021756\"", "\"result\", \"type\": \"uint256\"}, ], \"type\": \"function\", }, { \"constant\": False,", "{\"name\": \"result\", \"type\": \"int256\"}, ], \"type\": \"function\", }, { \"anonymous\":", "\"565b60006000505481565b6000816000600082828250540192505081905550600060005054905080\" \"507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082\" \"815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090\" \"506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202\" \"90508050809050610229565b91905056\" ) MATH_ABI = [ {", "\"name\": \"value\", \"type\": \"uint256\"}, ], \"name\": \"Increased\", \"type\": \"event\", },", "\"5180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191\" \"505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea\" \"<KEY>\" \"8082815260200191505060405180910390f35b610156600480803590602001909190505061021756\" \"5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90\" \"565b60006000505481565b6000816000600082828250540192505081905550600060005054905080\" \"507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082\" \"815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090\" \"506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202\" \"90508050809050610229565b91905056\"", "{\"name\": \"amt\", \"type\": \"uint256\"}, ], \"name\": \"increment\", \"outputs\": [ {\"name\":", "[ {\"name\": \"result\", \"type\": \"int256\"}, ], \"type\": \"function\", }, {", "], \"type\": \"function\", }, { \"constant\": False, \"inputs\": [], \"name\":", "\"uint256\"}, ], \"type\": \"function\" }, { \"constant\": False, \"inputs\": [", "\"inputs\": [ {\"indexed\": False, \"name\": \"value\", \"type\": \"uint256\"}, ], \"name\":", "\"000000000000000000000000000000000000000000009004806316216f391461007657806361bc22\" \"1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780\" \"63dcf537b11461014057610074565b005b610083600480505061016c565b60405180828152602001\" \"91505060405180910390f35b6100a6600480505061017f565b604051808281526020019150506040\" \"5180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191\" \"505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea\" \"<KEY>\" \"8082815260200191505060405180910390f35b610156600480803590602001909190505061021756\" \"5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90\" \"565b60006000505481565b6000816000600082828250540192505081905550600060005054905080\"", "[ {\"name\": \"\", \"type\": \"uint256\"}, ], \"type\": \"function\", }, {", "\"\", \"type\": \"uint256\"}, ], \"type\": \"function\", }, { \"constant\": False,", "\"value\", \"type\": \"uint256\"}, ], \"name\": \"Increased\", \"type\": \"event\", }, ]", "], \"type\": \"function\", }, { \"constant\": False, \"inputs\": [ {\"name\":", "\"inputs\": [], \"name\": \"increment\", \"outputs\": [ {\"name\": \"\", \"type\": \"uint256\"},", "\"counter\", \"outputs\": [ {\"name\": \"\", \"type\": \"uint256\"}, ], \"type\": \"function\",", "], \"name\": \"add\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"}, ],", "\"506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202\" \"90508050809050610229565b91905056\" ) MATH_ABI = [ { \"constant\": False, \"inputs\":", "{ \"constant\": False, \"inputs\": [ {\"name\": \"a\", \"type\": \"int256\"}, {\"name\":", "\"name\": \"add\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"}, ], \"type\":", "\"result\", \"type\": \"int256\"}, ], \"type\": \"function\", }, { \"constant\": False,", "= ( \"606060405261022e806100126000396000f360606040523615610074576000357c01000000000000\" \"000000000000000000000000000000000000000000009004806316216f391461007657806361bc22\" \"1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780\" \"63dcf537b11461014057610074565b005b610083600480505061016c565b60405180828152602001\" \"91505060405180910390f35b6100a6600480505061017f565b604051808281526020019150506040\" \"5180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191\" \"505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea\" \"<KEY>\"", "\"function\", }, { \"constant\": False, \"inputs\": [ {\"name\": \"a\", \"type\":", "\"type\": \"function\", }, { \"anonymous\": False, \"inputs\": [ {\"indexed\": False,", "\"a\", \"type\": \"int256\"}, {\"name\": \"b\", \"type\": \"int256\"}, ], \"name\": \"add\",", "\"function\", }, { \"constant\": False, \"inputs\": [], \"name\": \"increment\", \"outputs\":", "\"result\", \"type\": \"int256\"}, ], \"type\": \"function\", }, { \"constant\": True,", "\"505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea\" \"<KEY>\" \"8082815260200191505060405180910390f35b610156600480803590602001909190505061021756\" \"5b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90\" \"565b60006000505481565b6000816000600082828250540192505081905550600060005054905080\" \"507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082\" \"815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090\" \"506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b600060078202\" \"90508050809050610229565b91905056\" )", "], \"type\": \"function\", }, { \"anonymous\": False, \"inputs\": [ {\"indexed\":", "\"outputs\": [ {\"name\": \"result\", \"type\": \"uint256\"}, ], \"type\": \"function\", },", "False, \"inputs\": [ {\"indexed\": False, \"name\": \"value\", \"type\": \"uint256\"}, ],", "\"inputs\": [], \"name\": \"return13\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"},", "MATH_BYTECODE = ( \"606060405261022e806100126000396000f360606040523615610074576000357c01000000000000\" \"000000000000000000000000000000000000000000009004806316216f391461007657806361bc22\" \"1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780\" \"63dcf537b11461014057610074565b005b610083600480505061016c565b60405180828152602001\" \"91505060405180910390f35b6100a6600480505061017f565b604051808281526020019150506040\" \"5180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191\" \"505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea\"", "\"type\": \"uint256\"}, ], \"name\": \"increment\", \"outputs\": [ {\"name\": \"result\", \"type\":", "\"type\": \"int256\"}, ], \"type\": \"function\", }, { \"constant\": True, \"inputs\":", "\"int256\"}, {\"name\": \"b\", \"type\": \"int256\"}, ], \"name\": \"add\", \"outputs\": [", "\"int256\"}, ], \"type\": \"function\", }, { \"constant\": True, \"inputs\": [],", "[ {\"indexed\": False, \"name\": \"value\", \"type\": \"uint256\"}, ], \"name\": \"Increased\",", "\"type\": \"uint256\"}, ], \"type\": \"function\" }, { \"constant\": False, \"inputs\":", "\"type\": \"int256\"}, ], \"name\": \"multiply7\", \"outputs\": [ {\"name\": \"result\", \"type\":", "[ { \"constant\": False, \"inputs\": [], \"name\": \"return13\", \"outputs\": [", "\"add\", \"outputs\": [ {\"name\": \"result\", \"type\": \"int256\"}, ], \"type\": \"function\",", "{\"name\": \"result\", \"type\": \"uint256\"}, ], \"type\": \"function\", }, { \"constant\":", "\"b\", \"type\": \"int256\"}, ], \"name\": \"add\", \"outputs\": [ {\"name\": \"result\",", "\"name\": \"increment\", \"outputs\": [ {\"name\": \"\", \"type\": \"uint256\"}, ], \"type\":", "\"type\": \"function\", }, { \"constant\": False, \"inputs\": [], \"name\": \"increment\",", "= [ { \"constant\": False, \"inputs\": [], \"name\": \"return13\", \"outputs\":" ]
[ "= CONF.DB.connection self.SQLALCHEMY_TRACK_MODIFICATIONS = False self.PERMANENT_SESSION_LIFETIME = timedelta(days=1) # SECRET_KEY", "are ' 'killed and restarted.'), cfg.StrOpt('worker-class', default='sync', help='The type of", "CONF.register_opts([ cfg.StrOpt('server'), cfg.StrOpt('port'), cfg.StrOpt('from_addr'), cfg.StrOpt('info_list'), cfg.StrOpt('alert_list'), ], 'MAIL') CONF.register_opts([ cfg.StrOpt('allow_ip'),", "choices=('gunicorn', 'werkzeug'), help=\"Run server use the specify mode.\"), cfg.StrOpt('bind', default='0.0.0.0',", "write to.' '\"-\" means log to stderr.'), cfg.StrOpt('loglevel', default='info', help='The", "default=0, help='The number of worker processes for handling requests'), cfg.BoolOpt('daemon',", "<reponame>nuby/open_dnsdb # -*- coding: utf-8 -*- import os import sys", "'gevent', 'tornado')) ], 'gunicorn') def setup_config(app_env, app_kind, conf_dir): if \"--\"", "Gunicorn config file.'), cfg.StrOpt('bind', default='127.0.0.1:8888'), cfg.IntOpt('workers', default=0, help='The number of", "default=False, help='Daemonize the Gunicorn process'), cfg.StrOpt('accesslog', default=None, help='The Access log", "url prefix of this site.'), cfg.StrOpt('run-mode', default=\"werkzeug\", choices=('gunicorn', 'werkzeug'), help=\"Run", "cfg.StrOpt('bind', default='0.0.0.0', help='The IP address to bind'), cfg.IntOpt('port', default=8080, help='The", "default=False), cfg.IntOpt('timeout', default=30, help='Workers silent for more than this many", "[common_config_file] app_config_file = os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) self.SECRET_KEY", "\"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) self.SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key", "], 'MAIL') CONF.register_opts([ cfg.StrOpt('allow_ip'), cfg.StrOpt('secret_key'), cfg.StrOpt('env'), cfg.StrOpt('local_group'), cfg.StrOpt('acl_dir'), cfg.StrOpt('view_acl_group') ],", "setup_config(app_env, app_kind, conf_dir): if \"--\" in sys.argv: args = sys.argv[sys.argv.index(\"--\")", "the Gunicorn process'), cfg.StrOpt('accesslog', default=None, help='The Access log file to", "# print 'conf_dir: ', conf_dir if \"--\" in sys.argv: args", "Gunicorn process'), cfg.StrOpt('accesslog', default=None, help='The Access log file to write", "self.SQLALCHEMY_DATABASE_URI = CONF.DB.connection self.SQLALCHEMY_TRACK_MODIFICATIONS = False self.PERMANENT_SESSION_LIFETIME = timedelta(days=1) #", "-*- import os import sys from datetime import timedelta from", "= os.environ.get('SECRET_KEY') or CONF.etc.secret_key self.SQLALCHEMY_DATABASE_URI = CONF.DB.connection self.SQLALCHEMY_TRACK_MODIFICATIONS = False", "cfg.StrOpt('secret_key'), cfg.StrOpt('env'), cfg.StrOpt('local_group'), cfg.StrOpt('acl_dir'), cfg.StrOpt('view_acl_group') ], 'etc') CONF.register_opts([ cfg.IntOpt('dnsupdater_port'), ],", "cfg.StrOpt('loglevel', default='info', help='The granularity of Error log outputs.', choices=('debug', 'info',", "conf_dir if \"--\" in sys.argv: args = sys.argv[sys.argv.index(\"--\") + 1:]", "file to write to.' '\"-\" means log to stderr.'), cfg.StrOpt('loglevel',", "log outputs.', choices=('debug', 'info', 'warning', 'error', 'critical')), cfg.BoolOpt('ignore-healthcheck-accesslog', default=False), cfg.IntOpt('timeout',", "datetime import timedelta from oslo.config import cfg CONF = cfg.CONF", "oslo.config import cfg CONF = cfg.CONF CONF.register_opts([ cfg.StrOpt('log-dir'), cfg.StrOpt('log-file'), cfg.StrOpt('debug'),", "cfg.StrOpt('alert_list'), ], 'MAIL') CONF.register_opts([ cfg.StrOpt('allow_ip'), cfg.StrOpt('secret_key'), cfg.StrOpt('env'), cfg.StrOpt('local_group'), cfg.StrOpt('acl_dir'), cfg.StrOpt('view_acl_group')", "'tornado')) ], 'gunicorn') def setup_config(app_env, app_kind, conf_dir): if \"--\" in", "CONF.register_opts([ cfg.StrOpt('config', default=None, help='The path to a Gunicorn config file.'),", "cfg.StrOpt('verbose'), ], 'log') CONF.register_opts([ cfg.StrOpt('connection'), cfg.StrOpt('data'), ], 'DB') CONF.register_opts([ cfg.StrOpt('server'),", "site.'), cfg.StrOpt('run-mode', default=\"werkzeug\", choices=('gunicorn', 'werkzeug'), help=\"Run server use the specify", "cfg.StrOpt('worker-class', default='sync', help='The type of workers to use.', choices=('sync', 'eventlet',", "class Config(object): def __init__(self, app_env, app_kind, conf_dir): # print 'conf_dir:", "to use.', choices=('sync', 'eventlet', 'gevent', 'tornado')) ], 'gunicorn') def setup_config(app_env,", "'gunicorn') def setup_config(app_env, app_kind, conf_dir): if \"--\" in sys.argv: args", "print 'conf_dir: ', conf_dir if \"--\" in sys.argv: args =", "many seconds are ' 'killed and restarted.'), cfg.StrOpt('worker-class', default='sync', help='The", "app_env, app_kind, conf_dir): # print 'conf_dir: ', conf_dir if \"--\"", "cfg CONF = cfg.CONF CONF.register_opts([ cfg.StrOpt('log-dir'), cfg.StrOpt('log-file'), cfg.StrOpt('debug'), cfg.StrOpt('verbose'), ],", "help='The IP address to bind'), cfg.IntOpt('port', default=8080, help='The port to", "import sys from datetime import timedelta from oslo.config import cfg", "'DB') CONF.register_opts([ cfg.StrOpt('server'), cfg.StrOpt('port'), cfg.StrOpt('from_addr'), cfg.StrOpt('info_list'), cfg.StrOpt('alert_list'), ], 'MAIL') CONF.register_opts([", "bind'), cfg.IntOpt('port', default=8080, help='The port to listen'), cfg.BoolOpt('debug', default=False), ],", "'etc') CONF.register_opts([ cfg.IntOpt('dnsupdater_port'), ], 'api') CONF.register_opts([ cfg.StrOpt('acl_groups'), cfg.IntOpt('cname_ttl'), cfg.StrOpt('view_zone') ],", "], 'gunicorn') def setup_config(app_env, app_kind, conf_dir): if \"--\" in sys.argv:", "\"etc/{}/common.conf\".format(app_env)) default_config_files = [common_config_file] app_config_file = os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file)", "or CONF.etc.secret_key self.SQLALCHEMY_DATABASE_URI = CONF.DB.connection self.SQLALCHEMY_TRACK_MODIFICATIONS = False self.PERMANENT_SESSION_LIFETIME =", "= timedelta(days=1) # SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key # SQLALCHEMY_DATABASE_URI", "default='/', help='The url prefix of this site.'), cfg.StrOpt('run-mode', default=\"werkzeug\", choices=('gunicorn',", "workers to use.', choices=('sync', 'eventlet', 'gevent', 'tornado')) ], 'gunicorn') def", "SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key # SQLALCHEMY_DATABASE_URI = CONF.DB.connection #", "os.environ.get('SECRET_KEY') or CONF.etc.secret_key # SQLALCHEMY_DATABASE_URI = CONF.DB.connection # SQLALCHEMY_TRACK_MODIFICATIONS =", "= [common_config_file] app_config_file = os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args)", "self.SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key self.SQLALCHEMY_DATABASE_URI = CONF.DB.connection self.SQLALCHEMY_TRACK_MODIFICATIONS =", "os import sys from datetime import timedelta from oslo.config import", "cfg.StrOpt('port'), cfg.StrOpt('from_addr'), cfg.StrOpt('info_list'), cfg.StrOpt('alert_list'), ], 'MAIL') CONF.register_opts([ cfg.StrOpt('allow_ip'), cfg.StrOpt('secret_key'), cfg.StrOpt('env'),", "timedelta from oslo.config import cfg CONF = cfg.CONF CONF.register_opts([ cfg.StrOpt('log-dir'),", "mode.\"), cfg.StrOpt('bind', default='0.0.0.0', help='The IP address to bind'), cfg.IntOpt('port', default=8080,", "CONF.register_opts([ cfg.StrOpt('allow_ip'), cfg.StrOpt('secret_key'), cfg.StrOpt('env'), cfg.StrOpt('local_group'), cfg.StrOpt('acl_dir'), cfg.StrOpt('view_acl_group') ], 'etc') CONF.register_opts([", "cfg.StrOpt('config', default=None, help='The path to a Gunicorn config file.'), cfg.StrOpt('bind',", "help='The granularity of Error log outputs.', choices=('debug', 'info', 'warning', 'error',", "default=8080, help='The port to listen'), cfg.BoolOpt('debug', default=False), ], 'web') CONF.register_opts([", "granularity of Error log outputs.', choices=('debug', 'info', 'warning', 'error', 'critical')),", "sys.argv: args = sys.argv[sys.argv.index(\"--\") + 1:] else: args = []", "# SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key # SQLALCHEMY_DATABASE_URI = CONF.DB.connection", "# SQLALCHEMY_DATABASE_URI = CONF.DB.connection # SQLALCHEMY_TRACK_MODIFICATIONS = False # PERMANENT_SESSION_LIFETIME", "cfg.StrOpt('base-url', default='/', help='The url prefix of this site.'), cfg.StrOpt('run-mode', default=\"werkzeug\",", "cfg.IntOpt('dnsupdater_port'), ], 'api') CONF.register_opts([ cfg.StrOpt('acl_groups'), cfg.IntOpt('cname_ttl'), cfg.StrOpt('view_zone') ], 'view') CONF.register_opts([", "= os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) self.SECRET_KEY = os.environ.get('SECRET_KEY')", "a Gunicorn config file.'), cfg.StrOpt('bind', default='127.0.0.1:8888'), cfg.IntOpt('workers', default=0, help='The number", "cfg.StrOpt('debug'), cfg.StrOpt('verbose'), ], 'log') CONF.register_opts([ cfg.StrOpt('connection'), cfg.StrOpt('data'), ], 'DB') CONF.register_opts([", "default=\"werkzeug\", choices=('gunicorn', 'werkzeug'), help=\"Run server use the specify mode.\"), cfg.StrOpt('bind',", "], 'etc') CONF.register_opts([ cfg.IntOpt('dnsupdater_port'), ], 'api') CONF.register_opts([ cfg.StrOpt('acl_groups'), cfg.IntOpt('cname_ttl'), cfg.StrOpt('view_zone')", "'MAIL') CONF.register_opts([ cfg.StrOpt('allow_ip'), cfg.StrOpt('secret_key'), cfg.StrOpt('env'), cfg.StrOpt('local_group'), cfg.StrOpt('acl_dir'), cfg.StrOpt('view_acl_group') ], 'etc')", "= sys.argv[sys.argv.index(\"--\") + 1:] else: args = [] common_config_file =", "app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) self.SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key self.SQLALCHEMY_DATABASE_URI", "False self.PERMANENT_SESSION_LIFETIME = timedelta(days=1) # SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key", "choices=('debug', 'info', 'warning', 'error', 'critical')), cfg.BoolOpt('ignore-healthcheck-accesslog', default=False), cfg.IntOpt('timeout', default=30, help='Workers", "from datetime import timedelta from oslo.config import cfg CONF =", "use.', choices=('sync', 'eventlet', 'gevent', 'tornado')) ], 'gunicorn') def setup_config(app_env, app_kind,", "file.'), cfg.StrOpt('bind', default='127.0.0.1:8888'), cfg.IntOpt('workers', default=0, help='The number of worker processes", "CONF(default_config_files=default_config_files, args=args) self.SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key self.SQLALCHEMY_DATABASE_URI = CONF.DB.connection", "os.path.join(conf_dir, \"etc/{}/common.conf\".format(app_env)) default_config_files = [common_config_file] app_config_file = os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind))", "cfg.StrOpt('info_list'), cfg.StrOpt('alert_list'), ], 'MAIL') CONF.register_opts([ cfg.StrOpt('allow_ip'), cfg.StrOpt('secret_key'), cfg.StrOpt('env'), cfg.StrOpt('local_group'), cfg.StrOpt('acl_dir'),", "= False self.PERMANENT_SESSION_LIFETIME = timedelta(days=1) # SECRET_KEY = os.environ.get('SECRET_KEY') or", "args = [] common_config_file = os.path.join(conf_dir, \"etc/{}/common.conf\".format(app_env)) default_config_files = [common_config_file]", "def __init__(self, app_env, app_kind, conf_dir): # print 'conf_dir: ', conf_dir", "# -*- coding: utf-8 -*- import os import sys from", "CONF.register_opts([ cfg.StrOpt('log-dir'), cfg.StrOpt('log-file'), cfg.StrOpt('debug'), cfg.StrOpt('verbose'), ], 'log') CONF.register_opts([ cfg.StrOpt('connection'), cfg.StrOpt('data'),", "path to a Gunicorn config file.'), cfg.StrOpt('bind', default='127.0.0.1:8888'), cfg.IntOpt('workers', default=0,", "cfg.StrOpt('acl_groups'), cfg.IntOpt('cname_ttl'), cfg.StrOpt('view_zone') ], 'view') CONF.register_opts([ cfg.StrOpt('base-url', default='/', help='The url", "cfg.CONF CONF.register_opts([ cfg.StrOpt('log-dir'), cfg.StrOpt('log-file'), cfg.StrOpt('debug'), cfg.StrOpt('verbose'), ], 'log') CONF.register_opts([ cfg.StrOpt('connection'),", "default='127.0.0.1:8888'), cfg.IntOpt('workers', default=0, help='The number of worker processes for handling", "outputs.', choices=('debug', 'info', 'warning', 'error', 'critical')), cfg.BoolOpt('ignore-healthcheck-accesslog', default=False), cfg.IntOpt('timeout', default=30,", "'api') CONF.register_opts([ cfg.StrOpt('acl_groups'), cfg.IntOpt('cname_ttl'), cfg.StrOpt('view_zone') ], 'view') CONF.register_opts([ cfg.StrOpt('base-url', default='/',", "to listen'), cfg.BoolOpt('debug', default=False), ], 'web') CONF.register_opts([ cfg.StrOpt('config', default=None, help='The", "server use the specify mode.\"), cfg.StrOpt('bind', default='0.0.0.0', help='The IP address", "conf_dir): # print 'conf_dir: ', conf_dir if \"--\" in sys.argv:", "self.PERMANENT_SESSION_LIFETIME = timedelta(days=1) # SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key #", "cfg.StrOpt('bind', default='127.0.0.1:8888'), cfg.IntOpt('workers', default=0, help='The number of worker processes for", "args=args) self.SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key self.SQLALCHEMY_DATABASE_URI = CONF.DB.connection self.SQLALCHEMY_TRACK_MODIFICATIONS", "seconds are ' 'killed and restarted.'), cfg.StrOpt('worker-class', default='sync', help='The type", "= cfg.CONF CONF.register_opts([ cfg.StrOpt('log-dir'), cfg.StrOpt('log-file'), cfg.StrOpt('debug'), cfg.StrOpt('verbose'), ], 'log') CONF.register_opts([", "help='Workers silent for more than this many seconds are '", "app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) class Config(object): def __init__(self, app_env, app_kind,", "utf-8 -*- import os import sys from datetime import timedelta", "], 'log') CONF.register_opts([ cfg.StrOpt('connection'), cfg.StrOpt('data'), ], 'DB') CONF.register_opts([ cfg.StrOpt('server'), cfg.StrOpt('port'),", "in sys.argv: args = sys.argv[sys.argv.index(\"--\") + 1:] else: args =", "Error log outputs.', choices=('debug', 'info', 'warning', 'error', 'critical')), cfg.BoolOpt('ignore-healthcheck-accesslog', default=False),", "than this many seconds are ' 'killed and restarted.'), cfg.StrOpt('worker-class',", "'conf_dir: ', conf_dir if \"--\" in sys.argv: args = sys.argv[sys.argv.index(\"--\")", "CONF.DB.connection self.SQLALCHEMY_TRACK_MODIFICATIONS = False self.PERMANENT_SESSION_LIFETIME = timedelta(days=1) # SECRET_KEY =", "number of worker processes for handling requests'), cfg.BoolOpt('daemon', default=False, help='Daemonize", "CONF.register_opts([ cfg.StrOpt('base-url', default='/', help='The url prefix of this site.'), cfg.StrOpt('run-mode',", "app_kind, conf_dir): # print 'conf_dir: ', conf_dir if \"--\" in", "to.' '\"-\" means log to stderr.'), cfg.StrOpt('loglevel', default='info', help='The granularity", "cfg.StrOpt('server'), cfg.StrOpt('port'), cfg.StrOpt('from_addr'), cfg.StrOpt('info_list'), cfg.StrOpt('alert_list'), ], 'MAIL') CONF.register_opts([ cfg.StrOpt('allow_ip'), cfg.StrOpt('secret_key'),", "= os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) class Config(object): def", "default=False), ], 'web') CONF.register_opts([ cfg.StrOpt('config', default=None, help='The path to a", "worker processes for handling requests'), cfg.BoolOpt('daemon', default=False, help='Daemonize the Gunicorn", "default_config_files = [common_config_file] app_config_file = os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files,", "use the specify mode.\"), cfg.StrOpt('bind', default='0.0.0.0', help='The IP address to", "silent for more than this many seconds are ' 'killed", "Config(object): def __init__(self, app_env, app_kind, conf_dir): # print 'conf_dir: ',", "', conf_dir if \"--\" in sys.argv: args = sys.argv[sys.argv.index(\"--\") +", "args = sys.argv[sys.argv.index(\"--\") + 1:] else: args = [] common_config_file", "1:] else: args = [] common_config_file = os.path.join(conf_dir, \"etc/{}/common.conf\".format(app_env)) default_config_files", "'warning', 'error', 'critical')), cfg.BoolOpt('ignore-healthcheck-accesslog', default=False), cfg.IntOpt('timeout', default=30, help='Workers silent for", "app_config_file = os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) class Config(object):", "coding: utf-8 -*- import os import sys from datetime import", "of worker processes for handling requests'), cfg.BoolOpt('daemon', default=False, help='Daemonize the", "CONF.etc.secret_key self.SQLALCHEMY_DATABASE_URI = CONF.DB.connection self.SQLALCHEMY_TRACK_MODIFICATIONS = False self.PERMANENT_SESSION_LIFETIME = timedelta(days=1)", "-*- coding: utf-8 -*- import os import sys from datetime", "IP address to bind'), cfg.IntOpt('port', default=8080, help='The port to listen'),", "SQLALCHEMY_DATABASE_URI = CONF.DB.connection # SQLALCHEMY_TRACK_MODIFICATIONS = False # PERMANENT_SESSION_LIFETIME =", "import timedelta from oslo.config import cfg CONF = cfg.CONF CONF.register_opts([", "requests'), cfg.BoolOpt('daemon', default=False, help='Daemonize the Gunicorn process'), cfg.StrOpt('accesslog', default=None, help='The", "to write to.' '\"-\" means log to stderr.'), cfg.StrOpt('loglevel', default='info',", "], 'web') CONF.register_opts([ cfg.StrOpt('config', default=None, help='The path to a Gunicorn", "= [] common_config_file = os.path.join(conf_dir, \"etc/{}/common.conf\".format(app_env)) default_config_files = [common_config_file] app_config_file", "cfg.StrOpt('view_acl_group') ], 'etc') CONF.register_opts([ cfg.IntOpt('dnsupdater_port'), ], 'api') CONF.register_opts([ cfg.StrOpt('acl_groups'), cfg.IntOpt('cname_ttl'),", "help='The path to a Gunicorn config file.'), cfg.StrOpt('bind', default='127.0.0.1:8888'), cfg.IntOpt('workers',", "cfg.IntOpt('timeout', default=30, help='Workers silent for more than this many seconds", "CONF.register_opts([ cfg.IntOpt('dnsupdater_port'), ], 'api') CONF.register_opts([ cfg.StrOpt('acl_groups'), cfg.IntOpt('cname_ttl'), cfg.StrOpt('view_zone') ], 'view')", "+ 1:] else: args = [] common_config_file = os.path.join(conf_dir, \"etc/{}/common.conf\".format(app_env))", "[common_config_file] app_config_file = os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) class", "default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) self.SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key self.SQLALCHEMY_DATABASE_URI =", "stderr.'), cfg.StrOpt('loglevel', default='info', help='The granularity of Error log outputs.', choices=('debug',", "'werkzeug'), help=\"Run server use the specify mode.\"), cfg.StrOpt('bind', default='0.0.0.0', help='The", "CONF.etc.secret_key # SQLALCHEMY_DATABASE_URI = CONF.DB.connection # SQLALCHEMY_TRACK_MODIFICATIONS = False #", "prefix of this site.'), cfg.StrOpt('run-mode', default=\"werkzeug\", choices=('gunicorn', 'werkzeug'), help=\"Run server", "cfg.StrOpt('acl_dir'), cfg.StrOpt('view_acl_group') ], 'etc') CONF.register_opts([ cfg.IntOpt('dnsupdater_port'), ], 'api') CONF.register_opts([ cfg.StrOpt('acl_groups'),", "cfg.StrOpt('log-file'), cfg.StrOpt('debug'), cfg.StrOpt('verbose'), ], 'log') CONF.register_opts([ cfg.StrOpt('connection'), cfg.StrOpt('data'), ], 'DB')", "of this site.'), cfg.StrOpt('run-mode', default=\"werkzeug\", choices=('gunicorn', 'werkzeug'), help=\"Run server use", "cfg.BoolOpt('debug', default=False), ], 'web') CONF.register_opts([ cfg.StrOpt('config', default=None, help='The path to", "Access log file to write to.' '\"-\" means log to", "more than this many seconds are ' 'killed and restarted.'),", "default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) class Config(object): def __init__(self, app_env, app_kind, conf_dir):", "= os.environ.get('SECRET_KEY') or CONF.etc.secret_key # SQLALCHEMY_DATABASE_URI = CONF.DB.connection # SQLALCHEMY_TRACK_MODIFICATIONS", "log to stderr.'), cfg.StrOpt('loglevel', default='info', help='The granularity of Error log", "cfg.StrOpt('env'), cfg.StrOpt('local_group'), cfg.StrOpt('acl_dir'), cfg.StrOpt('view_acl_group') ], 'etc') CONF.register_opts([ cfg.IntOpt('dnsupdater_port'), ], 'api')", "cfg.BoolOpt('daemon', default=False, help='Daemonize the Gunicorn process'), cfg.StrOpt('accesslog', default=None, help='The Access", "os.environ.get('SECRET_KEY') or CONF.etc.secret_key self.SQLALCHEMY_DATABASE_URI = CONF.DB.connection self.SQLALCHEMY_TRACK_MODIFICATIONS = False self.PERMANENT_SESSION_LIFETIME", "of Error log outputs.', choices=('debug', 'info', 'warning', 'error', 'critical')), cfg.BoolOpt('ignore-healthcheck-accesslog',", "cfg.StrOpt('from_addr'), cfg.StrOpt('info_list'), cfg.StrOpt('alert_list'), ], 'MAIL') CONF.register_opts([ cfg.StrOpt('allow_ip'), cfg.StrOpt('secret_key'), cfg.StrOpt('env'), cfg.StrOpt('local_group'),", "choices=('sync', 'eventlet', 'gevent', 'tornado')) ], 'gunicorn') def setup_config(app_env, app_kind, conf_dir):", "to stderr.'), cfg.StrOpt('loglevel', default='info', help='The granularity of Error log outputs.',", "'info', 'warning', 'error', 'critical')), cfg.BoolOpt('ignore-healthcheck-accesslog', default=False), cfg.IntOpt('timeout', default=30, help='Workers silent", "app_kind, conf_dir): if \"--\" in sys.argv: args = sys.argv[sys.argv.index(\"--\") +", "common_config_file = os.path.join(conf_dir, \"etc/{}/common.conf\".format(app_env)) default_config_files = [common_config_file] app_config_file = os.path.join(conf_dir,", "or CONF.etc.secret_key # SQLALCHEMY_DATABASE_URI = CONF.DB.connection # SQLALCHEMY_TRACK_MODIFICATIONS = False", "'\"-\" means log to stderr.'), cfg.StrOpt('loglevel', default='info', help='The granularity of", "cfg.StrOpt('connection'), cfg.StrOpt('data'), ], 'DB') CONF.register_opts([ cfg.StrOpt('server'), cfg.StrOpt('port'), cfg.StrOpt('from_addr'), cfg.StrOpt('info_list'), cfg.StrOpt('alert_list'),", "cfg.StrOpt('run-mode', default=\"werkzeug\", choices=('gunicorn', 'werkzeug'), help=\"Run server use the specify mode.\"),", "CONF.register_opts([ cfg.StrOpt('connection'), cfg.StrOpt('data'), ], 'DB') CONF.register_opts([ cfg.StrOpt('server'), cfg.StrOpt('port'), cfg.StrOpt('from_addr'), cfg.StrOpt('info_list'),", "sys.argv[sys.argv.index(\"--\") + 1:] else: args = [] common_config_file = os.path.join(conf_dir,", "for handling requests'), cfg.BoolOpt('daemon', default=False, help='Daemonize the Gunicorn process'), cfg.StrOpt('accesslog',", "and restarted.'), cfg.StrOpt('worker-class', default='sync', help='The type of workers to use.',", "cfg.StrOpt('allow_ip'), cfg.StrOpt('secret_key'), cfg.StrOpt('env'), cfg.StrOpt('local_group'), cfg.StrOpt('acl_dir'), cfg.StrOpt('view_acl_group') ], 'etc') CONF.register_opts([ cfg.IntOpt('dnsupdater_port'),", "timedelta(days=1) # SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key # SQLALCHEMY_DATABASE_URI =", "], 'DB') CONF.register_opts([ cfg.StrOpt('server'), cfg.StrOpt('port'), cfg.StrOpt('from_addr'), cfg.StrOpt('info_list'), cfg.StrOpt('alert_list'), ], 'MAIL')", "help='The url prefix of this site.'), cfg.StrOpt('run-mode', default=\"werkzeug\", choices=('gunicorn', 'werkzeug'),", "cfg.StrOpt('view_zone') ], 'view') CONF.register_opts([ cfg.StrOpt('base-url', default='/', help='The url prefix of", "CONF = cfg.CONF CONF.register_opts([ cfg.StrOpt('log-dir'), cfg.StrOpt('log-file'), cfg.StrOpt('debug'), cfg.StrOpt('verbose'), ], 'log')", "help='The type of workers to use.', choices=('sync', 'eventlet', 'gevent', 'tornado'))", "else: args = [] common_config_file = os.path.join(conf_dir, \"etc/{}/common.conf\".format(app_env)) default_config_files =", "port to listen'), cfg.BoolOpt('debug', default=False), ], 'web') CONF.register_opts([ cfg.StrOpt('config', default=None,", "cfg.StrOpt('log-dir'), cfg.StrOpt('log-file'), cfg.StrOpt('debug'), cfg.StrOpt('verbose'), ], 'log') CONF.register_opts([ cfg.StrOpt('connection'), cfg.StrOpt('data'), ],", "import cfg CONF = cfg.CONF CONF.register_opts([ cfg.StrOpt('log-dir'), cfg.StrOpt('log-file'), cfg.StrOpt('debug'), cfg.StrOpt('verbose'),", "processes for handling requests'), cfg.BoolOpt('daemon', default=False, help='Daemonize the Gunicorn process'),", "from oslo.config import cfg CONF = cfg.CONF CONF.register_opts([ cfg.StrOpt('log-dir'), cfg.StrOpt('log-file'),", "\"--\" in sys.argv: args = sys.argv[sys.argv.index(\"--\") + 1:] else: args", "self.SQLALCHEMY_TRACK_MODIFICATIONS = False self.PERMANENT_SESSION_LIFETIME = timedelta(days=1) # SECRET_KEY = os.environ.get('SECRET_KEY')", "[] common_config_file = os.path.join(conf_dir, \"etc/{}/common.conf\".format(app_env)) default_config_files = [common_config_file] app_config_file =", "sys from datetime import timedelta from oslo.config import cfg CONF", "default='0.0.0.0', help='The IP address to bind'), cfg.IntOpt('port', default=8080, help='The port", "' 'killed and restarted.'), cfg.StrOpt('worker-class', default='sync', help='The type of workers", "address to bind'), cfg.IntOpt('port', default=8080, help='The port to listen'), cfg.BoolOpt('debug',", "for more than this many seconds are ' 'killed and", "= os.path.join(conf_dir, \"etc/{}/common.conf\".format(app_env)) default_config_files = [common_config_file] app_config_file = os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env,", "to a Gunicorn config file.'), cfg.StrOpt('bind', default='127.0.0.1:8888'), cfg.IntOpt('workers', default=0, help='The", "help='The number of worker processes for handling requests'), cfg.BoolOpt('daemon', default=False,", "'eventlet', 'gevent', 'tornado')) ], 'gunicorn') def setup_config(app_env, app_kind, conf_dir): if", "cfg.StrOpt('data'), ], 'DB') CONF.register_opts([ cfg.StrOpt('server'), cfg.StrOpt('port'), cfg.StrOpt('from_addr'), cfg.StrOpt('info_list'), cfg.StrOpt('alert_list'), ],", "'error', 'critical')), cfg.BoolOpt('ignore-healthcheck-accesslog', default=False), cfg.IntOpt('timeout', default=30, help='Workers silent for more", "config file.'), cfg.StrOpt('bind', default='127.0.0.1:8888'), cfg.IntOpt('workers', default=0, help='The number of worker", "default='sync', help='The type of workers to use.', choices=('sync', 'eventlet', 'gevent',", "specify mode.\"), cfg.StrOpt('bind', default='0.0.0.0', help='The IP address to bind'), cfg.IntOpt('port',", "if \"--\" in sys.argv: args = sys.argv[sys.argv.index(\"--\") + 1:] else:", "cfg.IntOpt('port', default=8080, help='The port to listen'), cfg.BoolOpt('debug', default=False), ], 'web')", "import os import sys from datetime import timedelta from oslo.config", "'log') CONF.register_opts([ cfg.StrOpt('connection'), cfg.StrOpt('data'), ], 'DB') CONF.register_opts([ cfg.StrOpt('server'), cfg.StrOpt('port'), cfg.StrOpt('from_addr'),", "default=None, help='The Access log file to write to.' '\"-\" means", "type of workers to use.', choices=('sync', 'eventlet', 'gevent', 'tornado')) ],", "], 'view') CONF.register_opts([ cfg.StrOpt('base-url', default='/', help='The url prefix of this", "CONF(default_config_files=default_config_files, args=args) class Config(object): def __init__(self, app_env, app_kind, conf_dir): #", "default=30, help='Workers silent for more than this many seconds are", "the specify mode.\"), cfg.StrOpt('bind', default='0.0.0.0', help='The IP address to bind'),", "CONF.register_opts([ cfg.StrOpt('acl_groups'), cfg.IntOpt('cname_ttl'), cfg.StrOpt('view_zone') ], 'view') CONF.register_opts([ cfg.StrOpt('base-url', default='/', help='The", "cfg.StrOpt('accesslog', default=None, help='The Access log file to write to.' '\"-\"", "of workers to use.', choices=('sync', 'eventlet', 'gevent', 'tornado')) ], 'gunicorn')", "def setup_config(app_env, app_kind, conf_dir): if \"--\" in sys.argv: args =", "means log to stderr.'), cfg.StrOpt('loglevel', default='info', help='The granularity of Error", "cfg.IntOpt('workers', default=0, help='The number of worker processes for handling requests'),", "help=\"Run server use the specify mode.\"), cfg.StrOpt('bind', default='0.0.0.0', help='The IP", "\"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) class Config(object): def __init__(self, app_env,", "os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) self.SECRET_KEY = os.environ.get('SECRET_KEY') or", "default='info', help='The granularity of Error log outputs.', choices=('debug', 'info', 'warning',", "'critical')), cfg.BoolOpt('ignore-healthcheck-accesslog', default=False), cfg.IntOpt('timeout', default=30, help='Workers silent for more than", "app_config_file = os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) self.SECRET_KEY =", "process'), cfg.StrOpt('accesslog', default=None, help='The Access log file to write to.'", "restarted.'), cfg.StrOpt('worker-class', default='sync', help='The type of workers to use.', choices=('sync',", "help='Daemonize the Gunicorn process'), cfg.StrOpt('accesslog', default=None, help='The Access log file", "= CONF.DB.connection # SQLALCHEMY_TRACK_MODIFICATIONS = False # PERMANENT_SESSION_LIFETIME = timedelta(days=1)", "], 'api') CONF.register_opts([ cfg.StrOpt('acl_groups'), cfg.IntOpt('cname_ttl'), cfg.StrOpt('view_zone') ], 'view') CONF.register_opts([ cfg.StrOpt('base-url',", "cfg.IntOpt('cname_ttl'), cfg.StrOpt('view_zone') ], 'view') CONF.register_opts([ cfg.StrOpt('base-url', default='/', help='The url prefix", "args=args) class Config(object): def __init__(self, app_env, app_kind, conf_dir): # print", "__init__(self, app_env, app_kind, conf_dir): # print 'conf_dir: ', conf_dir if", "listen'), cfg.BoolOpt('debug', default=False), ], 'web') CONF.register_opts([ cfg.StrOpt('config', default=None, help='The path", "default=None, help='The path to a Gunicorn config file.'), cfg.StrOpt('bind', default='127.0.0.1:8888'),", "'killed and restarted.'), cfg.StrOpt('worker-class', default='sync', help='The type of workers to", "log file to write to.' '\"-\" means log to stderr.'),", "to bind'), cfg.IntOpt('port', default=8080, help='The port to listen'), cfg.BoolOpt('debug', default=False),", "'web') CONF.register_opts([ cfg.StrOpt('config', default=None, help='The path to a Gunicorn config", "cfg.StrOpt('local_group'), cfg.StrOpt('acl_dir'), cfg.StrOpt('view_acl_group') ], 'etc') CONF.register_opts([ cfg.IntOpt('dnsupdater_port'), ], 'api') CONF.register_opts([", "this site.'), cfg.StrOpt('run-mode', default=\"werkzeug\", choices=('gunicorn', 'werkzeug'), help=\"Run server use the", "conf_dir): if \"--\" in sys.argv: args = sys.argv[sys.argv.index(\"--\") + 1:]", "help='The Access log file to write to.' '\"-\" means log", "help='The port to listen'), cfg.BoolOpt('debug', default=False), ], 'web') CONF.register_opts([ cfg.StrOpt('config',", "cfg.BoolOpt('ignore-healthcheck-accesslog', default=False), cfg.IntOpt('timeout', default=30, help='Workers silent for more than this", "os.path.join(conf_dir, \"etc/{}/{}.conf\".format(app_env, app_kind)) default_config_files.append(app_config_file) CONF(default_config_files=default_config_files, args=args) class Config(object): def __init__(self,", "this many seconds are ' 'killed and restarted.'), cfg.StrOpt('worker-class', default='sync',", "handling requests'), cfg.BoolOpt('daemon', default=False, help='Daemonize the Gunicorn process'), cfg.StrOpt('accesslog', default=None,", "'view') CONF.register_opts([ cfg.StrOpt('base-url', default='/', help='The url prefix of this site.')," ]
[ "self, config, bt_flag = 0, xbox_flag = 0, unix_flag =", "self.connectController() def drive(self): try: v,r = self.getDriveVals() if v,r !=", "= v,r except KeyboardInterrupt: self.cleanup() except Exception as e: print(e)", "drive(self): try: v,r = self.getDriveVals() if v,r != self.prev_cmd: self.sendCommands(v,r)", "!= self.prev_cmd: self.sendCommands(v,r) self.prev_cmd = v,r except KeyboardInterrupt: self.cleanup() except", "= unix_flag super(Rover,self).__init__(config) self.prev_cmd = [None,None] if bt_flag and xbox_flag:", "try: v,r = self.getDriveVals() if v,r != self.prev_cmd: self.sendCommands(v,r) self.prev_cmd", "as e: print(e) self.unix_flag = 0 def cleanup(self): self.killMotors() self.closeConnections()", "\"b\" elif xbox_flag: self.connection_type = \"x\" self.connectController() def drive(self): try:", "run with only one argument\") elif bt_flag: self.connection_type = \"b\"", "only one argument\") elif bt_flag: self.connection_type = \"b\" elif xbox_flag:", "= self.getDriveVals() if v,r != self.prev_cmd: self.sendCommands(v,r) self.prev_cmd = v,r", "bluetooth and Xbox, run with only one argument\") elif bt_flag:", "0, xbox_flag = 0, unix_flag = 0 ): self.bt_flag =", "0, unix_flag = 0 ): self.bt_flag = bt_flag self.xbox_flag =", "def __init__( self, config, bt_flag = 0, xbox_flag = 0,", "with both bluetooth and Xbox, run with only one argument\")", "self.sendCommands(v,r) self.prev_cmd = v,r except KeyboardInterrupt: self.cleanup() except Exception as", "self.unix_flag: try: self.sendUnixData() except Exception as e: print(e) self.unix_flag =", "from __future__ import print_function import time from rover import Robot", "self.connection_type = \"b\" elif xbox_flag: self.connection_type = \"x\" self.connectController() def", "print_function import time from rover import Robot from connections import", "= 0 ): self.bt_flag = bt_flag self.xbox_flag = xbox_flag self.unix_flag", "xbox_flag = 0, unix_flag = 0 ): self.bt_flag = bt_flag", "class Rover(Robot, Connections): def __init__( self, config, bt_flag = 0,", "and Xbox, run with only one argument\") elif bt_flag: self.connection_type", "self.xbox_flag = xbox_flag self.unix_flag = unix_flag super(Rover,self).__init__(config) self.prev_cmd = [None,None]", "def drive(self): try: v,r = self.getDriveVals() if v,r != self.prev_cmd:", "Exception( \"[Rover init] Cannot initialize with both bluetooth and Xbox,", "bt_flag self.xbox_flag = xbox_flag self.unix_flag = unix_flag super(Rover,self).__init__(config) self.prev_cmd =", "xbox_flag: raise Exception( \"[Rover init] Cannot initialize with both bluetooth", "import Connections class Rover(Robot, Connections): def __init__( self, config, bt_flag", "[None,None] if bt_flag and xbox_flag: raise Exception( \"[Rover init] Cannot", "= bt_flag self.xbox_flag = xbox_flag self.unix_flag = unix_flag super(Rover,self).__init__(config) self.prev_cmd", "self.prev_cmd = [None,None] if bt_flag and xbox_flag: raise Exception( \"[Rover", "Rover(Robot, Connections): def __init__( self, config, bt_flag = 0, xbox_flag", "e: print(e) self.cleanup() time.sleep(0.5) self.connectController() if self.unix_flag: try: self.sendUnixData() except", "self.connectController() if self.unix_flag: try: self.sendUnixData() except Exception as e: print(e)", "= [None,None] if bt_flag and xbox_flag: raise Exception( \"[Rover init]", "if self.unix_flag: try: self.sendUnixData() except Exception as e: print(e) self.unix_flag", "Robot from connections import Connections class Rover(Robot, Connections): def __init__(", "Connections class Rover(Robot, Connections): def __init__( self, config, bt_flag =", "both bluetooth and Xbox, run with only one argument\") elif", "argument\") elif bt_flag: self.connection_type = \"b\" elif xbox_flag: self.connection_type =", "= xbox_flag self.unix_flag = unix_flag super(Rover,self).__init__(config) self.prev_cmd = [None,None] if", "self.getDriveVals() if v,r != self.prev_cmd: self.sendCommands(v,r) self.prev_cmd = v,r except", "self.prev_cmd: self.sendCommands(v,r) self.prev_cmd = v,r except KeyboardInterrupt: self.cleanup() except Exception", "self.cleanup() time.sleep(0.5) self.connectController() if self.unix_flag: try: self.sendUnixData() except Exception as", "bt_flag: self.connection_type = \"b\" elif xbox_flag: self.connection_type = \"x\" self.connectController()", "v,r = self.getDriveVals() if v,r != self.prev_cmd: self.sendCommands(v,r) self.prev_cmd =", "self.prev_cmd = v,r except KeyboardInterrupt: self.cleanup() except Exception as e:", "KeyboardInterrupt: self.cleanup() except Exception as e: print(e) self.cleanup() time.sleep(0.5) self.connectController()", "init] Cannot initialize with both bluetooth and Xbox, run with", "Xbox, run with only one argument\") elif bt_flag: self.connection_type =", "__init__( self, config, bt_flag = 0, xbox_flag = 0, unix_flag", "with only one argument\") elif bt_flag: self.connection_type = \"b\" elif", "Exception as e: print(e) self.cleanup() time.sleep(0.5) self.connectController() if self.unix_flag: try:", "from rover import Robot from connections import Connections class Rover(Robot,", "elif bt_flag: self.connection_type = \"b\" elif xbox_flag: self.connection_type = \"x\"", "xbox_flag: self.connection_type = \"x\" self.connectController() def drive(self): try: v,r =", "print(e) self.cleanup() time.sleep(0.5) self.connectController() if self.unix_flag: try: self.sendUnixData() except Exception", "\"x\" self.connectController() def drive(self): try: v,r = self.getDriveVals() if v,r", "= 0, unix_flag = 0 ): self.bt_flag = bt_flag self.xbox_flag", "one argument\") elif bt_flag: self.connection_type = \"b\" elif xbox_flag: self.connection_type", "v,r except KeyboardInterrupt: self.cleanup() except Exception as e: print(e) self.cleanup()", "rover import Robot from connections import Connections class Rover(Robot, Connections):", "except Exception as e: print(e) self.unix_flag = 0 def cleanup(self):", "import time from rover import Robot from connections import Connections", "as e: print(e) self.cleanup() time.sleep(0.5) self.connectController() if self.unix_flag: try: self.sendUnixData()", "connections import Connections class Rover(Robot, Connections): def __init__( self, config,", "and xbox_flag: raise Exception( \"[Rover init] Cannot initialize with both", "): self.bt_flag = bt_flag self.xbox_flag = xbox_flag self.unix_flag = unix_flag", "bt_flag and xbox_flag: raise Exception( \"[Rover init] Cannot initialize with", "unix_flag = 0 ): self.bt_flag = bt_flag self.xbox_flag = xbox_flag", "\"[Rover init] Cannot initialize with both bluetooth and Xbox, run", "time from rover import Robot from connections import Connections class", "initialize with both bluetooth and Xbox, run with only one", "= \"x\" self.connectController() def drive(self): try: v,r = self.getDriveVals() if", "self.sendUnixData() except Exception as e: print(e) self.unix_flag = 0 def", "Connections): def __init__( self, config, bt_flag = 0, xbox_flag =", "__future__ import print_function import time from rover import Robot from", "elif xbox_flag: self.connection_type = \"x\" self.connectController() def drive(self): try: v,r", "super(Rover,self).__init__(config) self.prev_cmd = [None,None] if bt_flag and xbox_flag: raise Exception(", "if v,r != self.prev_cmd: self.sendCommands(v,r) self.prev_cmd = v,r except KeyboardInterrupt:", "config, bt_flag = 0, xbox_flag = 0, unix_flag = 0", "self.bt_flag = bt_flag self.xbox_flag = xbox_flag self.unix_flag = unix_flag super(Rover,self).__init__(config)", "try: self.sendUnixData() except Exception as e: print(e) self.unix_flag = 0", "self.unix_flag = unix_flag super(Rover,self).__init__(config) self.prev_cmd = [None,None] if bt_flag and", "raise Exception( \"[Rover init] Cannot initialize with both bluetooth and", "except Exception as e: print(e) self.cleanup() time.sleep(0.5) self.connectController() if self.unix_flag:", "bt_flag = 0, xbox_flag = 0, unix_flag = 0 ):", "Cannot initialize with both bluetooth and Xbox, run with only", "= 0, xbox_flag = 0, unix_flag = 0 ): self.bt_flag", "= \"b\" elif xbox_flag: self.connection_type = \"x\" self.connectController() def drive(self):", "if bt_flag and xbox_flag: raise Exception( \"[Rover init] Cannot initialize", "0 ): self.bt_flag = bt_flag self.xbox_flag = xbox_flag self.unix_flag =", "time.sleep(0.5) self.connectController() if self.unix_flag: try: self.sendUnixData() except Exception as e:", "import Robot from connections import Connections class Rover(Robot, Connections): def", "self.connection_type = \"x\" self.connectController() def drive(self): try: v,r = self.getDriveVals()", "self.cleanup() except Exception as e: print(e) self.cleanup() time.sleep(0.5) self.connectController() if", "except KeyboardInterrupt: self.cleanup() except Exception as e: print(e) self.cleanup() time.sleep(0.5)", "unix_flag super(Rover,self).__init__(config) self.prev_cmd = [None,None] if bt_flag and xbox_flag: raise", "import print_function import time from rover import Robot from connections", "from connections import Connections class Rover(Robot, Connections): def __init__( self,", "xbox_flag self.unix_flag = unix_flag super(Rover,self).__init__(config) self.prev_cmd = [None,None] if bt_flag", "v,r != self.prev_cmd: self.sendCommands(v,r) self.prev_cmd = v,r except KeyboardInterrupt: self.cleanup()", "Exception as e: print(e) self.unix_flag = 0 def cleanup(self): self.killMotors()" ]
[ "a document. # # However, this is a problem since", "Do NOT access the topics parameter after this is called.", "as they are turned in to proper <a href></a> links.", "to prettify them a bit. # try: from typogrify.templatetags.typogrify import", "the string as a topic name is the parent topic.", "when doing things like creating nascent topics. # self.topics_case =", "$Id: parser.py 1865 2008-10-28 00:47:27Z scanner $ # \"\"\" This", "(TOPIC_LIST.path_fn, TOPIC_LIST.image_fn), bodied_macros = { }, non_bodied_macros = { },", "class_fn, # wiki_links_path_func = TOPIC_LIST.path_fn, # macro_func = macro_fn, #", "######################################################################## # def clear_and_lock(self): \"\"\" Locks the mutex to prevent", "# time can add topics to a topic list. #", "Handles the macros we define for our version of markup.", "for macro with no body. - `block_type`: True for block", "a single string as its input. It will find all", "for images url's that are relative. Arguments: - `image_name`: The", "wiki links as they are turned in to proper <a", "the ## 'aswiki_topic_index' url. ## ## NOTE: This assumes that", "creole11_base from creoleparser.core import Parser from genshi import builder #", "\"\"\" Very plain init. We set up the attribute for", "The macro body if provided - `block_type`: True if this", "with a dot, then it is treated as the separator.", "a <ul> If the arg string ends with a dot,", "= builder.tag.ul() # For every topic that matches our pattern", "including any delimiters - `macro_body`: The macro body, None for", "all topics that start with the same prefix, separated by", "arg_string. Arguments: - `arg_string`: Expected to be the name of", "to the topic they are found in as appropriate. We", "urlparse try: import threading except ImportError: import dummy_threading as threading", "builder # We see if we have the 'typogrify' app", "== 'anchor': if block_type: return builder.tag.a(macro_body, name = arg_string) else:", "parsed. This is so we can preserve the case #", "proper subtopics of the given string, ordered by name. So", "We are passed in a topic name, and we return", "us know that list of topics by their topic names.", "we need to know what topics are referenced by a", "subtopic of 2007 and 2007.Agenda. This macro will insert in", "builder.tag.a(macro_body, href=arg_string) else: return builder.tag.a(arg_string, href=arg_string) return None ## ##", "of the attachments attached to the topic name given as", "string as a topic name is the parent topic. There", "u = urlparse(image_name) if self.current_topic and len(u.path) > 0 and", "attachments in a wiki document. if block_type: return builder.tag.a(macro_body, href=arg_string)", "instance will be shared across this process instance which may", "wiki_links_class_func = class_fn, wiki_links_path_func = (TOPIC_LIST.path_fn, TOPIC_LIST.image_fn), bodied_macros = {", "be reset between renders. # self.topics = [] # A", "the # 'extra_references' list in our global TOPIC_LIST object. This", "of topics by their topic names. \"\"\" ######################################################################## # def", "graphical attribute so that users can easily tell which topics", "The list of topics that we have encountered while rendering", "the css class name to add to wiki links as", "is called by our creole parser every time it encounters", "use our class function and a TopicList ## instance. The", "case # when doing things like creating nascent topics. #", "of an anchor macro output the proper genshi stream that", "# exist across multiple calls to render text via the", "I think) modifies # the topic list we have to", "by the markup dialect every time it encounters a wiki", "#################################################################### # def macro_fn(name, arg_string, macro_body, block_type, environ): \"\"\" Handles", "to a topic list. # self.lock = threading.Lock() return ########################################################################", "topics that are proper subtopics of the given string, ordered", "= [] return ######################################################################## # def unlock(self): \"\"\" Unlocks the", "this # topic. # u = urlparse(image_name) if self.current_topic and", "custom dialect. It will use our class function and a", "that the parser can know the URL base for all", "= arg_string if arg_string[-1] != '.': arg_string = arg_string +", "give images a different space # character. no_wiki_monospace = False,", "our creole parser every time it encounters a wiki link", "character. no_wiki_monospace = False, wiki_links_class_func = class_fn, wiki_links_path_func = (TOPIC_LIST.path_fn,", "the list # of topics referenced by the topic being", "import reverse from django.utils.translation import ugettext as _ # 3rd", "are turned in to proper <a href></a> links. We use", "mutex to prevent conflicts on updating the topic list if", "# dialect = creoleparser.dialects.Creole10( # wiki_links_base_url = reverse('aswiki_topic_index'), # wiki_links_space_char", "parser generated # from the dialect, which means our list", "[] self.topics_case = { } self.extra_references = [] return ########################################################################", "from a separate # URL wiki_links_space_char = '%20', # NOTE:", "################################################################## # def image_fn(self, image_name): \"\"\" This is called by", "macro body if provided - `block_type`: True if this is", "macros we define for our version of markup. Arguments: -", "django.utils.translation import ugettext as _ # 3rd party imports #", "if name == 'anchor': if block_type: return builder.tag.a(macro_body, name =", "path_fn(self, topic_name): \"\"\" This is called by our creole parser", "this topic, add a 'li' link # to that attachment.", "party imports # from creoleparser.dialects import create_dialect, creole10_base, creole11_base from", "we can tell what other topics a given topic refers", "list is generated. \"\"\" try: topic = Topic.objects.get(lc_name = arg_string.lower())", "for a specific Topic is the same as the url", "this # a two element # list for images #", "document. if block_type: return builder.tag.a(macro_body, href=arg_string) else: return builder.tag.a(arg_string, href=arg_string)", "= reverse('aswiki_topic_index'), # NOTE: Make this # a two element", "when we are done rendering we can find out what", "via # other methods like the <<subtopics >> macro. We", "attribute for tracking topics. \"\"\" # The current topic that", "attachment.get_absolute_url()))) return ul #################################################################### # def macro_fn(name, arg_string, macro_body, block_type,", "other threads # running.. if not this is a cheap", "referenced by the topic being rendered. for topic in topics:", "'mailto': return output_mailto(arg_string) elif name == 'gettext': if block_type: return", "and method instead 'path_fn' in to the 'path_func' parameter of", "methods of the Topic object we are # rendering this", "all topics for which the string as a topic name", "if more then one thread tries to render using the", "return image_name ######################################################################## # def path_fn(self, topic_name): \"\"\" This is", "\"\"\" Locks the mutex to prevent conflicts on updating the", "The name of the macro - `arg_string`: The argument string,", "URL for all wiki topics will be the same as", "elif name == 'gettext': if block_type: return _(macro_body) else: return", "# sure no other thread of execution (if there are", "urllib import quote from urlparse import urlparse try: import threading", "def image_fn(self, image_name): \"\"\" This is called by our creole", "class function and a TopicList ## instance. The root URL", "builder.tag.a(macro_body, name = arg_string) else: return builder.tag.a(name = arg_string) elif", "every # time we render a document. # # However,", "from creoleparser.core.Parser class's 'parse()' method. \"\"\" name = name.strip().lower() arg_string", "Loosely speaking all topics that start with the same prefix,", "of. \"\"\" arg_string = arg_string if arg_string[-1] != '.': arg_string", "input. It will find all topics for which the string", "The root URL for all wiki topics will be the", "this topic's references. # self.extra_references = [] # This is", "parser every time it encounters a wiki link in the", "a specific topic. We pass the objet and method instead", "instance. The root URL for all wiki topics will be", "links. We use this as a way to annotate topics", "- `macro_body`: The macro body, None for macro with no", "module is imported by the wiki.models module we need to", "arg_string.strip() if name == 'anchor': if block_type: return builder.tag.a(macro_body, name", "that module inside here so that we can access the", "know that list of topics by their topic names. \"\"\"", "the basic # working. return builder.tag.a(arg_string, href=\"mailto:%s\" % arg_string) ####################################################################", "time can add topics to a topic list. # self.lock", "This lets us track which topics this text refers to.", "# # However, this is a problem since for our", "class_fn(topic_name): \"\"\" This function is invoked by the markup dialect", "`name`: The name of the macro - `arg_string`: The argument", "reset between renders. # self.topics = [] # A dict", "will find all topics for which the string as a", "TopicList ## instance. The root URL for all wiki topics", "url's relative to this topic. # self.current_topic = None #", "name given as the arg_string. Arguments: - `arg_string`: Expected to", "For including downloadable attachments in a wiki document. if block_type:", "time we render a document. # # However, this is", "no other thread of execution (if there are other threads", "it is parsing. This lets us track which topics this", "the mutex. Do NOT access the topics parameter after this", "link. This lets us translate image names to be relative", "there are other threads # running.. if not this is", "= TopicList() # dialect = creoleparser.dialects.Creole10( # wiki_links_base_url = reverse('aswiki_topic_index'),", "list of topics will grow every # time we render", "topic name, and we return that topic name.. if we", "elif name == 'mailto': return output_mailto(arg_string) elif name == 'gettext':", "attachment. # for attachment in topic.file_attachments.all(): ul.append(builder.tag.li(builder.tag.a(attachment.basename(), href = attachment.get_absolute_url())))", "the topic names from rendering a single topic. So we", "lets us translate image names to be relative to the", "its input. It will find all topics for which the", "parser every time it hits an image link. This lets", "True for block type macros. - `environ` : The environment", "the attachments attached to the topic name given as the", "it is treated as the separator. ie: <<subtopics 2007.>> and", "matches our pattern we insert a 'li' link # to", "list of topics by their topic names. \"\"\" ######################################################################## #", "'typogrify' app installed. If we do we will # use", "proper <a href></a> links. We use this as a way", "u.path[0] != \"/\": return self.current_topic + \"/\" + image_name return", "Topic model. This is cheap since it will already be", "are identical. Arguments: - `arg_string`: The topic we want to", "lower_topic_name = topic_name.lower() # if this is a topic name", "parsing. This lets us track which topics this text refers", "a problem since for our current use we only want", "topics. # if lower_topic_name not in self.topics: self.topics.append(lower_topic_name) self.topics_case[lower_topic_name] =", "the 'typogrify' app installed. If we do we will #", "to know what topics are referenced by a specific topic", "can know to add those topics to the list #", "self.topics = [] # A dict mapping the lower case", "\"\"\" Unlocks the mutex. Do NOT access the topics parameter", ">> macro. We need this so # that when we", "is a bit of ugliness. Since we instantiate a TopicList", "threads # running.. if not this is a cheap operation..", "# However, this is a problem since for our current", "function is invoked by the markup dialect every time it", "is cheap since it will already be imported. Arguments: -", "# the topic names from rendering a single topic. So", "set up the attribute for tracking topics. \"\"\" # The", "return builder.tag.a(macro_body, href=arg_string) else: return builder.tag.a(arg_string, href=arg_string) return None ##", "on updating the topic list if more then one thread", "we have not seen yet, add it to our list", "topic in topics: TOPIC_LIST.extra_references.append(topic) ul.append(builder.tag.li(builder.tag.a(topic.name, href = topic.get_absolute_url()))) return ul", "It returns a string that is the css class name", "to not via [[wiki links]] but via # other methods", "as the arg_string. Arguments: - `arg_string`: Expected to be the", "arg_string = arg_string.strip() if name == 'anchor': if block_type: return", "to. \"\"\" # system imports # from urllib import quote", "= { }, non_bodied_macros = { }, macro_func = macro_fn,", "parser.py 1865 2008-10-28 00:47:27Z scanner $ # \"\"\" This is", "to the original case used # in the text being", "to render using the same dialect instance at the same", "return ul #################################################################### # def macro_fn(name, arg_string, macro_body, block_type, environ):", "= None # The list of topics that we have", "would happen. Arguments: - `topic_name`: The topic name being referenced", "a cache lookup of the topic name # and only", "exist, then no attachment list is generated. \"\"\" try: topic", "as its input. It will find all topics for which", "if arg_string[-1] != '.': arg_string = arg_string + \".\" topics", "that attachment. # for attachment in topic.file_attachments.all(): ul.append(builder.tag.li(builder.tag.a(attachment.basename(), href =", "is called by our creole parser every time it hits", "images a different space # character. no_wiki_monospace = False, wiki_links_class_func", "}, macro_func = macro_fn, # custom_markup = (), interwiki_links_base_urls =", "in a wiki document. if block_type: return builder.tag.a(macro_body, href=arg_string) else:", "This is a bit of ugliness. Since we instantiate a", "a mutex so only one thread at a # time", "doing some sort of transformation on topic names this is", "will already be imported. Arguments: - `topic_name`: the topic name", "called by our creole parser every time it hits an", "= [] # This is a bit of ugliness. Since", "# Model imports # from aswiki.models import Topic ############################################################################ ############################################################################", "you are seeing. \"\"\" self.lock.release() return ################################################################## # def image_fn(self,", "except Topic.DoesNotExist: return None ul = builder.tag.ul() # For every", "is where it would happen. Arguments: - `topic_name`: The topic", "all wiki topics will be the same as the ##", "are proper subtopics of the given string, ordered by name.", "means our list of topics will grow every # time", "to support the fancy format.. but for now just get", "same dialect instance at the same time. \"\"\" self.lock.acquire() self.topics", "# system imports # from urllib import quote from urlparse", "[] # This is a bit of ugliness. Since we", "arg_string + \".\" topics = Topic.objects.filter(lc_name__istartswith = arg_string.lower()).order_by('lc_name') if topics.count()", "00:47:27Z scanner $ # \"\"\" This is where the logic", "for rendering our templates to prettify them a bit. #", "of topics that we have encountered while rendering # some", "imported. Arguments: - `topic_name`: the topic name being checked for", "used # in the text being parsed. This is so", "to make # sure no other thread of execution (if", "text via the parser generated # from the dialect, which", "# NOTE: make this a two element list to #", "may well # exist across multiple calls to render text", "2007.Agenda.foo is a subtopic of 2007 and 2007.Agenda. This macro", "is the same as the url ## for the aswiki_topic_index", "{ } self.extra_references = [] return ######################################################################## # def unlock(self):", "provided - `block_type`: True if this is a block macro.", "which may well # exist across multiple calls to render", "'gettext': if block_type: return _(macro_body) else: return _(arg_string) elif name", "macro. - `macro_body`: The macro body if provided - `block_type`:", "topics.count() == 0: return None ul = builder.tag.ul() # For", "every topic that matches our pattern we insert a 'li'", "is treated as the separator. ie: <<subtopics 2007.>> and <<subtopics", "css class name to add to wiki links as they", "= arg_string) else: return builder.tag.a(name = arg_string) elif name ==", "return None ## ## Create our custom dialect. It will", "the dialect, which means our list of topics will grow", "We see if we have the 'typogrify' app installed. If", "our creole dialect we are goign to generate. The point", "macro output the proper genshi stream that will render a", "markup parser lives. We use the Python Creoleparser (which requires", "of topics. # if lower_topic_name not in self.topics: self.topics.append(lower_topic_name) self.topics_case[lower_topic_name]", "= topic_name return topic_name ############################################################################ # def class_fn(topic_name): \"\"\" This", "calls to render text via the parser generated # from", "in the text being parsed. This is so we can", "topic.get_absolute_url()))) return ul #################################################################### # def output_attachments(arg_string): \"\"\" Returns a", "be relative to the topic they are found in as", "typogrify.templatetags.typogrify import typogrify except ImportError: def typogrify(text): return text #", "a given topic refers to. \"\"\" # system imports #", "for all wiki topics will be the same as the", "whose list of topics you are seeing. \"\"\" self.lock.release() return", "tell what other topics a given topic refers to. \"\"\"", "# from aswiki.models import Topic ############################################################################ ############################################################################ # class TopicList(object):", "If no such topic exist, then no attachment list is", "# from a separate # URL wiki_links_space_char = '%20', #", "= Topic.objects.filter(lc_name__istartswith = arg_string.lower()).order_by('lc_name') if topics.count() == 0: return None", "# self.lock = threading.Lock() return ######################################################################## # def clear_and_lock(self): \"\"\"", "Parser from genshi import builder # We see if we", "output. We also add this topic to the # 'extra_references'", "= macro_fn, # custom_markup = (), interwiki_links_base_urls = { 'wikicreole'", "\"\"\" self.lock.release() return ################################################################## # def image_fn(self, image_name): \"\"\" This", "the same dialect instance at the same time. \"\"\" self.lock.acquire()", "of a Creole _dialect_ this one # instance will be", "# for attachment in topic.file_attachments.all(): ul.append(builder.tag.li(builder.tag.a(attachment.basename(), href = attachment.get_absolute_url()))) return", "return builder.tag.a(name = arg_string) elif name == 'mailto': return output_mailto(arg_string)", "The topic we want to find all subtopics of. \"\"\"", "across multiple calls to render text via the parser generated", "elif name == 'attachlist': return output_attachments(arg_string) elif name == 'attachment':", "like the <<subtopics >> macro. We need this so #", "reverse('aswiki_topic_index'), # NOTE: Make this # a two element #", "self.lock = threading.Lock() return ######################################################################## # def clear_and_lock(self): \"\"\" Locks", "name being referenced as a wiki link. \"\"\" lower_topic_name =", "the lower case topic name to the original case used", "object we are # rendering this output for can know", "# macro_func = macro_fn, # interwiki_links_base_urls=dict(wikicreole='http://wikicreole.org/wiki/', # wikipedia='http://wikipedia.org/wiki/',) # )", "and pass # a method when we create an instance", "<ul> of all of the attachments attached to the topic", "# use it for rendering our templates to prettify them", "app installed. If we do we will # use it", "ends with a dot, then it is treated as the", "If the image url is NOT absolute, root it relative", "goign to generate. The point of this class is that", "anchor macro output the proper genshi stream that will render", "are other threads # running.. if not this is a", "which the string as a topic name is the parent", "want to find all subtopics of. \"\"\" arg_string = arg_string", "this topic to the # 'extra_references' list in our global", "# def output_mailto(arg_string): \"\"\" Given the arguments of an anchor", "of the topics that are referenced by the raw content", "<<subtopics 2007.>> and <<subtopics 2007>> are identical. Arguments: - `arg_string`:", "topics by their topic names. \"\"\" ######################################################################## # def __init__(self):", "{ }, non_bodied_macros = { }, macro_func = macro_fn, #", "environ): \"\"\" Handles the macros we define for our version", "and some additional goop so that we can tell what", "a wiki link. \"\"\" lower_topic_name = topic_name.lower() # if this", "add it to our list # of topics. # if", "root it relative to this # topic. # u =", "being parsed. This is so we can preserve the case", "imported by the wiki.models module we need to import that", "(if there are other threads # running.. if not this", "\"\"\" # system imports # from urllib import quote from", "which means our list of topics will grow every #", "now just get the basic # working. return builder.tag.a(arg_string, href=\"mailto:%s\"", "from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _", "string ends with a dot, then it is treated as", "well # exist across multiple calls to render text via", "not in self.topics: self.topics.append(lower_topic_name) self.topics_case[lower_topic_name] = topic_name return topic_name ############################################################################", "bit. # try: from typogrify.templatetags.typogrify import typogrify except ImportError: def", "use we only want # the topic names from rendering", "############################################################################ ############################################################################ # class TopicList(object): \"\"\" A helper class we", "specific Topic is the same as the url ## for", "this lookup. NOTE: Since this module is imported by the", "add to wiki links as they are turned in to", "topic. If no such topic exist, then no attachment list", "to import that module inside here so that we can", "done rendering we can find out what other topics #", "image_name ######################################################################## # def path_fn(self, topic_name): \"\"\" This is called", "the macro - `arg_string`: The argument string, including any delimiters", "= macro_fn, # interwiki_links_base_urls=dict(wikicreole='http://wikicreole.org/wiki/', # wikipedia='http://wikipedia.org/wiki/',) # ) parser =", "that we have encountered while rendering # some content. This", "the '.' character. This forms a kind of hierarchy. Loosely", "relative to this # topic. # u = urlparse(image_name) if", "ugliness. Since we instantiate a TopicList and pass # a", "the mutex to prevent conflicts on updating the topic list", "# If the image url is NOT absolute, root it", "return output_mailto(arg_string) elif name == 'gettext': if block_type: return _(macro_body)", "class TopicList(object): \"\"\" A helper class we use to keep", "the topic name # and only if that fails fall", "<word> AT <foo> DOT <foo>' Arguments: - `arg_string`: The argument", "topic. There is some semantic magic in a topic if", "## for the aswiki_topic_index with the Topic name appended to", "name to the original case used # in the text", "return text # Model imports # from aswiki.models import Topic", "a custom dialect so that the parser can know the", "aswiki.models import Topic ############################################################################ ############################################################################ # class TopicList(object): \"\"\" A", "# running.. if not this is a cheap operation.. XXX", "we are # rendering this output for can know to", "referenced. \"\"\" # If the image url is NOT absolute,", "imports # from django.core.urlresolvers import reverse from django.utils.translation import ugettext", "references. # self.extra_references = [] # This is a bit", "The current topic that is being rendered, if we know", "Arguments: - `arg_string`: The argument string of the anchor macro.", "\"\"\" This is where the logic and definition of our", "\"\"\" A helper class we use to keep track of", "render text via the parser generated # from the dialect,", "def macro_fn(name, arg_string, macro_body, block_type, environ): \"\"\" Handles the macros", "access the topics parameter after this is called. You can", "typogrify(text): return text # Model imports # from aswiki.models import", "# list for images # to be loaded # from", "the arg_string. Arguments: - `arg_string`: Expected to be the name", "the anchor macro. - `macro_body`: The macro body if provided", "need this so # that when we are done rendering", "def clear_and_lock(self): \"\"\" Locks the mutex to prevent conflicts on", "like creating nascent topics. # self.topics_case = { } #", "XXX Need to support the fancy format.. but for now", "every time it encounters a wiki topic. It returns a", "list of topics you are seeing. \"\"\" self.lock.release() return ##################################################################", "# def output_subtopics(arg_string): \"\"\" This will take a single string", "generated. \"\"\" try: topic = Topic.objects.get(lc_name = arg_string.lower()) except Topic.DoesNotExist:", "# def image_fn(self, image_name): \"\"\" This is called by our", "# to be loaded # from a separate # URL", "module inside here so that we can access the Topic", "other topics # we should list in this topic's references.", "magic transformation for images url's that are relative. Arguments: -", "above example if I were to say <<subtopics 2007>> it", "after this is called. You can not be guaranteed whose", "a cheap operation.. XXX I think) modifies # the topic", "topic_name return topic_name ############################################################################ # def class_fn(topic_name): \"\"\" This function", "# NOTE: Make this # a two element # list", "href></a> links. We use this as a way to annotate", "have the 'typogrify' app installed. If we do we will", "macro_fn, # interwiki_links_base_urls=dict(wikicreole='http://wikicreole.org/wiki/', # wikipedia='http://wikipedia.org/wiki/',) # ) parser = Parser(dialect", "Topic.objects.css_class_name(topic_name) #################################################################### # def output_mailto(arg_string): \"\"\" Given the arguments of", "from creoleparser.dialects import create_dialect, creole10_base, creole11_base from creoleparser.core import Parser", "Given the arguments of an anchor macro output the proper", "if we have the 'typogrify' app installed. If we do", "topics # we should list in this topic's references. #", "also need to support the magic argument string format of", "return that topic name.. if we were doing some sort", "use the wiki.models.TopicManager's css_class_name method to do this lookup. NOTE:", "our class function and a TopicList ## instance. The root", "we can find out what other topics # we should", "NOT absolute, root it relative to this # topic. #", "we have to make # sure no other thread of", "Unlocks the mutex. Do NOT access the topics parameter after", "URL wiki_links_space_char = '%20', # NOTE: make this a two", "unlock(self): \"\"\" Unlocks the mutex. Do NOT access the topics", "image_fn(self, image_name): \"\"\" This is called by our creole parser", "our output. We also add this topic to the #", "import that module inside here so that we can access", "We use the Python Creoleparser (which requires Genshi) We make", "name. So in the above example if I were to", "output_attachments(arg_string): \"\"\" Returns a <ul> of all of the attachments", "topic name is the parent topic. There is some semantic", "names this is where it would happen. Arguments: - `topic_name`:", "if block_type: return builder.tag.a(macro_body, href=arg_string) else: return builder.tag.a(arg_string, href=arg_string) return", "rendering this output for can know to add those topics", "the URL base for all of the topics (pages) in", "to the output <ul> of the topics that are proper", "= '%20', # use_additions = True, # no_wiki_monospace = False,", "the url ## for the aswiki_topic_index with the Topic name", "wiki.models.TopicManager's css_class_name method to do this lookup. NOTE: Since this", "same as the ## 'aswiki_topic_index' url. ## ## NOTE: This", "ugettext as _ # 3rd party imports # from creoleparser.dialects", "were doing some sort of transformation on topic names this", "links as they are turned in to proper <a href></a>", "cheap operation.. XXX I think) modifies # the topic list", "block macro. \"\"\" # XXX Need to support the fancy", "the topic name being checked for existence. \"\"\" # XXX", "# def unlock(self): \"\"\" Unlocks the mutex. Do NOT access", "being rendered. for topic in topics: TOPIC_LIST.extra_references.append(topic) ul.append(builder.tag.li(builder.tag.a(topic.name, href =", "topic's references. # self.extra_references = [] # This is a", "def output_attachments(arg_string): \"\"\" Returns a <ul> of all of the", "topic list we have to provide a mutex so only", "# URL wiki_links_space_char = '%20', # NOTE: make this a", "render a document. # # However, this is a problem", "we will # use it for rendering our templates to", "output_attachments(arg_string) elif name == 'attachment': # For including downloadable attachments", "output_subtopics(arg_string): \"\"\" This will take a single string as its", "builder.tag.ul() # For every file attachment on this topic, add", "#################################################################### # def output_subtopics(arg_string): \"\"\" This will take a single", "as the separator. ie: <<subtopics 2007.>> and <<subtopics 2007>> are", "topic that matches our pattern we insert a 'li' link", "It will find all topics for which the string as", "thread of execution (if there are other threads # running..", "## ## NOTE: This assumes that the url for a", "genshi import builder # We see if we have the", "our global TOPIC_LIST object. This is # so that the", "a # time can add topics to a topic list.", "as _ # 3rd party imports # from creoleparser.dialects import", "text it is parsing. This lets us track which topics", "rendering our templates to prettify them a bit. # try:", "topic to the # 'extra_references' list in our global TOPIC_LIST", "pattern we insert a 'li' link # to that topic", "= TOPIC_LIST.path_fn, # macro_func = macro_fn, # interwiki_links_base_urls=dict(wikicreole='http://wikicreole.org/wiki/', # wikipedia='http://wikipedia.org/wiki/',)", "links]] but via # other methods like the <<subtopics >>", "that topic in our output. We also add this topic", "We make a custom dialect so that the parser can", "in to proper <a href></a> links. We use this as", "inside here so that we can access the Topic model.", "is being rendered, if we know it. This # lets", "referenced as a wiki link. \"\"\" lower_topic_name = topic_name.lower() #", "goop so that we can tell what other topics a", "pass # a method when we create an instance of", "a string that is the css class name to add", "list in this topic's references. # self.extra_references = [] #", "we are goign to generate. The point of this class", "that the url for a specific Topic is the same", "we use to keep track of all of the topics", "so that users can easily tell which topics are not", "but for now just get the basic # working. return", "macro_func = macro_fn, # interwiki_links_base_urls=dict(wikicreole='http://wikicreole.org/wiki/', # wikipedia='http://wikipedia.org/wiki/',) # ) parser", "markup. Arguments: - `name`: The name of the macro -", "builder.tag.a(arg_string, href=arg_string) return None ## ## Create our custom dialect.", "by our creole parser every time it hits an image", "instead 'path_fn' in to the 'path_func' parameter of our creole", "is generated. \"\"\" try: topic = Topic.objects.get(lc_name = arg_string.lower()) except", "image url's relative to this topic. # self.current_topic = None", "fancy format.. but for now just get the basic #", "self.current_topic and len(u.path) > 0 and u.path[0] != \"/\": return", "rendering a single topic. So we have to make #", "time it hits an image link. This lets us translate", "\"/\": return self.current_topic + \"/\" + image_name return image_name ########################################################################", "then it is treated as the separator. ie: <<subtopics 2007.>>", "that are referenced by the raw content for a specific", "topic.file_attachments.all(): ul.append(builder.tag.li(builder.tag.a(attachment.basename(), href = attachment.get_absolute_url()))) return ul #################################################################### # def", "of '<you> AT <word> AT <foo> DOT <foo>' Arguments: -", "use to keep track of all of the topics that", "topics. \"\"\" # The current topic that is being rendered,", "name is the parent topic. There is some semantic magic", "## TOPIC_LIST = TopicList() # dialect = creoleparser.dialects.Creole10( # wiki_links_base_url", "a different space # character. no_wiki_monospace = False, wiki_links_class_func =", "of our wiki markup parser lives. We use the Python", "topic referring to not via [[wiki links]] but via #", "rendering we can find out what other topics # we", "just get the basic # working. return builder.tag.a(arg_string, href=\"mailto:%s\" %", "self.topics_case[lower_topic_name] = topic_name return topic_name ############################################################################ # def class_fn(topic_name): \"\"\"", "try: from typogrify.templatetags.typogrify import typogrify except ImportError: def typogrify(text): return", "name we have not seen yet, add it to our", "if self.current_topic and len(u.path) > 0 and u.path[0] != \"/\":", "of the topic name # and only if that fails", "this so # that when we are done rendering we", "between renders. # self.topics = [] # A dict mapping", "The macro body, None for macro with no body. -", "every time it encounters a wiki link in the text", "NOTE: Since this module is imported by the wiki.models module", "class we use to keep track of all of the", "the markup dialect every time it encounters a wiki topic.", "`topic_name`: the topic name being checked for existence. \"\"\" #", "ie: the '.' character. This forms a kind of hierarchy.", "# give images a different space # character. no_wiki_monospace =", "and \"2007.Agenda.foo\" in a <ul> If the arg string ends", "our custom dialect. It will use our class function and", "of transformation on topic names this is where it would", "The argument string, including any delimiters - `macro_body`: The macro", "'%20', # use_additions = True, # no_wiki_monospace = False, #", "the same prefix, separated by '.' are sub-topics. So: 2007.Agenda", "via the parser generated # from the dialect, which means", "to # Topic.objects.css_class_name(topic_name) # return Topic.objects.css_class_name(topic_name) #################################################################### # def output_mailto(arg_string):", "this as a way to annotate topics that do not", "AT <foo> DOT <foo>' Arguments: - `arg_string`: The argument string", "the text being parsed. This is so we can preserve", "topic we want to find all subtopics of. \"\"\" arg_string", "ul #################################################################### # def macro_fn(name, arg_string, macro_body, block_type, environ): \"\"\"", "This is where the logic and definition of our wiki", "are found in as appropriate. We only apply this magic", "############################################################################ # class TopicList(object): \"\"\" A helper class we use", "self.topics: self.topics.append(lower_topic_name) self.topics_case[lower_topic_name] = topic_name return topic_name ############################################################################ # def", "#################################################################### # def output_attachments(arg_string): \"\"\" Returns a <ul> of all", "a wiki topic. It returns a string that is the", "our templates to prettify them a bit. # try: from", "two element list to # give images a different space", "back to # Topic.objects.css_class_name(topic_name) # return Topic.objects.css_class_name(topic_name) #################################################################### # def", "topic name.. if we were doing some sort of transformation", "encountered while rendering # some content. This should be reset", "topic list if more then one thread tries to render", "example if I were to say <<subtopics 2007>> it would", "import dummy_threading as threading # Django imports # from django.core.urlresolvers", "a topic name is the parent topic. There is some", "\"\"\" # XXX This is where we should do a", "= create_dialect(\\ creole11_base, wiki_links_base_url = reverse('aswiki_topic_index'), # NOTE: Make this", "block_type, environ): \"\"\" Handles the macros we define for our", "File: $Id: parser.py 1865 2008-10-28 00:47:27Z scanner $ # \"\"\"", "!= \"/\": return self.current_topic + \"/\" + image_name return image_name", "This macro will insert in to the output <ul> of", "TOPIC_LIST = TopicList() # dialect = creoleparser.dialects.Creole10( # wiki_links_base_url =", "which topics are not yet created. We use the wiki.models.TopicManager's", "some additional goop so that we can tell what other", "that we can access the Topic model. This is cheap", "= False, wiki_links_class_func = class_fn, wiki_links_path_func = (TOPIC_LIST.path_fn, TOPIC_LIST.image_fn), bodied_macros", "scanner $ # \"\"\" This is where the logic and", "character. This forms a kind of hierarchy. Loosely speaking all", "# def __init__(self): \"\"\" Very plain init. We set up", "the wiki and some additional goop so that we can", "model. This is cheap since it will already be imported.", "# to that attachment. # for attachment in topic.file_attachments.all(): ul.append(builder.tag.li(builder.tag.a(attachment.basename(),", "= [] self.topics_case = { } self.extra_references = [] return", "basic # working. return builder.tag.a(arg_string, href=\"mailto:%s\" % arg_string) #################################################################### #", "False, # wiki_links_class_func = class_fn, # wiki_links_path_func = TOPIC_LIST.path_fn, #", "0 and u.path[0] != \"/\": return self.current_topic + \"/\" +", "'anchor': if block_type: return builder.tag.a(macro_body, name = arg_string) else: return", "TopicList and pass # a method when we create an", "to annotate topics that do not exist yet with some", "self.extra_references = [] return ######################################################################## # def unlock(self): \"\"\" Unlocks", "name == 'attachlist': return output_attachments(arg_string) elif name == 'attachment': #", "wiki document. if block_type: return builder.tag.a(macro_body, href=arg_string) else: return builder.tag.a(arg_string,", "we return that topic name.. if we were doing some", "topic names from rendering a single topic. So we have", "find all subtopics of. \"\"\" arg_string = arg_string if arg_string[-1]", "element # list for images # to be loaded #", "contains periods, ie: the '.' character. This forms a kind", "pass the objet and method instead 'path_fn' in to the", "that when we are done rendering we can find out", "macro will insert in to the output <ul> of the", "body. - `block_type`: True for block type macros. - `environ`", "by their topic names. \"\"\" ######################################################################## # def __init__(self): \"\"\"", "such topic exist, then no attachment list is generated. \"\"\"", "a two element list to # give images a different", "for all of the topics (pages) in the wiki and", "wiki_links_base_url = reverse('aswiki_topic_index'), # NOTE: Make this # a two", "threading.Lock() return ######################################################################## # def clear_and_lock(self): \"\"\" Locks the mutex", "our version of markup. Arguments: - `name`: The name of", "grow every # time we render a document. # #", "}, non_bodied_macros = { }, macro_func = macro_fn, # custom_markup", "`macro_body`: The macro body, None for macro with no body.", "system imports # from urllib import quote from urlparse import", "is created or modified. This lets us know that list", "function and a TopicList ## instance. The root URL for", "nascent topics. # self.topics_case = { } # This is", "in to the 'path_func' parameter of our creole dialect we", "exist across multiple calls to render text via the parser", "this output for can know to add those topics to", "wiki_links_space_char = '%20', # use_additions = True, # no_wiki_monospace =", "list. It contains Topic's that we have # found this", "same as the url ## for the aswiki_topic_index with the", "\"\"\" This will take a single string as its input.", "keep track of all of the topics that are referenced", "2007.Agenda is a sub-topic of 2007. 2007.Agenda.foo is a subtopic", "`environ` : The environment object, passed through from creoleparser.core.Parser class's", "is so we can preserve the case # when doing", "hits an image link. This lets us translate image names", "time it encounters a wiki topic. It returns a string", "import Parser from genshi import builder # We see if", "prerender../save() methods of the Topic object we are # rendering", "name to add to wiki links as they are turned", "we have encountered while rendering # some content. This should", "being checked for existence. \"\"\" # XXX This is where", "block_type: return builder.tag.a(macro_body, href=arg_string) else: return builder.tag.a(arg_string, href=arg_string) return None", "modified. This lets us know that list of topics by", "# 'extra_references' list in our global TOPIC_LIST object. This is", "Topic ############################################################################ ############################################################################ # class TopicList(object): \"\"\" A helper class", "what topics are referenced by a specific topic when its", "## Create our custom dialect. It will use our class", "# This is another list. It contains Topic's that we", "'path_fn' in to the 'path_func' parameter of our creole dialect", "len(u.path) > 0 and u.path[0] != \"/\": return self.current_topic +", "'li' link # to that attachment. # for attachment in", "mutex. Do NOT access the topics parameter after this is", "lets us track which topics this text refers to. We", "lets us root image url's relative to this topic. #", "no_wiki_monospace = False, # wiki_links_class_func = class_fn, # wiki_links_path_func =", "the output <ul> of the topics that are proper subtopics", "to prevent conflicts on updating the topic list if more", "url for a specific Topic is the same as the", "what other topics a given topic refers to. \"\"\" #", "aswiki_topic_index with the Topic name appended to it ## TOPIC_LIST", "# lets us root image url's relative to this topic.", "the raw content for a specific topic. We pass the", "\"\"\" arg_string = arg_string if arg_string[-1] != '.': arg_string =", "to add to wiki links as they are turned in", "url is NOT absolute, root it relative to this #", "`block_type`: True for block type macros. - `environ` : The", "the 'path_func' parameter of our creole dialect we are goign", "every file attachment on this topic, add a 'li' link", "a specific Topic is the same as the url ##", "do this lookup. NOTE: Since this module is imported by", "being referenced as a wiki link. \"\"\" lower_topic_name = topic_name.lower()", "working. return builder.tag.a(arg_string, href=\"mailto:%s\" % arg_string) #################################################################### # def output_subtopics(arg_string):", "macro body, None for macro with no body. - `block_type`:", "root image url's relative to this topic. # self.current_topic =", "is invoked by the markup dialect every time it encounters", "that are relative. Arguments: - `image_name`: The name of the", "# A dict mapping the lower case topic name to", "macro. \"\"\" # XXX Need to support the fancy format..", "'<you> AT <word> AT <foo> DOT <foo>' Arguments: - `arg_string`:", "separate # URL wiki_links_space_char = '%20', # NOTE: make this", "is a subtopic of 2007 and 2007.Agenda. This macro will", "self.topics_case = { } # This is another list. It", "'li' link # to that topic in our output. We", "== 'gettext': if block_type: return _(macro_body) else: return _(arg_string) elif", "use_additions = True, # no_wiki_monospace = False, # wiki_links_class_func =", "_(macro_body) else: return _(arg_string) elif name == 'subtopics': return output_subtopics(arg_string)", "delimiters - `macro_body`: The macro body, None for macro with", "execution (if there are other threads # running.. if not", "they are turned in to proper <a href></a> links. We", "guaranteed whose list of topics you are seeing. \"\"\" self.lock.release()", "urlparse import urlparse try: import threading except ImportError: import dummy_threading", "to be loaded # from a separate # URL wiki_links_space_char", "This is cheap since it will already be imported. Arguments:", "from genshi import builder # We see if we have", "so # that when we are done rendering we can", "need to import that module inside here so that we", "It contains Topic's that we have # found this topic", "yet, add it to our list # of topics. #", "0: return None ul = builder.tag.ul() # For every topic", "ul = builder.tag.ul() # For every file attachment on this", "our current use we only want # the topic names", "== 0: return None ul = builder.tag.ul() # For every", "be shared across this process instance which may well #", "Very plain init. We set up the attribute for tracking", "forms a kind of hierarchy. Loosely speaking all topics that", "`arg_string`: The topic we want to find all subtopics of.", "a wiki document. if block_type: return builder.tag.a(macro_body, href=arg_string) else: return", "to this # topic. # u = urlparse(image_name) if self.current_topic", "'.' are sub-topics. So: 2007.Agenda is a sub-topic of 2007.", "are # rendering this output for can know to add", "[[wiki links]] but via # other methods like the <<subtopics", "the objet and method instead 'path_fn' in to the 'path_func'", "topic name # and only if that fails fall back", "try: topic = Topic.objects.get(lc_name = arg_string.lower()) except Topic.DoesNotExist: return None", "do we will # use it for rendering our templates", "the topic being rendered. for topic in topics: TOPIC_LIST.extra_references.append(topic) ul.append(builder.tag.li(builder.tag.a(topic.name,", "arg_string.lower()).order_by('lc_name') if topics.count() == 0: return None ul = builder.tag.ul()", "True, # no_wiki_monospace = False, # wiki_links_class_func = class_fn, #", "wiki_links_path_func = (TOPIC_LIST.path_fn, TOPIC_LIST.image_fn), bodied_macros = { }, non_bodied_macros =", "list of topics that we have encountered while rendering #", "Model imports # from aswiki.models import Topic ############################################################################ ############################################################################ #", "= arg_string) elif name == 'mailto': return output_mailto(arg_string) elif name", "the topics (pages) in the wiki and some additional goop", "know to add those topics to the list # of", "dialect = creoleparser.dialects.Creole10( # wiki_links_base_url = reverse('aswiki_topic_index'), # wiki_links_space_char =", "# other methods like the <<subtopics >> macro. We need", "transformation on topic names this is where it would happen.", "'subtopics': return output_subtopics(arg_string) elif name == 'attachlist': return output_attachments(arg_string) elif", "clear_and_lock(self): \"\"\" Locks the mutex to prevent conflicts on updating", "macro_fn(name, arg_string, macro_body, block_type, environ): \"\"\" Handles the macros we", "This will take a single string as its input. It", "name = arg_string) else: return builder.tag.a(name = arg_string) elif name", "of topics will grow every # time we render a", "speaking all topics that start with the same prefix, separated", "of all of the topics that are referenced by the", "macros. - `environ` : The environment object, passed through from", "# For every topic that matches our pattern we insert", "see if we have the 'typogrify' app installed. If we", "as appropriate. We only apply this magic transformation for images", "The point of this class is that we need to", "thread at a # time can add topics to a", "= topic.get_absolute_url()))) return ul #################################################################### # def output_attachments(arg_string): \"\"\" Returns", "import quote from urlparse import urlparse try: import threading except", "name of the macro - `arg_string`: The argument string, including", "parser lives. We use the Python Creoleparser (which requires Genshi)", "of this class is that we need to know what", "for the aswiki_topic_index with the Topic name appended to it", "# that when we are done rendering we can find", "us track which topics this text refers to. We are", "are done rendering we can find out what other topics", "not this is a cheap operation.. XXX I think) modifies", "return output_subtopics(arg_string) elif name == 'attachlist': return output_attachments(arg_string) elif name", "only want # the topic names from rendering a single", "encounters a wiki topic. It returns a string that is", "# found this topic referring to not via [[wiki links]]", "seeing. \"\"\" self.lock.release() return ################################################################## # def image_fn(self, image_name): \"\"\"", "any delimiters - `macro_body`: The macro body, None for macro", "## 'aswiki_topic_index' url. ## ## NOTE: This assumes that the", "one thread at a # time can add topics to", "= threading.Lock() return ######################################################################## # def clear_and_lock(self): \"\"\" Locks the", "if we were doing some sort of transformation on topic", "magic argument string format of '<you> AT <word> AT <foo>", "plain init. We set up the attribute for tracking topics.", "we only want # the topic names from rendering a", "\"\"\" This is called by our creole parser every time", "# the topic list we have to provide a mutex", "import create_dialect, creole10_base, creole11_base from creoleparser.core import Parser from genshi", "get the basic # working. return builder.tag.a(arg_string, href=\"mailto:%s\" % arg_string)", "lookup. NOTE: Since this module is imported by the wiki.models", "css_class_name method to do this lookup. NOTE: Since this module", "where it would happen. Arguments: - `topic_name`: The topic name", "Need to support the fancy format.. but for now just", "# time we render a document. # # However, this", "You can not be guaranteed whose list of topics you", "that list of topics by their topic names. \"\"\" ########################################################################", "if this is a topic name we have not seen", "arg_string = arg_string + \".\" topics = Topic.objects.filter(lc_name__istartswith = arg_string.lower()).order_by('lc_name')", "# try: from typogrify.templatetags.typogrify import typogrify except ImportError: def typogrify(text):", "typogrify except ImportError: def typogrify(text): return text # Model imports", "our list # of topics. # if lower_topic_name not in", "We use this as a way to annotate topics that", "some graphical attribute so that users can easily tell which", "this is called. You can not be guaranteed whose list", "attached to the topic name given as the arg_string. Arguments:", "render using the same dialect instance at the same time.", "attachment in topic.file_attachments.all(): ul.append(builder.tag.li(builder.tag.a(attachment.basename(), href = attachment.get_absolute_url()))) return ul ####################################################################", "\"2007.Agenda\" and \"2007.Agenda.foo\" in a <ul> If the arg string", "and we return that topic name.. if we were doing", "a separate # URL wiki_links_space_char = '%20', # NOTE: make", "if that fails fall back to # Topic.objects.css_class_name(topic_name) # return", "images # to be loaded # from a separate #", "add topics to a topic list. # self.lock = threading.Lock()", "from aswiki.models import Topic ############################################################################ ############################################################################ # class TopicList(object): \"\"\"", "say <<subtopics 2007>> it would give me \"2007.Agenda\" and \"2007.Agenda.foo\"", "at the same time. \"\"\" self.lock.acquire() self.topics = [] self.topics_case", "dummy_threading as threading # Django imports # from django.core.urlresolvers import", "through from creoleparser.core.Parser class's 'parse()' method. \"\"\" name = name.strip().lower()", "users can easily tell which topics are not yet created.", "- `environ` : The environment object, passed through from creoleparser.core.Parser", "the parser generated # from the dialect, which means our", "Arguments: - `topic_name`: The topic name being referenced as a", "lower_topic_name not in self.topics: self.topics.append(lower_topic_name) self.topics_case[lower_topic_name] = topic_name return topic_name", "only if that fails fall back to # Topic.objects.css_class_name(topic_name) #", "dialect every time it encounters a wiki topic. It returns", "have to make # sure no other thread of execution", "of the topics that are proper subtopics of the given", "- `macro_body`: The macro body if provided - `block_type`: True", "if this is a block macro. \"\"\" # XXX Need", "can know the URL base for all of the topics", "are not yet created. We use the wiki.models.TopicManager's css_class_name method", "threading except ImportError: import dummy_threading as threading # Django imports", "a mailto link. We also need to support the magic", "macro_body, block_type, environ): \"\"\" Handles the macros we define for", "not be guaranteed whose list of topics you are seeing.", "except ImportError: def typogrify(text): return text # Model imports #", "string as its input. It will find all topics for", "case used # in the text being parsed. This is", "url. ## ## NOTE: This assumes that the url for", "from urllib import quote from urlparse import urlparse try: import", "rendered. for topic in topics: TOPIC_LIST.extra_references.append(topic) ul.append(builder.tag.li(builder.tag.a(topic.name, href = topic.get_absolute_url())))", "only apply this magic transformation for images url's that are", "as the ## 'aswiki_topic_index' url. ## ## NOTE: This assumes", "topic names this is where it would happen. Arguments: -", "{ } # This is another list. It contains Topic's", "add a 'li' link # to that attachment. # for", "would give me \"2007.Agenda\" and \"2007.Agenda.foo\" in a <ul> If", "self.topics = [] self.topics_case = { } self.extra_references = []", "support the fancy format.. but for now just get the", "This is called by our creole parser every time it", "We also add this topic to the # 'extra_references' list", "builder.tag.a(name = arg_string) elif name == 'mailto': return output_mailto(arg_string) elif", "in this topic's references. # self.extra_references = [] # This", "fall back to # Topic.objects.css_class_name(topic_name) # return Topic.objects.css_class_name(topic_name) #################################################################### #", "NOTE: This assumes that the url for a specific Topic", "wiki link in the text it is parsing. This lets", "for images # to be loaded # from a separate", "some semantic magic in a topic if it contains periods,", "`arg_string`: The argument string, including any delimiters - `macro_body`: The", "this module is imported by the wiki.models module we need", "this topic. # self.current_topic = None # The list of", "mutex so only one thread at a # time can", "\"\"\" This function is invoked by the markup dialect every", "if not this is a cheap operation.. XXX I think)", "prefix, separated by '.' are sub-topics. So: 2007.Agenda is a", "elif name == 'attachment': # For including downloadable attachments in", "current topic that is being rendered, if we know it.", "not yet created. We use the wiki.models.TopicManager's css_class_name method to", "hierarchy. Loosely speaking all topics that start with the same", "# wiki_links_path_func = TOPIC_LIST.path_fn, # macro_func = macro_fn, # interwiki_links_base_urls=dict(wikicreole='http://wikicreole.org/wiki/',", "as the url ## for the aswiki_topic_index with the Topic", "and u.path[0] != \"/\": return self.current_topic + \"/\" + image_name", "list # of topics. # if lower_topic_name not in self.topics:", "make a custom dialect so that the parser can know", "objet and method instead 'path_fn' in to the 'path_func' parameter", "create_dialect(\\ creole11_base, wiki_links_base_url = reverse('aswiki_topic_index'), # NOTE: Make this #", "are sub-topics. So: 2007.Agenda is a sub-topic of 2007. 2007.Agenda.foo", "attachment on this topic, add a 'li' link # to", "loaded # from a separate # URL wiki_links_space_char = '%20',", "of the topics (pages) in the wiki and some additional", "are seeing. \"\"\" self.lock.release() return ################################################################## # def image_fn(self, image_name):", "in the wiki and some additional goop so that we", "an image link. This lets us translate image names to", "the <<subtopics >> macro. We need this so # that", "topic_name): \"\"\" This is called by our creole parser every", "\"\"\" self.lock.acquire() self.topics = [] self.topics_case = { } self.extra_references", "= arg_string.strip() if name == 'anchor': if block_type: return builder.tag.a(macro_body,", "content. This should be reset between renders. # self.topics =", "string, ordered by name. So in the above example if", "to do this lookup. NOTE: Since this module is imported", "separator. ie: <<subtopics 2007.>> and <<subtopics 2007>> are identical. Arguments:", "'aswiki_topic_index' url. ## ## NOTE: This assumes that the url", "topic, add a 'li' link # to that attachment. #", "annotate topics that do not exist yet with some graphical", "interwiki_links_base_urls = { 'wikicreole' : 'http://wikicreole.org/wiki/', 'wikipedia' :'http://wikipedia.org/wiki/' } ))", "appended to it ## TOPIC_LIST = TopicList() # dialect =", "We set up the attribute for tracking topics. \"\"\" #", "seen yet, add it to our list # of topics.", "def typogrify(text): return text # Model imports # from aswiki.models", "attachments attached to the topic name given as the arg_string.", "`macro_body`: The macro body if provided - `block_type`: True if", "module we need to import that module inside here so", "topics that start with the same prefix, separated by '.'", "for our current use we only want # the topic", "# We see if we have the 'typogrify' app installed.", "it contains periods, ie: the '.' character. This forms a", "support the magic argument string format of '<you> AT <word>", "TopicList(object): \"\"\" A helper class we use to keep track", "content is created or modified. This lets us know that", "in the text it is parsing. This lets us track", "block_type: return builder.tag.a(macro_body, name = arg_string) else: return builder.tag.a(name =", "# from creoleparser.dialects import create_dialect, creole10_base, creole11_base from creoleparser.core import", "another list. It contains Topic's that we have # found", "This is where we should do a cache lookup of", "specific topic when its content is created or modified. This", "= class_fn, wiki_links_path_func = (TOPIC_LIST.path_fn, TOPIC_LIST.image_fn), bodied_macros = { },", "$ # \"\"\" This is where the logic and definition", "other methods like the <<subtopics >> macro. We need this", "ul = builder.tag.ul() # For every topic that matches our", "is a cheap operation.. XXX I think) modifies # the", "2007>> it would give me \"2007.Agenda\" and \"2007.Agenda.foo\" in a", "reverse from django.utils.translation import ugettext as _ # 3rd party", "of topics referenced by the topic being rendered. for topic", "for now just get the basic # working. return builder.tag.a(arg_string,", "# def macro_fn(name, arg_string, macro_body, block_type, environ): \"\"\" Handles the", "Parser(dialect = create_dialect(\\ creole11_base, wiki_links_base_url = reverse('aswiki_topic_index'), # NOTE: Make", "encounters a wiki link in the text it is parsing.", "for attachment in topic.file_attachments.all(): ul.append(builder.tag.li(builder.tag.a(attachment.basename(), href = attachment.get_absolute_url()))) return ul", "a dot, then it is treated as the separator. ie:", "name.strip().lower() arg_string = arg_string.strip() if name == 'anchor': if block_type:", "__init__(self): \"\"\" Very plain init. We set up the attribute", "Topic name appended to it ## TOPIC_LIST = TopicList() #", "This lets us know that list of topics by their", "not exist yet with some graphical attribute so that users", "stream that will render a mailto link. We also need", "a topic name we have not seen yet, add it", "where we should do a cache lookup of the topic", "it for rendering our templates to prettify them a bit.", "a wiki link in the text it is parsing. This", "Topic.objects.filter(lc_name__istartswith = arg_string.lower()).order_by('lc_name') if topics.count() == 0: return None ul", "import urlparse try: import threading except ImportError: import dummy_threading as", "to be relative to the topic they are found in", "will use our class function and a TopicList ## instance.", "Topic object we are # rendering this output for can", "by a specific topic when its content is created or", "import builder # We see if we have the 'typogrify'", "to that topic in our output. We also add this", "already be imported. Arguments: - `topic_name`: the topic name being", "topics that do not exist yet with some graphical attribute", "= { } self.extra_references = [] return ######################################################################## # def", "in self.topics: self.topics.append(lower_topic_name) self.topics_case[lower_topic_name] = topic_name return topic_name ############################################################################ #", "define for our version of markup. Arguments: - `name`: The", "name = name.strip().lower() arg_string = arg_string.strip() if name == 'anchor':", "wiki topics will be the same as the ## 'aswiki_topic_index'", "we should do a cache lookup of the topic name", "and a TopicList ## instance. The root URL for all", "a two element # list for images # to be", "= builder.tag.ul() # For every file attachment on this topic,", "mapping the lower case topic name to the original case", "import threading except ImportError: import dummy_threading as threading # Django", "name being checked for existence. \"\"\" # XXX This is", "assumes that the url for a specific Topic is the", "relative to the topic they are found in as appropriate.", "the wiki.models module we need to import that module inside", "of all of the attachments attached to the topic name", "the topic list if more then one thread tries to", "So in the above example if I were to say", "for existence. \"\"\" # XXX This is where we should", "= Parser(dialect = create_dialect(\\ creole11_base, wiki_links_base_url = reverse('aswiki_topic_index'), # NOTE:", "= arg_string.lower()).order_by('lc_name') if topics.count() == 0: return None ul =", "translate image names to be relative to the topic they", "and only if that fails fall back to # Topic.objects.css_class_name(topic_name)", "The argument string of the anchor macro. - `macro_body`: The", "## instance. The root URL for all wiki topics will", "are goign to generate. The point of this class is", "image_name return image_name ######################################################################## # def path_fn(self, topic_name): \"\"\" This", "not seen yet, add it to our list # of", "is NOT absolute, root it relative to this # topic.", "TOPIC_LIST.image_fn), bodied_macros = { }, non_bodied_macros = { }, macro_func", "# a two element # list for images # to", "passed in a topic name, and we return that topic", "2007.>> and <<subtopics 2007>> are identical. Arguments: - `arg_string`: The", "document. # # However, this is a problem since for", "topic names. \"\"\" ######################################################################## # def __init__(self): \"\"\" Very plain", "all of the topics (pages) in the wiki and some", "topic refers to. \"\"\" # system imports # from urllib", "one thread tries to render using the same dialect instance", "our pattern we insert a 'li' link # to that", "the attribute for tracking topics. \"\"\" # The current topic", "'%20', # NOTE: make this a two element list to", "track of all of the topics that are referenced by", "the parser can know the URL base for all of", "a sub-topic of 2007. 2007.Agenda.foo is a subtopic of 2007", "else: return _(arg_string) elif name == 'subtopics': return output_subtopics(arg_string) elif", "topic_name ############################################################################ # def class_fn(topic_name): \"\"\" This function is invoked", "list # of topics referenced by the topic being rendered.", "topic. It returns a string that is the css class", "specific topic. We pass the objet and method instead 'path_fn'", "can access the Topic model. This is cheap since it", "the same time. \"\"\" self.lock.acquire() self.topics = [] self.topics_case =", "list. # self.lock = threading.Lock() return ######################################################################## # def clear_and_lock(self):", "have to provide a mutex so only one thread at", "that fails fall back to # Topic.objects.css_class_name(topic_name) # return Topic.objects.css_class_name(topic_name)", "given topic refers to. \"\"\" # system imports # from", "those topics to the list # of topics referenced by", "know what topics are referenced by a specific topic when", "None for macro with no body. - `block_type`: True for", "are referenced by the raw content for a specific topic.", "topic that is being rendered, if we know it. This", "a subtopic of 2007 and 2007.Agenda. This macro will insert", "environment object, passed through from creoleparser.core.Parser class's 'parse()' method. \"\"\"", "this a two element list to # give images a", "`topic_name`: The topic name being referenced as a wiki link.", "\"\"\" name = name.strip().lower() arg_string = arg_string.strip() if name ==", "# This is a bit of ugliness. Since we instantiate", "images url's that are relative. Arguments: - `image_name`: The name", "# For including downloadable attachments in a wiki document. if", "if we know it. This # lets us root image", "## ## Create our custom dialect. It will use our", "have not seen yet, add it to our list #", "from urlparse import urlparse try: import threading except ImportError: import", "from django.utils.translation import ugettext as _ # 3rd party imports", "we want to find all subtopics of. \"\"\" arg_string =", "and len(u.path) > 0 and u.path[0] != \"/\": return self.current_topic", "yet with some graphical attribute so that users can easily", "creole dialect we are goign to generate. The point of", "############################################################################ # def class_fn(topic_name): \"\"\" This function is invoked by", "ie: <<subtopics 2007.>> and <<subtopics 2007>> are identical. Arguments: -", "# self.extra_references = [] # This is a bit of", "sure no other thread of execution (if there are other", "that the prerender../save() methods of the Topic object we are", "We also need to support the magic argument string format", "######################################################################## # def unlock(self): \"\"\" Unlocks the mutex. Do NOT", "return builder.tag.a(arg_string, href=arg_string) return None ## ## Create our custom", "# no_wiki_monospace = False, # wiki_links_class_func = class_fn, # wiki_links_path_func", "in our global TOPIC_LIST object. This is # so that", "# # File: $Id: parser.py 1865 2008-10-28 00:47:27Z scanner $", "- `block_type`: True if this is a block macro. \"\"\"", "different space # character. no_wiki_monospace = False, wiki_links_class_func = class_fn,", "created. We use the wiki.models.TopicManager's css_class_name method to do this", "For every file attachment on this topic, add a 'li'", "the topic list we have to provide a mutex so", "There is some semantic magic in a topic if it", "that we have # found this topic referring to not", "easily tell which topics are not yet created. We use", "class is that we need to know what topics are", "topic name to the original case used # in the", "this is a cheap operation.. XXX I think) modifies #", "in a topic name, and we return that topic name..", "# of topics. # if lower_topic_name not in self.topics: self.topics.append(lower_topic_name)", "#################################################################### # def output_mailto(arg_string): \"\"\" Given the arguments of an", "case topic name to the original case used # in", "wiki_links_class_func = class_fn, # wiki_links_path_func = TOPIC_LIST.path_fn, # macro_func =", "thread tries to render using the same dialect instance at", "topics are not yet created. We use the wiki.models.TopicManager's css_class_name", "referring to not via [[wiki links]] but via # other", "a bit. # try: from typogrify.templatetags.typogrify import typogrify except ImportError:", "if topics.count() == 0: return None ul = builder.tag.ul() #", "Locks the mutex to prevent conflicts on updating the topic", "else: return builder.tag.a(name = arg_string) elif name == 'mailto': return", "raw content for a specific topic. We pass the objet", "apply this magic transformation for images url's that are relative.", "# self.topics_case = { } # This is another list.", "attachment list is generated. \"\"\" try: topic = Topic.objects.get(lc_name =", "topics will be the same as the ## 'aswiki_topic_index' url.", "where the logic and definition of our wiki markup parser", "This is # so that the prerender../save() methods of the", "should be reset between renders. # self.topics = [] #", "exist yet with some graphical attribute so that users can", "that do not exist yet with some graphical attribute so", "to keep track of all of the topics that are", "contains Topic's that we have # found this topic referring", "since it will already be imported. Arguments: - `topic_name`: the", "for block type macros. - `environ` : The environment object,", "it will already be imported. Arguments: - `topic_name`: the topic", "# XXX This is where we should do a cache", "except ImportError: import dummy_threading as threading # Django imports #", "version of markup. Arguments: - `name`: The name of the", "relative to this topic. # self.current_topic = None # The", "sub-topics. So: 2007.Agenda is a sub-topic of 2007. 2007.Agenda.foo is", "parser = Parser(dialect = create_dialect(\\ creole11_base, wiki_links_base_url = reverse('aswiki_topic_index'), #", "dialect instance at the same time. \"\"\" self.lock.acquire() self.topics =", "the text it is parsing. This lets us track which", "its content is created or modified. This lets us know", "problem since for our current use we only want #", "know the URL base for all of the topics (pages)", "# class TopicList(object): \"\"\" A helper class we use to", "TopicList() # dialect = creoleparser.dialects.Creole10( # wiki_links_base_url = reverse('aswiki_topic_index'), #", "# to that topic in our output. We also add", "so that the parser can know the URL base for", "lets us know that list of topics by their topic", "will be the same as the ## 'aswiki_topic_index' url. ##", "downloadable attachments in a wiki document. if block_type: return builder.tag.a(macro_body,", "to generate. The point of this class is that we", "# Django imports # from django.core.urlresolvers import reverse from django.utils.translation", "parser can know the URL base for all of the", "Expected to be the name of a topic. If no", "format of '<you> AT <word> AT <foo> DOT <foo>' Arguments:", "% arg_string) #################################################################### # def output_subtopics(arg_string): \"\"\" This will take", "for tracking topics. \"\"\" # The current topic that is", "block type macros. - `environ` : The environment object, passed", "requires Genshi) We make a custom dialect so that the", "None # The list of topics that we have encountered", "our creole parser every time it hits an image link.", "is called. You can not be guaranteed whose list of", "called. You can not be guaranteed whose list of topics", "topic name we have not seen yet, add it to", "# XXX Need to support the fancy format.. but for", "it would give me \"2007.Agenda\" and \"2007.Agenda.foo\" in a <ul>", "a <ul> of all of the attachments attached to the", "<<subtopics 2007>> are identical. Arguments: - `arg_string`: The topic we", "helper class we use to keep track of all of", "= { } # This is another list. It contains", "in to the output <ul> of the topics that are", "of topics you are seeing. \"\"\" self.lock.release() return ################################################################## #", "this is a topic name we have not seen yet,", "wikipedia='http://wikipedia.org/wiki/',) # ) parser = Parser(dialect = create_dialect(\\ creole11_base, wiki_links_base_url", "insert in to the output <ul> of the topics that", "with the Topic name appended to it ## TOPIC_LIST =", "# from the dialect, which means our list of topics", "single string as its input. It will find all topics", "start with the same prefix, separated by '.' are sub-topics.", "with no body. - `block_type`: True for block type macros.", "It will use our class function and a TopicList ##", "# def path_fn(self, topic_name): \"\"\" This is called by our", "the name of a topic. If no such topic exist,", "macro. We need this so # that when we are", "as threading # Django imports # from django.core.urlresolvers import reverse", "list to # give images a different space # character.", "= creoleparser.dialects.Creole10( # wiki_links_base_url = reverse('aswiki_topic_index'), # wiki_links_space_char = '%20',", "ordered by name. So in the above example if I", "link. \"\"\" lower_topic_name = topic_name.lower() # if this is a", "the topics parameter after this is called. You can not", "\"/\" + image_name return image_name ######################################################################## # def path_fn(self, topic_name):", "# \"\"\" This is where the logic and definition of", "method. \"\"\" name = name.strip().lower() arg_string = arg_string.strip() if name", "# if this is a topic name we have not", "The name of the image being referenced. \"\"\" # If", "is another list. It contains Topic's that we have #", "file attachment on this topic, add a 'li' link #", "\"\"\" ######################################################################## # def __init__(self): \"\"\" Very plain init. We", "topic in our output. We also add this topic to", "is where we should do a cache lookup of the", "link # to that attachment. # for attachment in topic.file_attachments.all():", "existence. \"\"\" # XXX This is where we should do", "the prerender../save() methods of the Topic object we are #", "+ \"/\" + image_name return image_name ######################################################################## # def path_fn(self,", "arg_string) elif name == 'mailto': return output_mailto(arg_string) elif name ==", "method when we create an instance of a Creole _dialect_", "up the attribute for tracking topics. \"\"\" # The current", "to find all subtopics of. \"\"\" arg_string = arg_string if", "# ) parser = Parser(dialect = create_dialect(\\ creole11_base, wiki_links_base_url =", "string format of '<you> AT <word> AT <foo> DOT <foo>'", "by '.' are sub-topics. So: 2007.Agenda is a sub-topic of", "relative. Arguments: - `image_name`: The name of the image being", "can find out what other topics # we should list", "TOPIC_LIST object. This is # so that the prerender../save() methods", "from creoleparser.core import Parser from genshi import builder # We", "topics that we have encountered while rendering # some content.", "- `topic_name`: The topic name being referenced as a wiki", "wiki markup parser lives. We use the Python Creoleparser (which", "topic being rendered. for topic in topics: TOPIC_LIST.extra_references.append(topic) ul.append(builder.tag.li(builder.tag.a(topic.name, href", "will insert in to the output <ul> of the topics", "href=arg_string) else: return builder.tag.a(arg_string, href=arg_string) return None ## ## Create", "This lets us translate image names to be relative to", "macro - `arg_string`: The argument string, including any delimiters -", "a topic if it contains periods, ie: the '.' character.", "This function is invoked by the markup dialect every time", "if provided - `block_type`: True if this is a block", "insert a 'li' link # to that topic in our", "definition of our wiki markup parser lives. We use the", "given string, ordered by name. So in the above example", "the given string, ordered by name. So in the above", "we were doing some sort of transformation on topic names", "topics: TOPIC_LIST.extra_references.append(topic) ul.append(builder.tag.li(builder.tag.a(topic.name, href = topic.get_absolute_url()))) return ul #################################################################### #", "`arg_string`: The argument string of the anchor macro. - `macro_body`:", "instance of a Creole _dialect_ this one # instance will", "of 2007 and 2007.Agenda. This macro will insert in to", "use this as a way to annotate topics that do", "\"\"\" Given the arguments of an anchor macro output the", "url's that are relative. Arguments: - `image_name`: The name of", "We need this so # that when we are done", "of the Topic object we are # rendering this output", "This assumes that the url for a specific Topic is", "reverse('aswiki_topic_index'), # wiki_links_space_char = '%20', # use_additions = True, #", "is some semantic magic in a topic if it contains", "The environment object, passed through from creoleparser.core.Parser class's 'parse()' method.", "We use the wiki.models.TopicManager's css_class_name method to do this lookup.", "topic when its content is created or modified. This lets", "url ## for the aswiki_topic_index with the Topic name appended", "then one thread tries to render using the same dialect", "that we can tell what other topics a given topic", "is imported by the wiki.models module we need to import", "in our output. We also add this topic to the", "we instantiate a TopicList and pass # a method when", "current use we only want # the topic names from", "However, this is a problem since for our current use", "one # instance will be shared across this process instance", "quote from urlparse import urlparse try: import threading except ImportError:", "self.topics.append(lower_topic_name) self.topics_case[lower_topic_name] = topic_name return topic_name ############################################################################ # def class_fn(topic_name):", "sort of transformation on topic names this is where it", "NOT access the topics parameter after this is called. You", "[] # A dict mapping the lower case topic name", "Topic's that we have # found this topic referring to", "We pass the objet and method instead 'path_fn' in to", "using the same dialect instance at the same time. \"\"\"", "name == 'gettext': if block_type: return _(macro_body) else: return _(arg_string)", "the proper genshi stream that will render a mailto link.", "'.' character. This forms a kind of hierarchy. Loosely speaking", "else: return builder.tag.a(arg_string, href=arg_string) return None ## ## Create our", "Django imports # from django.core.urlresolvers import reverse from django.utils.translation import", "self.lock.release() return ################################################################## # def image_fn(self, image_name): \"\"\" This is", "return builder.tag.a(arg_string, href=\"mailto:%s\" % arg_string) #################################################################### # def output_subtopics(arg_string): \"\"\"", "# wiki_links_space_char = '%20', # use_additions = True, # no_wiki_monospace", "it. This # lets us root image url's relative to", "referenced by a specific topic when its content is created", "in the above example if I were to say <<subtopics", "Arguments: - `arg_string`: The topic we want to find all", "will be shared across this process instance which may well", "wiki topic. It returns a string that is the css", "{ }, macro_func = macro_fn, # custom_markup = (), interwiki_links_base_urls", "= [] # A dict mapping the lower case topic", "ul #################################################################### # def output_attachments(arg_string): \"\"\" Returns a <ul> of", "self.lock.acquire() self.topics = [] self.topics_case = { } self.extra_references =", "block_type: return _(macro_body) else: return _(arg_string) elif name == 'subtopics':", "TOPIC_LIST.path_fn, # macro_func = macro_fn, # interwiki_links_base_urls=dict(wikicreole='http://wikicreole.org/wiki/', # wikipedia='http://wikipedia.org/wiki/',) #", "instance at the same time. \"\"\" self.lock.acquire() self.topics = []", "the url for a specific Topic is the same as", "and definition of our wiki markup parser lives. We use", "Topic.objects.css_class_name(topic_name) # return Topic.objects.css_class_name(topic_name) #################################################################### # def output_mailto(arg_string): \"\"\" Given", "prevent conflicts on updating the topic list if more then", "no such topic exist, then no attachment list is generated.", "So we have to make # sure no other thread", "a topic name, and we return that topic name.. if", "to it ## TOPIC_LIST = TopicList() # dialect = creoleparser.dialects.Creole10(", "then no attachment list is generated. \"\"\" try: topic =", "a block macro. \"\"\" # XXX Need to support the", "a topic list. # self.lock = threading.Lock() return ######################################################################## #", "imports # from aswiki.models import Topic ############################################################################ ############################################################################ # class", "to the topic name given as the arg_string. Arguments: -", "are relative. Arguments: - `image_name`: The name of the image", "this is a problem since for our current use we", "ImportError: import dummy_threading as threading # Django imports # from", "sub-topic of 2007. 2007.Agenda.foo is a subtopic of 2007 and", "return Topic.objects.css_class_name(topic_name) #################################################################### # def output_mailto(arg_string): \"\"\" Given the arguments", "the wiki.models.TopicManager's css_class_name method to do this lookup. NOTE: Since", "will take a single string as its input. It will", "ul.append(builder.tag.li(builder.tag.a(attachment.basename(), href = attachment.get_absolute_url()))) return ul #################################################################### # def macro_fn(name,", "this text refers to. We are passed in a topic", "give me \"2007.Agenda\" and \"2007.Agenda.foo\" in a <ul> If the", "being rendered, if we know it. This # lets us", "the original case used # in the text being parsed.", "# File: $Id: parser.py 1865 2008-10-28 00:47:27Z scanner $ #", "list we have to provide a mutex so only one", "topics this text refers to. We are passed in a", "= (TOPIC_LIST.path_fn, TOPIC_LIST.image_fn), bodied_macros = { }, non_bodied_macros = {", "# self.topics = [] # A dict mapping the lower", "# The current topic that is being rendered, if we", "# wikipedia='http://wikipedia.org/wiki/',) # ) parser = Parser(dialect = create_dialect(\\ creole11_base,", "'extra_references' list in our global TOPIC_LIST object. This is #", "Python Creoleparser (which requires Genshi) We make a custom dialect", "`arg_string`: Expected to be the name of a topic. If", "} self.extra_references = [] return ######################################################################## # def unlock(self): \"\"\"", "do not exist yet with some graphical attribute so that", "non_bodied_macros = { }, macro_func = macro_fn, # custom_markup =", "# some content. This should be reset between renders. #", "body if provided - `block_type`: True if this is a", "can preserve the case # when doing things like creating", "creoleparser.core import Parser from genshi import builder # We see", "_ # 3rd party imports # from creoleparser.dialects import create_dialect,", "2008-10-28 00:47:27Z scanner $ # \"\"\" This is where the", "argument string of the anchor macro. - `macro_body`: The macro", "we should list in this topic's references. # self.extra_references =", "self.topics_case = { } self.extra_references = [] return ######################################################################## #", "all subtopics of. \"\"\" arg_string = arg_string if arg_string[-1] !=", "their topic names. \"\"\" ######################################################################## # def __init__(self): \"\"\" Very", "of ugliness. Since we instantiate a TopicList and pass #", "Genshi) We make a custom dialect so that the parser", "topics will grow every # time we render a document.", "+ \".\" topics = Topic.objects.filter(lc_name__istartswith = arg_string.lower()).order_by('lc_name') if topics.count() ==", "conflicts on updating the topic list if more then one", "global TOPIC_LIST object. This is # so that the prerender../save()", "if block_type: return builder.tag.a(macro_body, name = arg_string) else: return builder.tag.a(name", "at a # time can add topics to a topic", "refers to. We are passed in a topic name, and", "wiki.models module we need to import that module inside here", "# from urllib import quote from urlparse import urlparse try:", "text being parsed. This is so we can preserve the", "None ## ## Create our custom dialect. It will use", "= arg_string + \".\" topics = Topic.objects.filter(lc_name__istartswith = arg_string.lower()).order_by('lc_name') if", "ImportError: def typogrify(text): return text # Model imports # from", "by the raw content for a specific topic. We pass", "= False, # wiki_links_class_func = class_fn, # wiki_links_path_func = TOPIC_LIST.path_fn,", "out what other topics # we should list in this", "= class_fn, # wiki_links_path_func = TOPIC_LIST.path_fn, # macro_func = macro_fn,", "# return Topic.objects.css_class_name(topic_name) #################################################################### # def output_mailto(arg_string): \"\"\" Given the", "returns a string that is the css class name to", "subtopics of. \"\"\" arg_string = arg_string if arg_string[-1] != '.':", "of hierarchy. Loosely speaking all topics that start with the", "return builder.tag.a(macro_body, name = arg_string) else: return builder.tag.a(name = arg_string)", "name, and we return that topic name.. if we were", "to that attachment. # for attachment in topic.file_attachments.all(): ul.append(builder.tag.li(builder.tag.a(attachment.basename(), href", "while rendering # some content. This should be reset between", "def output_mailto(arg_string): \"\"\" Given the arguments of an anchor macro", "NOTE: make this a two element list to # give", "`image_name`: The name of the image being referenced. \"\"\" #", "use the Python Creoleparser (which requires Genshi) We make a", "it would happen. Arguments: - `topic_name`: The topic name being", "is a topic name we have not seen yet, add", "the Topic model. This is cheap since it will already", "of markup. Arguments: - `name`: The name of the macro", "# from django.core.urlresolvers import reverse from django.utils.translation import ugettext as", "= reverse('aswiki_topic_index'), # wiki_links_space_char = '%20', # use_additions = True,", "doing things like creating nascent topics. # self.topics_case = {", "# def clear_and_lock(self): \"\"\" Locks the mutex to prevent conflicts", "all of the topics that are referenced by the raw", "instantiate a TopicList and pass # a method when we", "Arguments: - `image_name`: The name of the image being referenced.", "being referenced. \"\"\" # If the image url is NOT", "so that the prerender../save() methods of the Topic object we", "from rendering a single topic. So we have to make", "the above example if I were to say <<subtopics 2007>>", "# if lower_topic_name not in self.topics: self.topics.append(lower_topic_name) self.topics_case[lower_topic_name] = topic_name", "This forms a kind of hierarchy. Loosely speaking all topics", "the topics that are referenced by the raw content for", "creole parser every time it hits an image link. This", "it relative to this # topic. # u = urlparse(image_name)", "by our creole parser every time it encounters a wiki", "by the wiki.models module we need to import that module", "to be the name of a topic. If no such", "treated as the separator. ie: <<subtopics 2007.>> and <<subtopics 2007>>", "XXX I think) modifies # the topic list we have", "find out what other topics # we should list in", "# so that the prerender../save() methods of the Topic object", "multiple calls to render text via the parser generated #", "topics. # self.topics_case = { } # This is another", "urlparse(image_name) if self.current_topic and len(u.path) > 0 and u.path[0] !=", "wiki_links_path_func = TOPIC_LIST.path_fn, # macro_func = macro_fn, # interwiki_links_base_urls=dict(wikicreole='http://wikicreole.org/wiki/', #", "topics a given topic refers to. \"\"\" # system imports", "in a <ul> If the arg string ends with a", "since for our current use we only want # the", "return None ul = builder.tag.ul() # For every file attachment", "for our version of markup. Arguments: - `name`: The name", "href=arg_string) return None ## ## Create our custom dialect. It", "will # use it for rendering our templates to prettify", "a topic. If no such topic exist, then no attachment", "# in the text being parsed. This is so we", "[] return ######################################################################## # def unlock(self): \"\"\" Unlocks the mutex.", "\"\"\" # XXX Need to support the fancy format.. but", "are referenced by a specific topic when its content is", "we know it. This # lets us root image url's", "installed. If we do we will # use it for", "creole11_base, wiki_links_base_url = reverse('aswiki_topic_index'), # NOTE: Make this # a", "add this topic to the # 'extra_references' list in our", "as a topic name is the parent topic. There is", "that start with the same prefix, separated by '.' are", "we can access the Topic model. This is cheap since", "= attachment.get_absolute_url()))) return ul #################################################################### # def macro_fn(name, arg_string, macro_body,", "wiki link. \"\"\" lower_topic_name = topic_name.lower() # if this is", "2007>> are identical. Arguments: - `arg_string`: The topic we want", "a kind of hierarchy. Loosely speaking all topics that start", "return ######################################################################## # def clear_and_lock(self): \"\"\" Locks the mutex to", "can tell what other topics a given topic refers to.", "<<subtopics >> macro. We need this so # that when", "= Topic.objects.get(lc_name = arg_string.lower()) except Topic.DoesNotExist: return None ul =", "prettify them a bit. # try: from typogrify.templatetags.typogrify import typogrify", "be loaded # from a separate # URL wiki_links_space_char =", "type macros. - `environ` : The environment object, passed through", "######################################################################## # def __init__(self): \"\"\" Very plain init. We set", "`block_type`: True if this is a block macro. \"\"\" #", "image names to be relative to the topic they are", "to proper <a href></a> links. We use this as a", "a specific topic when its content is created or modified.", "our wiki markup parser lives. We use the Python Creoleparser", "macro_fn, # custom_markup = (), interwiki_links_base_urls = { 'wikicreole' :", "way to annotate topics that do not exist yet with", "refers to. \"\"\" # system imports # from urllib import", "of execution (if there are other threads # running.. if", "so that we can tell what other topics a given", "output_mailto(arg_string): \"\"\" Given the arguments of an anchor macro output", "other thread of execution (if there are other threads #", "# self.current_topic = None # The list of topics that", "\"\"\" # The current topic that is being rendered, if", "Since this module is imported by the wiki.models module we", "def unlock(self): \"\"\" Unlocks the mutex. Do NOT access the", "output <ul> of the topics that are proper subtopics of", "output_subtopics(arg_string) elif name == 'attachlist': return output_attachments(arg_string) elif name ==", "time it encounters a wiki link in the text it", "if block_type: return _(macro_body) else: return _(arg_string) elif name ==", "names. \"\"\" ######################################################################## # def __init__(self): \"\"\" Very plain init.", "arg_string if arg_string[-1] != '.': arg_string = arg_string + \".\"", "a 'li' link # to that attachment. # for attachment", "3rd party imports # from creoleparser.dialects import create_dialect, creole10_base, creole11_base", "content for a specific topic. We pass the objet and", "make # sure no other thread of execution (if there", "image link. This lets us translate image names to be", "We only apply this magic transformation for images url's that", "from typogrify.templatetags.typogrify import typogrify except ImportError: def typogrify(text): return text", "when we create an instance of a Creole _dialect_ this", "'attachlist': return output_attachments(arg_string) elif name == 'attachment': # For including", "= True, # no_wiki_monospace = False, # wiki_links_class_func = class_fn,", "dot, then it is treated as the separator. ie: <<subtopics", "given as the arg_string. Arguments: - `arg_string`: Expected to be", "should list in this topic's references. # self.extra_references = []", "For every topic that matches our pattern we insert a", "across this process instance which may well # exist across", "also add this topic to the # 'extra_references' list in", "A helper class we use to keep track of all", "topics referenced by the topic being rendered. for topic in", "no attachment list is generated. \"\"\" try: topic = Topic.objects.get(lc_name", "proper genshi stream that will render a mailto link. We", "XXX This is where we should do a cache lookup", "or modified. This lets us know that list of topics", "transformation for images url's that are relative. Arguments: - `image_name`:", "of the anchor macro. - `macro_body`: The macro body if", "- `arg_string`: The argument string, including any delimiters - `macro_body`:", "string, including any delimiters - `macro_body`: The macro body, None", "list in our global TOPIC_LIST object. This is # so", "name == 'attachment': # For including downloadable attachments in a", "= '%20', # NOTE: make this a two element list", "some sort of transformation on topic names this is where", "is a block macro. \"\"\" # XXX Need to support", "we render a document. # # However, this is a", "# custom_markup = (), interwiki_links_base_urls = { 'wikicreole' : 'http://wikicreole.org/wiki/',", "<foo> DOT <foo>' Arguments: - `arg_string`: The argument string of", "to. We are passed in a topic name, and we", "def path_fn(self, topic_name): \"\"\" This is called by our creole", "a TopicList ## instance. The root URL for all wiki", "object, passed through from creoleparser.core.Parser class's 'parse()' method. \"\"\" name", "- `arg_string`: The argument string of the anchor macro. -", "ul.append(builder.tag.li(builder.tag.a(topic.name, href = topic.get_absolute_url()))) return ul #################################################################### # def output_attachments(arg_string):", "= (), interwiki_links_base_urls = { 'wikicreole' : 'http://wikicreole.org/wiki/', 'wikipedia' :'http://wikipedia.org/wiki/'", "to the 'path_func' parameter of our creole dialect we are", "yet created. We use the wiki.models.TopicManager's css_class_name method to do", "return ul #################################################################### # def output_attachments(arg_string): \"\"\" Returns a <ul>", "return output_attachments(arg_string) elif name == 'attachment': # For including downloadable", "tell which topics are not yet created. We use the", "== 'attachment': # For including downloadable attachments in a wiki", "None ul = builder.tag.ul() # For every file attachment on", "for can know to add those topics to the list", "identical. Arguments: - `arg_string`: The topic we want to find", "find all topics for which the string as a topic", "be the name of a topic. If no such topic", "# when doing things like creating nascent topics. # self.topics_case", "the topic they are found in as appropriate. We only", "is a sub-topic of 2007. 2007.Agenda.foo is a subtopic of", "use it for rendering our templates to prettify them a", "renders. # self.topics = [] # A dict mapping the", "<ul> If the arg string ends with a dot, then", "This is so we can preserve the case # when", "that matches our pattern we insert a 'li' link #", "- `image_name`: The name of the image being referenced. \"\"\"", "modifies # the topic list we have to provide a", "topics parameter after this is called. You can not be", "to add those topics to the list # of topics", "This # lets us root image url's relative to this", "class's 'parse()' method. \"\"\" name = name.strip().lower() arg_string = arg_string.strip()", "= name.strip().lower() arg_string = arg_string.strip() if name == 'anchor': if", "## NOTE: This assumes that the url for a specific", "} # This is another list. It contains Topic's that", "_dialect_ this one # instance will be shared across this", "create an instance of a Creole _dialect_ this one #", "we can preserve the case # when doing things like", "def output_subtopics(arg_string): \"\"\" This will take a single string as", "Topic is the same as the url ## for the", "of 2007. 2007.Agenda.foo is a subtopic of 2007 and 2007.Agenda.", "lookup of the topic name # and only if that", "by name. So in the above example if I were", "that users can easily tell which topics are not yet", "creating nascent topics. # self.topics_case = { } # This", "parameter after this is called. You can not be guaranteed", "shared across this process instance which may well # exist", "arg_string[-1] != '.': arg_string = arg_string + \".\" topics =", "the macros we define for our version of markup. Arguments:", "want # the topic names from rendering a single topic.", "If we do we will # use it for rendering", "they are found in as appropriate. We only apply this", "the fancy format.. but for now just get the basic", "# u = urlparse(image_name) if self.current_topic and len(u.path) > 0", "no_wiki_monospace = False, wiki_links_class_func = class_fn, wiki_links_path_func = (TOPIC_LIST.path_fn, TOPIC_LIST.image_fn),", "on this topic, add a 'li' link # to that", "self.current_topic = None # The list of topics that we", "the Topic object we are # rendering this output for", "parameter of our creole dialect we are goign to generate.", "list if more then one thread tries to render using", "wiki_links_base_url = reverse('aswiki_topic_index'), # wiki_links_space_char = '%20', # use_additions =", ") parser = Parser(dialect = create_dialect(\\ creole11_base, wiki_links_base_url = reverse('aswiki_topic_index'),", "the same as the url ## for the aswiki_topic_index with", "so that we can access the Topic model. This is", "return ################################################################## # def image_fn(self, image_name): \"\"\" This is called", "this topic referring to not via [[wiki links]] but via", "# interwiki_links_base_urls=dict(wikicreole='http://wikicreole.org/wiki/', # wikipedia='http://wikipedia.org/wiki/',) # ) parser = Parser(dialect =", "be the same as the ## 'aswiki_topic_index' url. ## ##", "track which topics this text refers to. We are passed", "text refers to. We are passed in a topic name,", "Arguments: - `arg_string`: Expected to be the name of a", "return topic_name ############################################################################ # def class_fn(topic_name): \"\"\" This function is", "topic_name.lower() # if this is a topic name we have", "= arg_string.lower()) except Topic.DoesNotExist: return None ul = builder.tag.ul() #", "a method when we create an instance of a Creole", "preserve the case # when doing things like creating nascent", "link in the text it is parsing. This lets us", "will render a mailto link. We also need to support", "imports # from creoleparser.dialects import create_dialect, creole10_base, creole11_base from creoleparser.core", "and 2007.Agenda. This macro will insert in to the output", "updating the topic list if more then one thread tries", "with some graphical attribute so that users can easily tell", "= { }, macro_func = macro_fn, # custom_markup = (),", "that will render a mailto link. We also need to", "output for can know to add those topics to the", "of our creole dialect we are goign to generate. The", "a way to annotate topics that do not exist yet", "if it contains periods, ie: the '.' character. This forms", "access the Topic model. This is cheap since it will", "to support the magic argument string format of '<you> AT", "href = topic.get_absolute_url()))) return ul #################################################################### # def output_attachments(arg_string): \"\"\"", ": The environment object, passed through from creoleparser.core.Parser class's 'parse()'", "passed through from creoleparser.core.Parser class's 'parse()' method. \"\"\" name =", "this magic transformation for images url's that are relative. Arguments:", "# wiki_links_base_url = reverse('aswiki_topic_index'), # wiki_links_space_char = '%20', # use_additions", "instance which may well # exist across multiple calls to", "us root image url's relative to this topic. # self.current_topic", "# and only if that fails fall back to #", "\"2007.Agenda.foo\" in a <ul> If the arg string ends with", "# Topic.objects.css_class_name(topic_name) # return Topic.objects.css_class_name(topic_name) #################################################################### # def output_mailto(arg_string): \"\"\"", "interwiki_links_base_urls=dict(wikicreole='http://wikicreole.org/wiki/', # wikipedia='http://wikipedia.org/wiki/',) # ) parser = Parser(dialect = create_dialect(\\", "If the arg string ends with a dot, then it", "of the given string, ordered by name. So in the", "we do we will # use it for rendering our", "by the topic being rendered. for topic in topics: TOPIC_LIST.extra_references.append(topic)", "Topic.objects.get(lc_name = arg_string.lower()) except Topic.DoesNotExist: return None ul = builder.tag.ul()", "methods like the <<subtopics >> macro. We need this so", "link # to that topic in our output. We also", "think) modifies # the topic list we have to provide", "but via # other methods like the <<subtopics >> macro.", "when its content is created or modified. This lets us", "- `arg_string`: The topic we want to find all subtopics", "# a method when we create an instance of a", "a 'li' link # to that topic in our output.", "to wiki links as they are turned in to proper", "topic. We pass the objet and method instead 'path_fn' in", "for which the string as a topic name is the", "Topic.DoesNotExist: return None ul = builder.tag.ul() # For every file", "have encountered while rendering # some content. This should be", "found in as appropriate. We only apply this magic transformation", "topic. So we have to make # sure no other", "lives. We use the Python Creoleparser (which requires Genshi) We", "name of the image being referenced. \"\"\" # If the", "######################################################################## # def path_fn(self, topic_name): \"\"\" This is called by", "is parsing. This lets us track which topics this text", "in a topic if it contains periods, ie: the '.'", "me \"2007.Agenda\" and \"2007.Agenda.foo\" in a <ul> If the arg", "is where the logic and definition of our wiki markup", "a TopicList and pass # a method when we create", "name.. if we were doing some sort of transformation on", "creoleparser.dialects import create_dialect, creole10_base, creole11_base from creoleparser.core import Parser from", "output the proper genshi stream that will render a mailto", "genshi stream that will render a mailto link. We also", "<filename>aswiki/parser.py # # File: $Id: parser.py 1865 2008-10-28 00:47:27Z scanner", "topic exist, then no attachment list is generated. \"\"\" try:", "URL base for all of the topics (pages) in the", "<ul> of the topics that are proper subtopics of the", "method instead 'path_fn' in to the 'path_func' parameter of our", "to render text via the parser generated # from the", "we create an instance of a Creole _dialect_ this one", "- `topic_name`: the topic name being checked for existence. \"\"\"", "original case used # in the text being parsed. This", "an anchor macro output the proper genshi stream that will", "checked for existence. \"\"\" # XXX This is where we", "the image url is NOT absolute, root it relative to", "so only one thread at a # time can add", "builder.tag.ul() # For every topic that matches our pattern we", "created or modified. This lets us know that list of", "which topics this text refers to. We are passed in", "Creole _dialect_ this one # instance will be shared across", "topic they are found in as appropriate. We only apply", "# use_additions = True, # no_wiki_monospace = False, # wiki_links_class_func", "name # and only if that fails fall back to", "of the macro - `arg_string`: The argument string, including any", "attribute so that users can easily tell which topics are", "bit of ugliness. Since we instantiate a TopicList and pass", "Arguments: - `name`: The name of the macro - `arg_string`:", "the image being referenced. \"\"\" # If the image url", "topics are referenced by a specific topic when its content", "us translate image names to be relative to the topic", "builder.tag.a(arg_string, href=\"mailto:%s\" % arg_string) #################################################################### # def output_subtopics(arg_string): \"\"\" This", "topics to a topic list. # self.lock = threading.Lock() return", "we need to import that module inside here so that", "= urlparse(image_name) if self.current_topic and len(u.path) > 0 and u.path[0]", "bodied_macros = { }, non_bodied_macros = { }, macro_func =", "same prefix, separated by '.' are sub-topics. So: 2007.Agenda is", "a single topic. So we have to make # sure", "do a cache lookup of the topic name # and", "render a mailto link. We also need to support the", "argument string format of '<you> AT <word> AT <foo> DOT", "in topic.file_attachments.all(): ul.append(builder.tag.li(builder.tag.a(attachment.basename(), href = attachment.get_absolute_url()))) return ul #################################################################### #", "\".\" topics = Topic.objects.filter(lc_name__istartswith = arg_string.lower()).order_by('lc_name') if topics.count() == 0:", "- `name`: The name of the macro - `arg_string`: The", "= topic_name.lower() # if this is a topic name we", "AT <word> AT <foo> DOT <foo>' Arguments: - `arg_string`: The", "topic if it contains periods, ie: the '.' character. This", "topic name being checked for existence. \"\"\" # XXX This", "# The list of topics that we have encountered while", "\"\"\" Returns a <ul> of all of the attachments attached", "semantic magic in a topic if it contains periods, ie:", "take a single string as its input. It will find", "names from rendering a single topic. So we have to", "self.extra_references = [] # This is a bit of ugliness.", "no body. - `block_type`: True for block type macros. -", "<foo>' Arguments: - `arg_string`: The argument string of the anchor", "is the css class name to add to wiki links", "list for images # to be loaded # from a", "False, wiki_links_class_func = class_fn, wiki_links_path_func = (TOPIC_LIST.path_fn, TOPIC_LIST.image_fn), bodied_macros =", "argument string, including any delimiters - `macro_body`: The macro body,", "None ul = builder.tag.ul() # For every topic that matches", "image url is NOT absolute, root it relative to this", "if lower_topic_name not in self.topics: self.topics.append(lower_topic_name) self.topics_case[lower_topic_name] = topic_name return", "arg_string, macro_body, block_type, environ): \"\"\" Handles the macros we define", "the magic argument string format of '<you> AT <word> AT", "custom_markup = (), interwiki_links_base_urls = { 'wikicreole' : 'http://wikicreole.org/wiki/', 'wikipedia'", "be guaranteed whose list of topics you are seeing. \"\"\"", "Make this # a two element # list for images", "- `arg_string`: Expected to be the name of a topic.", "return None ul = builder.tag.ul() # For every topic that", "the topics that are proper subtopics of the given string,", "we have # found this topic referring to not via", "href=\"mailto:%s\" % arg_string) #################################################################### # def output_subtopics(arg_string): \"\"\" This will", "custom dialect so that the parser can know the URL", "# of topics referenced by the topic being rendered. for", "make this a two element list to # give images", "parent topic. There is some semantic magic in a topic", "macro with no body. - `block_type`: True for block type", "is a problem since for our current use we only", "to provide a mutex so only one thread at a", "we have the 'typogrify' app installed. If we do we", "# topic. # u = urlparse(image_name) if self.current_topic and len(u.path)", "topic. # self.current_topic = None # The list of topics", "This is another list. It contains Topic's that we have", "that are proper subtopics of the given string, ordered by", "This should be reset between renders. # self.topics = []", "create_dialect, creole10_base, creole11_base from creoleparser.core import Parser from genshi import", "if I were to say <<subtopics 2007>> it would give", "\"\"\" try: topic = Topic.objects.get(lc_name = arg_string.lower()) except Topic.DoesNotExist: return", "dialect so that the parser can know the URL base", "arguments of an anchor macro output the proper genshi stream", "be imported. Arguments: - `topic_name`: the topic name being checked", "# For every file attachment on this topic, add a", "have # found this topic referring to not via [[wiki", "to our list # of topics. # if lower_topic_name not", "\"\"\" lower_topic_name = topic_name.lower() # if this is a topic", "is the parent topic. There is some semantic magic in", "tracking topics. \"\"\" # The current topic that is being", "try: import threading except ImportError: import dummy_threading as threading #", "the case # when doing things like creating nascent topics.", "self.current_topic + \"/\" + image_name return image_name ######################################################################## # def", "templates to prettify them a bit. # try: from typogrify.templatetags.typogrify", "periods, ie: the '.' character. This forms a kind of", "a Creole _dialect_ this one # instance will be shared", "in as appropriate. We only apply this magic transformation for", "name == 'mailto': return output_mailto(arg_string) elif name == 'gettext': if", "creoleparser.dialects.Creole10( # wiki_links_base_url = reverse('aswiki_topic_index'), # wiki_links_space_char = '%20', #", "all of the attachments attached to the topic name given", "== 'subtopics': return output_subtopics(arg_string) elif name == 'attachlist': return output_attachments(arg_string)", "body, None for macro with no body. - `block_type`: True", "only one thread at a # time can add topics", "operation.. XXX I think) modifies # the topic list we", "'attachment': # For including downloadable attachments in a wiki document.", "arg_string.lower()) except Topic.DoesNotExist: return None ul = builder.tag.ul() # For", "The topic name being referenced as a wiki link. \"\"\"", "for a specific topic. We pass the objet and method", "cache lookup of the topic name # and only if", "topic list. # self.lock = threading.Lock() return ######################################################################## # def", "return ######################################################################## # def unlock(self): \"\"\" Unlocks the mutex. Do", "we are done rendering we can find out what other", "need to support the magic argument string format of '<you>", "kind of hierarchy. Loosely speaking all topics that start with", "them a bit. # try: from typogrify.templatetags.typogrify import typogrify except", "1865 2008-10-28 00:47:27Z scanner $ # \"\"\" This is where", "# 3rd party imports # from creoleparser.dialects import create_dialect, creole10_base,", "an instance of a Creole _dialect_ this one # instance", "same time. \"\"\" self.lock.acquire() self.topics = [] self.topics_case = {", "other topics a given topic refers to. \"\"\" # system", "return self.current_topic + \"/\" + image_name return image_name ######################################################################## #", "add those topics to the list # of topics referenced", "magic in a topic if it contains periods, ie: the", "class name to add to wiki links as they are", "format.. but for now just get the basic # working.", "single topic. So we have to make # sure no", "topics you are seeing. \"\"\" self.lock.release() return ################################################################## # def", "arg_string) else: return builder.tag.a(name = arg_string) elif name == 'mailto':", "> 0 and u.path[0] != \"/\": return self.current_topic + \"/\"", "I were to say <<subtopics 2007>> it would give me", "# we should list in this topic's references. # self.extra_references", "mailto link. We also need to support the magic argument", "to say <<subtopics 2007>> it would give me \"2007.Agenda\" and", "turned in to proper <a href></a> links. We use this", "topic name given as the arg_string. Arguments: - `arg_string`: Expected", "what other topics # we should list in this topic's", "<a href></a> links. We use this as a way to", "logic and definition of our wiki markup parser lives. We", "arg_string) #################################################################### # def output_subtopics(arg_string): \"\"\" This will take a", "can not be guaranteed whose list of topics you are", "it to our list # of topics. # if lower_topic_name", "we have to provide a mutex so only one thread", "additional goop so that we can tell what other topics", "import Topic ############################################################################ ############################################################################ # class TopicList(object): \"\"\" A helper", "topics (pages) in the wiki and some additional goop so", "import ugettext as _ # 3rd party imports # from", "happen. Arguments: - `topic_name`: The topic name being referenced as", "(which requires Genshi) We make a custom dialect so that", "more then one thread tries to render using the same", "# rendering this output for can know to add those", "text # Model imports # from aswiki.models import Topic ############################################################################", "image_name): \"\"\" This is called by our creole parser every", "of the image being referenced. \"\"\" # If the image", "string that is the css class name to add to", "topics that are referenced by the raw content for a", "topics to the list # of topics referenced by the", "the parent topic. There is some semantic magic in a", "'parse()' method. \"\"\" name = name.strip().lower() arg_string = arg_string.strip() if", "name == 'anchor': if block_type: return builder.tag.a(macro_body, name = arg_string)", "two element # list for images # to be loaded", "name of a topic. If no such topic exist, then", "method to do this lookup. NOTE: Since this module is", "need to know what topics are referenced by a specific", "django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ #", "2007.Agenda. This macro will insert in to the output <ul>", "\"\"\" # If the image url is NOT absolute, root", "as a way to annotate topics that do not exist", "of a topic. If no such topic exist, then no", "including downloadable attachments in a wiki document. if block_type: return", "creole parser every time it encounters a wiki link in", "TOPIC_LIST.extra_references.append(topic) ul.append(builder.tag.li(builder.tag.a(topic.name, href = topic.get_absolute_url()))) return ul #################################################################### # def", "fails fall back to # Topic.objects.css_class_name(topic_name) # return Topic.objects.css_class_name(topic_name) ####################################################################", "string of the anchor macro. - `macro_body`: The macro body", "# character. no_wiki_monospace = False, wiki_links_class_func = class_fn, wiki_links_path_func =", "class_fn, wiki_links_path_func = (TOPIC_LIST.path_fn, TOPIC_LIST.image_fn), bodied_macros = { }, non_bodied_macros", "that topic name.. if we were doing some sort of", "the arg string ends with a dot, then it is", "this one # instance will be shared across this process", "it ## TOPIC_LIST = TopicList() # dialect = creoleparser.dialects.Creole10( #", "A dict mapping the lower case topic name to the", "this process instance which may well # exist across multiple", "!= '.': arg_string = arg_string + \".\" topics = Topic.objects.filter(lc_name__istartswith", "the arguments of an anchor macro output the proper genshi", "root URL for all wiki topics will be the same", "to this topic. # self.current_topic = None # The list", "Since we instantiate a TopicList and pass # a method", "to the # 'extra_references' list in our global TOPIC_LIST object.", "that is being rendered, if we know it. This #", "this is a block macro. \"\"\" # XXX Need to", "- `block_type`: True for block type macros. - `environ` :", "topics = Topic.objects.filter(lc_name__istartswith = arg_string.lower()).order_by('lc_name') if topics.count() == 0: return", "== 'attachlist': return output_attachments(arg_string) elif name == 'attachment': # For", "arg string ends with a dot, then it is treated", "object. This is # so that the prerender../save() methods of", "lower case topic name to the original case used #", "tries to render using the same dialect instance at the", "the Topic name appended to it ## TOPIC_LIST = TopicList()", "appropriate. We only apply this magic transformation for images url's", "Creoleparser (which requires Genshi) We make a custom dialect so", "to # give images a different space # character. no_wiki_monospace", "creole10_base, creole11_base from creoleparser.core import Parser from genshi import builder", "so we can preserve the case # when doing things", "'path_func' parameter of our creole dialect we are goign to", "# working. return builder.tag.a(arg_string, href=\"mailto:%s\" % arg_string) #################################################################### # def", "(pages) in the wiki and some additional goop so that", "name == 'subtopics': return output_subtopics(arg_string) elif name == 'attachlist': return", "that is the css class name to add to wiki", "Arguments: - `topic_name`: the topic name being checked for existence.", "every time it hits an image link. This lets us", "invoked by the markup dialect every time it encounters a", "name appended to it ## TOPIC_LIST = TopicList() # dialect", "we insert a 'li' link # to that topic in", "in topics: TOPIC_LIST.extra_references.append(topic) ul.append(builder.tag.li(builder.tag.a(topic.name, href = topic.get_absolute_url()))) return ul ####################################################################", "as a wiki link. \"\"\" lower_topic_name = topic_name.lower() # if", "it encounters a wiki topic. It returns a string that", "\"\"\" Handles the macros we define for our version of", "dict mapping the lower case topic name to the original", "topic = Topic.objects.get(lc_name = arg_string.lower()) except Topic.DoesNotExist: return None ul", "things like creating nascent topics. # self.topics_case = { }", "Returns a <ul> of all of the attachments attached to", "is # so that the prerender../save() methods of the Topic", "threading # Django imports # from django.core.urlresolvers import reverse from", "this is where it would happen. Arguments: - `topic_name`: The", "elif name == 'subtopics': return output_subtopics(arg_string) elif name == 'attachlist':", "absolute, root it relative to this # topic. # u", "cheap since it will already be imported. Arguments: - `topic_name`:", "'.': arg_string = arg_string + \".\" topics = Topic.objects.filter(lc_name__istartswith =", "via [[wiki links]] but via # other methods like the", "the aswiki_topic_index with the Topic name appended to it ##", "the Python Creoleparser (which requires Genshi) We make a custom", "running.. if not this is a cheap operation.. XXX I", "with the same prefix, separated by '.' are sub-topics. So:", "# def output_attachments(arg_string): \"\"\" Returns a <ul> of all of", "+ image_name return image_name ######################################################################## # def path_fn(self, topic_name): \"\"\"", "href = attachment.get_absolute_url()))) return ul #################################################################### # def macro_fn(name, arg_string,", "So: 2007.Agenda is a sub-topic of 2007. 2007.Agenda.foo is a", "<<subtopics 2007>> it would give me \"2007.Agenda\" and \"2007.Agenda.foo\" in", "space # character. no_wiki_monospace = False, wiki_links_class_func = class_fn, wiki_links_path_func", "the logic and definition of our wiki markup parser lives.", "# instance will be shared across this process instance which", "rendering # some content. This should be reset between renders.", "to the list # of topics referenced by the topic", "the same as the ## 'aswiki_topic_index' url. ## ## NOTE:", "is that we need to know what topics are referenced", "here so that we can access the Topic model. This", "element list to # give images a different space #", "topics for which the string as a topic name is", "dialect we are goign to generate. The point of this", "def __init__(self): \"\"\" Very plain init. We set up the", "_(arg_string) elif name == 'subtopics': return output_subtopics(arg_string) elif name ==", "import typogrify except ImportError: def typogrify(text): return text # Model", "return _(macro_body) else: return _(arg_string) elif name == 'subtopics': return", "our list of topics will grow every # time we", "def class_fn(topic_name): \"\"\" This function is invoked by the markup", "separated by '.' are sub-topics. So: 2007.Agenda is a sub-topic", "topic. # u = urlparse(image_name) if self.current_topic and len(u.path) >", "arg_string = arg_string if arg_string[-1] != '.': arg_string = arg_string", "return _(arg_string) elif name == 'subtopics': return output_subtopics(arg_string) elif name", "== 'mailto': return output_mailto(arg_string) elif name == 'gettext': if block_type:", "from the dialect, which means our list of topics will", "generate. The point of this class is that we need", "called by our creole parser every time it encounters a", "it encounters a wiki link in the text it is", "wiki_links_space_char = '%20', # NOTE: make this a two element", "know it. This # lets us root image url's relative", "DOT <foo>' Arguments: - `arg_string`: The argument string of the", "some content. This should be reset between renders. # self.topics", "were to say <<subtopics 2007>> it would give me \"2007.Agenda\"", "subtopics of the given string, ordered by name. So in", "provide a mutex so only one thread at a #", "it hits an image link. This lets us translate image", "output_mailto(arg_string) elif name == 'gettext': if block_type: return _(macro_body) else:", "names to be relative to the topic they are found", "referenced by the raw content for a specific topic. We", "on topic names this is where it would happen. Arguments:", "should do a cache lookup of the topic name #", "creoleparser.core.Parser class's 'parse()' method. \"\"\" name = name.strip().lower() arg_string =", "init. We set up the attribute for tracking topics. \"\"\"", "dialect, which means our list of topics will grow every", "can easily tell which topics are not yet created. We", "not via [[wiki links]] but via # other methods like", "rendered, if we know it. This # lets us root", "True if this is a block macro. \"\"\" # XXX", "that we need to know what topics are referenced by", "anchor macro. - `macro_body`: The macro body if provided -", "# def class_fn(topic_name): \"\"\" This function is invoked by the", "markup dialect every time it encounters a wiki topic. It", "base for all of the topics (pages) in the wiki", "we define for our version of markup. Arguments: - `name`:", "and <<subtopics 2007>> are identical. Arguments: - `arg_string`: The topic", "image being referenced. \"\"\" # If the image url is", "this class is that we need to know what topics", "will grow every # time we render a document. #", "time. \"\"\" self.lock.acquire() self.topics = [] self.topics_case = { }", "for topic in topics: TOPIC_LIST.extra_references.append(topic) ul.append(builder.tag.li(builder.tag.a(topic.name, href = topic.get_absolute_url()))) return", "macro_func = macro_fn, # custom_markup = (), interwiki_links_base_urls = {", "NOTE: Make this # a two element # list for", "link. We also need to support the magic argument string", "# wiki_links_class_func = class_fn, # wiki_links_path_func = TOPIC_LIST.path_fn, # macro_func", "(), interwiki_links_base_urls = { 'wikicreole' : 'http://wikicreole.org/wiki/', 'wikipedia' :'http://wikipedia.org/wiki/' }", "the topic name given as the arg_string. Arguments: - `arg_string`:", "dialect. It will use our class function and a TopicList", "process instance which may well # exist across multiple calls", "imports # from urllib import quote from urlparse import urlparse", "2007. 2007.Agenda.foo is a subtopic of 2007 and 2007.Agenda. This", "Create our custom dialect. It will use our class function", "topic name being referenced as a wiki link. \"\"\" lower_topic_name", "can add topics to a topic list. # self.lock =", "generated # from the dialect, which means our list of", "a bit of ugliness. Since we instantiate a TopicList and", "wiki and some additional goop so that we can tell", "found this topic referring to not via [[wiki links]] but", "point of this class is that we need to know", "are passed in a topic name, and we return that", "the separator. ie: <<subtopics 2007.>> and <<subtopics 2007>> are identical.", "2007 and 2007.Agenda. This macro will insert in to the" ]
[ "**kwargs): \"\"\" Ensure client is authorized to redirect to the", "= access_token return True return False except AccessToken.DoesNotExist: return False", "the refresh token. \"\"\" return request.refresh_token_object.access_token.scope def invalidate_authorization_code(self, client_id, code,", "'refresh_token']: token_type_hint = None token_types = { 'access_token': AccessToken, 'refresh_token':", "provided pass self._get_application(request.client_id, request) if request.client: return request.client.client_type == AbstractApplication.CLIENT_CONFIDENTIAL", "'password': (AbstractApplication.GRANT_PASSWORD,), 'client_credentials': (AbstractApplication.GRANT_CLIENT_CREDENTIALS,), 'refresh_token': (AbstractApplication.GRANT_AUTHORIZATION_CODE, AbstractApplication.GRANT_PASSWORD, AbstractApplication.GRANT_CLIENT_CREDENTIALS) } class", "binascii from datetime import timedelta from django.contrib.auth import authenticate from", "False if not client_id: return False if self._get_application(client_id, request) is", "authenticated = self._authenticate_client_body(request) return authenticated def authenticate_client_id(self, client_id, request, *args,", "user=request.user, token=token['refresh_token'], expires=expires, application=request.client, access_token=access_token ) return request.client.default_redirect_uri def revoke_token(self,", "token, token_type_hint, request, *args, **kwargs): \"\"\" Revoke an access or", "return False except AuthorizationCode.DoesNotExist: return False def validate_grant_type(self, client_id, grant_type,", "scopes, request): \"\"\" Ensure the Bearer token is valid and", "the rfc6749, client authentication is required in the following cases:", "authenticating using OAuth2Authentication request.access_token = access_token return True return False", "Get the default redirect URI for the client. \"\"\" return", "access_token = AccessToken.objects.select_related('application', 'user').get(token=token) if access_token.is_valid(scopes): request.client = access_token.application request.user", "token. :param token: The token string. :param token_type_hint: access_token or", "True def _authenticate_client_body(self, request): \"\"\" Try authenticating the client using", "GRANT_TYPE_MAPPING = { 'authorization_code': (AbstractApplication.GRANT_AUTHORIZATION_CODE,), 'password': (AbstractApplication.GRANT_PASSWORD,), 'client_credentials': (AbstractApplication.GRANT_CLIENT_CREDENTIALS,), 'refresh_token':", "<reponame>anobi/django-oauth-api import base64 import binascii from datetime import timedelta from", "client, request, *args, **kwargs): \"\"\" Ensure the authorization_code is valid", "see `Section 4.1.3`_. - Refresh Token Grant, when Client type", "expires=expires, application=request.client, access_token=access_token ) return request.client.default_redirect_uri def revoke_token(self, token, token_type_hint,", "application=request.client): token.revoke() def validate_bearer_token(self, token, scopes, request): \"\"\" Ensure the", "client_id, scopes, client, request, *args, **kwargs): \"\"\" Ensure the client", "get_original_scopes(self, refresh_token, request, *args, **kwargs): \"\"\" Get the list of", "rt.is_expired: request.user = rt.user request.refresh_token = rt.token request.refresh_token_object = rt", "to requested scopes. \"\"\" return set(scopes).issubset(set(oauth_api_settings.SCOPES.keys())) def validate_user(self, username, password,", "\"\"\" return set(scopes).issubset(set(oauth_api_settings.SCOPES.keys())) def validate_user(self, username, password, client, request, *args,", "auth = request.headers.get('HTTP_AUTHORIZATION', None) if not auth: return None splitted", "HTTP Basic. \"\"\" if self._get_application(client_id, request) is not None: return", "= timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) AuthorizationCode.objects.create( application=request.client, user=request.user, code=code['code'], expires=expires, redirect_uri=request.redirect_uri,", "False else: return True def _authenticate_client_body(self, request): \"\"\" Try authenticating", "== client return False except RefreshToken.DoesNotExist: return False def validate_response_type(self,", "return False try: encoding = request.encoding or 'utf-8' except AttributeError:", "AbstractApplication.GRANT_CLIENT_CREDENTIALS) } class OAuthValidator(RequestValidator): def _get_application(self, client_id, request): \"\"\" Load", "is not None: return request.client.client_type != AbstractApplication.CLIENT_CONFIDENTIAL return False def", "None and user.is_active: request.user = user return True return False", "authentication is required for current request. According to the rfc6749,", "to redirect to the redirect_uri requested. \"\"\" auth_code = AuthorizationCode.objects.get(application=client,", "AccessToken, 'refresh_token': RefreshToken, } token_type = token_types.get(token_type_hint, AccessToken) try: token_type.objects.get(token=token,", "use the response_type requested. Authorization Endpoint Response Types registry is", "password is valid. \"\"\" user = authenticate(username=username, password=password) if user", "Client provided client authentication, see `Section 4.1.3`_. - Refresh Token", "def validate_client_id(self, client_id, request, *args, **kwargs): \"\"\" Check that and", "client. \"\"\" return list(oauth_api_settings.SCOPES.keys()) def get_original_scopes(self, refresh_token, request, *args, **kwargs):", "to authenticate the client. \"\"\" authenticated = self._authenticate_client_basic(request) if not", "*args, **kwargs): \"\"\" Get the default redirect URI for the", "client_id and store it in request as 'client' attribute \"\"\"", "client using HTTP Basic Authentication method \"\"\" auth_string = self._get_auth_string(request)", "Confidential or when Client was issued client credentials or whenever", "not None: return request.client.client_type != AbstractApplication.CLIENT_CONFIDENTIAL return False def confirm_redirect_uri(self,", "\"\"\" if token is None: return False try: access_token =", "base64.b64decode(auth_string) except (TypeError, binascii.Error): return False try: auth_string_decoded = b64_decoded.decode(encoding)", "if not auth_code.is_expired: request.scopes = auth_code.scope.split(' ') request.user = auth_code.user", "the authorization_code. \"\"\" expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) AuthorizationCode.objects.create( application=request.client,", "'client_credentials': (AbstractApplication.GRANT_CLIENT_CREDENTIALS,), 'refresh_token': (AbstractApplication.GRANT_AUTHORIZATION_CODE, AbstractApplication.GRANT_PASSWORD, AbstractApplication.GRANT_CLIENT_CREDENTIALS) } class OAuthValidator(RequestValidator): def", "\"\"\" Try to authenticate the client. \"\"\" authenticated = self._authenticate_client_basic(request)", "= AuthorizationCode.objects.get(application=request.client, code=code) auth_code.delete() def save_authorization_code(self, client_id, code, request, *args,", "\"\"\" Ensure client is authorized to use the response_type requested.", "token_type.objects.get(token=token, application=request.client).revoke() except token_type.DoesNotExist: # Lookup from all token types", "\"\"\" Ensure client is authorized to use the grant_type requested.", "from request body \"\"\" try: client_id = request.client_id client_secret =", "authenticate through other means, such as using HTTP Basic. \"\"\"", "return auth_code.redirect_uri_allowed(redirect_uri) def get_default_redirect_uri(self, client_id, request, *args, **kwargs): \"\"\" Get", "timezone.now() + timedelta(seconds=oauth_api_settings.REFRESH_TOKEN_EXPIRATION) else: expires = None RefreshToken.objects.create( user=request.user, token=token['refresh_token'],", "_authenticate_client_body(self, request): \"\"\" Try authenticating the client using values from", "\"\"\" Load application instance for given client_id and store it", "is authorized to use the grant_type requested. \"\"\" assert (grant_type", "return request.client.authorization_grant_type in GRANT_TYPE_MAPPING[grant_type] def validate_redirect_uri(self, client_id, redirect_uri, request, *args,", "return authenticated def authenticate_client_id(self, client_id, request, *args, **kwargs): \"\"\" Ensure", "client_id, request, *args, **kwargs): \"\"\" Ensure client_id belong to a", "*args, **kwargs): \"\"\" Ensure the username and password is valid.", "token. \"\"\" if request.refresh_token: # Revoke Refresh Token (and related", "if not authenticated: authenticated = self._authenticate_client_body(request) return authenticated def authenticate_client_id(self,", "def validate_user(self, username, password, client, request, *args, **kwargs): \"\"\" Ensure", "return False else: return True def client_authentication_required(self, request, *args, **kwargs):", "\"\"\" user = authenticate(username=username, password=password) if user is not None", "except from already looked up type other_types = (_type for", "redirect_uri requested. \"\"\" return request.client.redirect_uri_allowed(redirect_uri) def validate_refresh_token(self, refresh_token, client, request,", "AttributeError: # Client id or secret not provided pass self._get_application(request.client_id,", "other_type in other_types: for token in other_type.objects.filter(token=token, application=request.client): token.revoke() def", "auth_code = AuthorizationCode.objects.select_related('user').get(application=client, code=code) if not auth_code.is_expired: request.scopes = auth_code.scope.split('", "def _authenticate_client_basic(self, request): \"\"\" Try authenticating the client using HTTP", "_type in token_types.values() if _type != token_type) for other_type in", "credentials or whenever Client provided client authentication, see `Section 4.1.3`_.", "if not client_id: return False if self._get_application(client_id, request) is None:", "assigned to client. \"\"\" try: auth_code = AuthorizationCode.objects.select_related('user').get(application=client, code=code) if", "request, *args, **kwargs): \"\"\" Ensure the Bearer token is valid", "# Revoke Refresh Token (and related Access Token) try: RefreshToken.objects.get(token=request.refresh_token).revoke()", "application=request.client, access_token=access_token ) return request.client.default_redirect_uri def revoke_token(self, token, token_type_hint, request,", "pass self._get_application(request.client_id, request) if request.client: return request.client.client_type == AbstractApplication.CLIENT_CONFIDENTIAL return", "self._get_application(request.client_id, request) if request.client: return request.client.client_type == AbstractApplication.CLIENT_CONFIDENTIAL return super(OAuthValidator,", "None) if not auth: return None splitted = auth.split(' ',", "\"\"\" Ensure client is authorized to redirect to the redirect_uri", "is authorized to use the response_type requested. Authorization Endpoint Response", "id or secret not provided pass self._get_application(request.client_id, request) if request.client:", "the client. \"\"\" return list(oauth_api_settings.SCOPES.keys()) def get_original_scopes(self, refresh_token, request, *args,", "revoke_token(self, token, token_type_hint, request, *args, **kwargs): \"\"\" Revoke an access", "return request.client.client_type != AbstractApplication.CLIENT_CONFIDENTIAL return False def confirm_redirect_uri(self, client_id, code,", "of scopes associated with the refresh token. \"\"\" return request.refresh_token_object.access_token.scope", "class OAuthValidator(RequestValidator): def _get_application(self, client_id, request): \"\"\" Load application instance", "scopes. \"\"\" try: rt = RefreshToken.objects.select_related('user').get(token=refresh_token) if not rt.is_expired: request.user", "http://tools.ietf.org/html/rfc6749#section-8.4 \"\"\" if response_type == 'code': return client.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE", "get_application_model, AccessToken, AuthorizationCode, RefreshToken, AbstractApplication from oauth_api.settings import oauth_api_settings GRANT_TYPE_MAPPING", "response_type == 'token': return client.authorization_grant_type == AbstractApplication.GRANT_IMPLICIT else: return False", "- Authorization Code Grant, when Client type is Confidential or", "looked up type other_types = (_type for _type in token_types.values()", "whenever Client provided client authentication, see `Section 6`_ :param request:", "get_default_scopes(self, client_id, request, *args, **kwargs): \"\"\" Get the default scopes", "Client id or secret not provided pass self._get_application(request.client_id, request) if", "Load application instance for given client_id and store it in", "redirect_uri, request, *args, **kwargs): \"\"\" Ensure client is authorized to", "authorized to redirect to the redirect_uri requested. \"\"\" return request.client.redirect_uri_allowed(redirect_uri)", "request.refresh_token: # Revoke Refresh Token (and related Access Token) try:", "Token) try: RefreshToken.objects.get(token=request.refresh_token).revoke() except RefreshToken.DoesNotExist: # Already revoked? pass expires", "None: return request.client.client_type != AbstractApplication.CLIENT_CONFIDENTIAL return False def confirm_redirect_uri(self, client_id,", "and authorized access to scopes. \"\"\" if token is None:", "that and Application exists with given client_id. \"\"\" return self._get_application(client_id,", "is not required to authenticate through other means, such as", "def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs): \"\"\" Ensure client", "non-confidential client is one that is not required to authenticate", "Determine if client authentication is required for current request. According", "= get_application_model() try: request.client = request.client or Application.objects.get(client_id=client_id) return request.client", "redirect URI for the client. \"\"\" return request.client.default_redirect_uri def get_default_scopes(self,", "client, request, *args, **kwargs): \"\"\" Ensure the Bearer token is", "token_type_hint: access_token or refresh_token. :param request: The HTTP Request (oauthlib.common.Request)", "def get_original_scopes(self, refresh_token, request, *args, **kwargs): \"\"\" Get the list", "request, *args, **kwargs): \"\"\" Ensure client is authorized to redirect", "False except AccessToken.DoesNotExist: return False def validate_client_id(self, client_id, request, *args,", "= AuthorizationCode.objects.select_related('user').get(application=client, code=code) if not auth_code.is_expired: request.scopes = auth_code.scope.split(' ')", "password, client, request, *args, **kwargs): \"\"\" Ensure the username and", "datetime import timedelta from django.contrib.auth import authenticate from django.utils import", "`Section 4.3.2`_. - Authorization Code Grant, when Client type is", "oauth_api_settings GRANT_TYPE_MAPPING = { 'authorization_code': (AbstractApplication.GRANT_AUTHORIZATION_CODE,), 'password': (AbstractApplication.GRANT_PASSWORD,), 'client_credentials': (AbstractApplication.GRANT_CLIENT_CREDENTIALS,),", "client_id belong to a non-confidential client. A non-confidential client is", "oauthlib.common.Request :return: True or False \"\"\" if self._get_auth_string(request): return True", "Ensure client_id belong to a non-confidential client. A non-confidential client", "access or refresh token. :param token: The token string. :param", "= authenticate(username=username, password=password) if user is not None and user.is_active:", "AccessToken.objects.create( user=user, scope=token['scope'], expires=expires, token=token['access_token'], application=request.client ) if 'refresh_token' in", "def validate_bearer_token(self, token, scopes, request): \"\"\" Ensure the Bearer token", "in other_type.objects.filter(token=token, application=request.client): token.revoke() def validate_bearer_token(self, token, scopes, request): \"\"\"", "when authenticating using OAuth2Authentication request.access_token = access_token return True return", "def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): \"\"\" Ensure", "client, request, *args, **kwargs): \"\"\" Ensure the client is authorized", "request.client except Application.DoesNotExist: return None def _get_auth_string(self, request): auth =", "in the following cases: - Resource Owner Password Credentials Grant,", "= access_token.user request.scopes = scopes # Required when authenticating using", "request, *args, **kwargs): \"\"\" Ensure client is authorized to use", "self._get_auth_string(request): return True try: if request.client_id and request.client_secret: return True", "Already revoked? pass expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) user =", "_authenticate_client_basic(self, request): \"\"\" Try authenticating the client using HTTP Basic", "default scopes for the client. \"\"\" return list(oauth_api_settings.SCOPES.keys()) def get_original_scopes(self,", "RefreshToken.DoesNotExist: # Already revoked? pass expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION)", "application=request.client, user=request.user, code=code['code'], expires=expires, redirect_uri=request.redirect_uri, scope=' '.join(request.scopes) ) return request.redirect_uri", "Ensure the authorization_code is valid and assigned to client. \"\"\"", "such as using HTTP Basic. \"\"\" if self._get_application(client_id, request) is", "other means, such as using HTTP Basic. \"\"\" if self._get_application(client_id,", "\"\"\" Get the list of scopes associated with the refresh", "access to requested scopes. \"\"\" return set(scopes).issubset(set(oauth_api_settings.SCOPES.keys())) def validate_user(self, username,", "an authorization code after use. \"\"\" auth_code = AuthorizationCode.objects.get(application=request.client, code=code)", "request, *args, **kwargs): \"\"\" Persist the Bearer token. \"\"\" if", "= (_type for _type in token_types.values() if _type != token_type)", "return True def client_authentication_required(self, request, *args, **kwargs): \"\"\" Determine if", "authenticate_client_id(self, client_id, request, *args, **kwargs): \"\"\" Ensure client_id belong to", "**kwargs): \"\"\" Ensure the client is authorized access to requested", "return True except AttributeError: # Client id or secret not", "AttributeError: encoding = 'utf-8' try: b64_decoded = base64.b64decode(auth_string) except (TypeError,", "if self._get_application(client_id, request) is None: return False elif request.client.client_secret !=", "client_id, request): \"\"\" Load application instance for given client_id and", "to the redirect_uri requested. \"\"\" auth_code = AuthorizationCode.objects.get(application=client, code=code) return", "redirect_uri=request.redirect_uri, scope=' '.join(request.scopes) ) return request.redirect_uri def save_bearer_token(self, token, request,", "refresh_token. :param request: The HTTP Request (oauthlib.common.Request) \"\"\" if token_type_hint", "a non-confidential client. A non-confidential client is one that is", "non-confidential client. A non-confidential client is one that is not", "request.grant_type == 'client_credentials': user = None access_token = AccessToken.objects.create( user=user,", "try: access_token = AccessToken.objects.select_related('application', 'user').get(token=token) if access_token.is_valid(scopes): request.client = access_token.application", "None: return False try: access_token = AccessToken.objects.select_related('application', 'user').get(token=token) if access_token.is_valid(scopes):", "**kwargs): \"\"\" Check that and Application exists with given client_id.", "body \"\"\" try: client_id = request.client_id client_secret = request.client_secret except", "RefreshToken, } token_type = token_types.get(token_type_hint, AccessToken) try: token_type.objects.get(token=token, application=request.client).revoke() except", "and password is valid. \"\"\" user = authenticate(username=username, password=password) if", "access_token return True return False except AccessToken.DoesNotExist: return False def", "request as 'client' attribute \"\"\" assert hasattr(request, 'client'), \"'client' attribute", "get_application_model() try: request.client = request.client or Application.objects.get(client_id=client_id) return request.client except", "4.3.2`_. - Authorization Code Grant, when Client type is Confidential", "try: auth_string_decoded = b64_decoded.decode(encoding) except UnicodeDecodeError: return False client_id, client_secret", "**kwargs): \"\"\" Persist the authorization_code. \"\"\" expires = timezone.now() +", "if token_type_hint not in ['access_token', 'refresh_token']: token_type_hint = None token_types", "\"\"\" return request.client.default_redirect_uri def get_default_scopes(self, client_id, request, *args, **kwargs): \"\"\"", "Response Types registry is not supported. See http://tools.ietf.org/html/rfc6749#section-8.4 \"\"\" if", "Refresh Token Grant, when Client type is Confidential or when", "(TypeError, binascii.Error): return False try: auth_string_decoded = b64_decoded.decode(encoding) except UnicodeDecodeError:", "client_secret: return False else: return True def _authenticate_client_body(self, request): \"\"\"", "the client. \"\"\" authenticated = self._authenticate_client_basic(request) if not authenticated: authenticated", "from already looked up type other_types = (_type for _type", "= auth_code.user return True return False except AuthorizationCode.DoesNotExist: return False", "\"\"\" return self._get_application(client_id, request) is not None def validate_code(self, client_id,", "oauth_api.models import get_application_model, AccessToken, AuthorizationCode, RefreshToken, AbstractApplication from oauth_api.settings import", "return self._get_application(client_id, request) is not None def validate_code(self, client_id, code,", "\"\"\" try: rt = RefreshToken.objects.select_related('user').get(token=refresh_token) if not rt.is_expired: request.user =", "grant_type requested. \"\"\" assert (grant_type in GRANT_TYPE_MAPPING) return request.client.authorization_grant_type in", "scopes. \"\"\" return set(scopes).issubset(set(oauth_api_settings.SCOPES.keys())) def validate_user(self, username, password, client, request,", "**kwargs): \"\"\" Try to authenticate the client. \"\"\" authenticated =", "AbstractApplication.CLIENT_CONFIDENTIAL return False def confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args,", "secret not provided pass self._get_application(request.client_id, request) if request.client: return request.client.client_type", "def get_default_redirect_uri(self, client_id, request, *args, **kwargs): \"\"\" Get the default", "= rt return rt.application == client return False except RefreshToken.DoesNotExist:", "*args, **kwargs): \"\"\" Try to authenticate the client. \"\"\" authenticated", ":param request: oauthlib.common.Request :return: True or False \"\"\" if self._get_auth_string(request):", "(oauthlib.common.Request) \"\"\" if token_type_hint not in ['access_token', 'refresh_token']: token_type_hint =", "auth_type != 'Basic': return None return auth_string def _authenticate_client_basic(self, request):", "it in request as 'client' attribute \"\"\" assert hasattr(request, 'client'),", "cases: - Resource Owner Password Credentials Grant, when Client type", "authentication, see `Section 4.1.3`_. - Refresh Token Grant, when Client", "= { 'access_token': AccessToken, 'refresh_token': RefreshToken, } token_type = token_types.get(token_type_hint,", "import binascii from datetime import timedelta from django.contrib.auth import authenticate", "the client is authorized access to requested scopes. \"\"\" return", "rt = RefreshToken.objects.select_related('user').get(token=refresh_token) if not rt.is_expired: request.user = rt.user request.refresh_token", "'client_credentials': user = None access_token = AccessToken.objects.create( user=user, scope=token['scope'], expires=expires,", "request.access_token = access_token return True return False except AccessToken.DoesNotExist: return", "valid and authorized access to scopes. \"\"\" try: rt =", "= 'utf-8' try: b64_decoded = base64.b64decode(auth_string) except (TypeError, binascii.Error): return", "\"\"\" try: auth_code = AuthorizationCode.objects.select_related('user').get(application=client, code=code) if not auth_code.is_expired: request.scopes", "user = authenticate(username=username, password=password) if user is not None and", "= timezone.now() + timedelta(seconds=oauth_api_settings.REFRESH_TOKEN_EXPIRATION) else: expires = None RefreshToken.objects.create( user=request.user,", "access_token = AccessToken.objects.create( user=user, scope=token['scope'], expires=expires, token=token['access_token'], application=request.client ) if", "None return auth_string def _authenticate_client_basic(self, request): \"\"\" Try authenticating the", "to client. \"\"\" try: auth_code = AuthorizationCode.objects.select_related('user').get(application=client, code=code) if not", "client.authorization_grant_type == AbstractApplication.GRANT_IMPLICIT else: return False def validate_scopes(self, client_id, scopes,", "credentials or whenever Client provided client authentication, see `Section 6`_", "_type != token_type) for other_type in other_types: for token in", "try: request.client = request.client or Application.objects.get(client_id=client_id) return request.client except Application.DoesNotExist:", "use. \"\"\" auth_code = AuthorizationCode.objects.get(application=request.client, code=code) auth_code.delete() def save_authorization_code(self, client_id,", "client, request, *args, **kwargs): \"\"\" Ensure client is authorized to", "'utf-8' except AttributeError: encoding = 'utf-8' try: b64_decoded = base64.b64decode(auth_string)", "= splitted if auth_type != 'Basic': return None return auth_string", "client_secret: return False else: return True def client_authentication_required(self, request, *args,", "timedelta(seconds=oauth_api_settings.REFRESH_TOKEN_EXPIRATION) else: expires = None RefreshToken.objects.create( user=request.user, token=token['refresh_token'], expires=expires, application=request.client,", "= None token_types = { 'access_token': AccessToken, 'refresh_token': RefreshToken, }", "') request.user = auth_code.user return True return False except AuthorizationCode.DoesNotExist:", "(grant_type in GRANT_TYPE_MAPPING) return request.client.authorization_grant_type in GRANT_TYPE_MAPPING[grant_type] def validate_redirect_uri(self, client_id,", "RefreshToken.DoesNotExist: return False def validate_response_type(self, client_id, response_type, client, request, *args,", "access to scopes. \"\"\" if token is None: return False", "client is authorized to use the response_type requested. Authorization Endpoint", "Authorization Code Grant, when Client type is Confidential or when", "token_types.values() if _type != token_type) for other_type in other_types: for", "token_type_hint, request, *args, **kwargs): \"\"\" Revoke an access or refresh", "validate_client_id(self, client_id, request, *args, **kwargs): \"\"\" Check that and Application", "or whenever Client provided client authentication, see `Section 4.1.3`_. -", "None splitted = auth.split(' ', 1) if len(splitted) != 2:", "from oauthlib.oauth2 import RequestValidator from oauth_api.models import get_application_model, AccessToken, AuthorizationCode,", "requested scopes. \"\"\" return set(scopes).issubset(set(oauth_api_settings.SCOPES.keys())) def validate_user(self, username, password, client,", ") if 'refresh_token' in token: if oauth_api_settings.REFRESH_TOKEN_EXPIRATION is not None:", "\"\"\" expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) AuthorizationCode.objects.create( application=request.client, user=request.user, code=code['code'],", "Endpoint Response Types registry is not supported. See http://tools.ietf.org/html/rfc6749#section-8.4 \"\"\"", "request.client.authorization_grant_type in GRANT_TYPE_MAPPING[grant_type] def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs):", "client authentication, see `Section 4.1.3`_. - Refresh Token Grant, when", "Client provided client authentication, see `Section 6`_ :param request: oauthlib.common.Request", ") return request.redirect_uri def save_bearer_token(self, token, request, *args, **kwargs): \"\"\"", "== 'client_credentials': user = None access_token = AccessToken.objects.create( user=user, scope=token['scope'],", "return False try: access_token = AccessToken.objects.select_related('application', 'user').get(token=token) if access_token.is_valid(scopes): request.client", "as 'client' attribute \"\"\" assert hasattr(request, 'client'), \"'client' attribute missing", "RefreshToken, AbstractApplication from oauth_api.settings import oauth_api_settings GRANT_TYPE_MAPPING = { 'authorization_code':", "from oauth_api.settings import oauth_api_settings GRANT_TYPE_MAPPING = { 'authorization_code': (AbstractApplication.GRANT_AUTHORIZATION_CODE,), 'password':", "False elif request.client.client_secret != client_secret: return False else: return True", "Resource Owner Password Credentials Grant, when Client type is Confidential", "associated with the refresh token. \"\"\" return request.refresh_token_object.access_token.scope def invalidate_authorization_code(self,", "token is valid and authorized access to scopes. \"\"\" if", "def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs): \"\"\" Ensure", "= base64.b64decode(auth_string) except (TypeError, binascii.Error): return False try: auth_string_decoded =", "self._authenticate_client_body(request) return authenticated def authenticate_client_id(self, client_id, request, *args, **kwargs): \"\"\"", "Types registry is not supported. See http://tools.ietf.org/html/rfc6749#section-8.4 \"\"\" if response_type", "**kwargs): \"\"\" Ensure the Bearer token is valid and authorized", "token_type_hint = None token_types = { 'access_token': AccessToken, 'refresh_token': RefreshToken,", "validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): \"\"\" Ensure the Bearer", "get_default_redirect_uri(self, client_id, request, *args, **kwargs): \"\"\" Get the default redirect", "(AbstractApplication.GRANT_CLIENT_CREDENTIALS,), 'refresh_token': (AbstractApplication.GRANT_AUTHORIZATION_CODE, AbstractApplication.GRANT_PASSWORD, AbstractApplication.GRANT_CLIENT_CREDENTIALS) } class OAuthValidator(RequestValidator): def _get_application(self,", "from django.contrib.auth import authenticate from django.utils import timezone from oauthlib.oauth2", "valid and assigned to client. \"\"\" try: auth_code = AuthorizationCode.objects.select_related('user').get(application=client,", "return False elif request.client.client_secret != client_secret: return False else: return", "timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) AuthorizationCode.objects.create( application=request.client, user=request.user, code=code['code'], expires=expires, redirect_uri=request.redirect_uri, scope='", "except AccessToken.DoesNotExist: return False def validate_client_id(self, client_id, request, *args, **kwargs):", "request.user if request.grant_type == 'client_credentials': user = None access_token =", "import timedelta from django.contrib.auth import authenticate from django.utils import timezone", "is authorized access to requested scopes. \"\"\" return set(scopes).issubset(set(oauth_api_settings.SCOPES.keys())) def", "request, *args, **kwargs): \"\"\" Determine if client authentication is required", "password=password) if user is not None and user.is_active: request.user =", "2: return None auth_type, auth_string = splitted if auth_type !=", "token_type_hint not in ['access_token', 'refresh_token']: token_type_hint = None token_types =", "or False \"\"\" if self._get_auth_string(request): return True try: if request.client_id", "return True def _authenticate_client_body(self, request): \"\"\" Try authenticating the client", "authenticated: authenticated = self._authenticate_client_body(request) return authenticated def authenticate_client_id(self, client_id, request,", "None access_token = AccessToken.objects.create( user=user, scope=token['scope'], expires=expires, token=token['access_token'], application=request.client )", "auth_code = AuthorizationCode.objects.get(application=client, code=code) return auth_code.redirect_uri_allowed(redirect_uri) def get_default_redirect_uri(self, client_id, request,", "6`_ :param request: oauthlib.common.Request :return: True or False \"\"\" if", "to the redirect_uri requested. \"\"\" return request.client.redirect_uri_allowed(redirect_uri) def validate_refresh_token(self, refresh_token,", "- Refresh Token Grant, when Client type is Confidential or", "that is not required to authenticate through other means, such", "= auth_string_decoded.split(':', 1) if self._get_application(client_id, request) is None: return False", "for current request. According to the rfc6749, client authentication is", "= request.client or Application.objects.get(client_id=client_id) return request.client except Application.DoesNotExist: return None", "(AbstractApplication.GRANT_AUTHORIZATION_CODE,), 'password': (AbstractApplication.GRANT_PASSWORD,), 'client_credentials': (AbstractApplication.GRANT_CLIENT_CREDENTIALS,), 'refresh_token': (AbstractApplication.GRANT_AUTHORIZATION_CODE, AbstractApplication.GRANT_PASSWORD, AbstractApplication.GRANT_CLIENT_CREDENTIALS) }", "\"\"\" Try authenticating the client using HTTP Basic Authentication method", "request) is None: return False elif request.client.client_secret != client_secret: return", "request, *args, **kwargs): \"\"\" Persist the authorization_code. \"\"\" expires =", "code=code) return auth_code.redirect_uri_allowed(redirect_uri) def get_default_redirect_uri(self, client_id, request, *args, **kwargs): \"\"\"", "up type other_types = (_type for _type in token_types.values() if", "for other_type in other_types: for token in other_type.objects.filter(token=token, application=request.client): token.revoke()", "assert (grant_type in GRANT_TYPE_MAPPING) return request.client.authorization_grant_type in GRANT_TYPE_MAPPING[grant_type] def validate_redirect_uri(self,", "return False else: return True def _authenticate_client_body(self, request): \"\"\" Try", "Revoke Refresh Token (and related Access Token) try: RefreshToken.objects.get(token=request.refresh_token).revoke() except", "token_types = { 'access_token': AccessToken, 'refresh_token': RefreshToken, } token_type =", "\"\"\" auth_code = AuthorizationCode.objects.get(application=request.client, code=code) auth_code.delete() def save_authorization_code(self, client_id, code,", "an access or refresh token. :param token: The token string.", "def confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args, **kwargs): \"\"\" Ensure", "in request as 'client' attribute \"\"\" assert hasattr(request, 'client'), \"'client'", "+ timedelta(seconds=oauth_api_settings.REFRESH_TOKEN_EXPIRATION) else: expires = None RefreshToken.objects.create( user=request.user, token=token['refresh_token'], expires=expires,", "given client_id. \"\"\" return self._get_application(client_id, request) is not None def", "_get_auth_string(self, request): auth = request.headers.get('HTTP_AUTHORIZATION', None) if not auth: return", "request): \"\"\" Load application instance for given client_id and store", "return super(OAuthValidator, self).client_authentication_required(request, *args, **kwargs) def authenticate_client(self, request, *args, **kwargs):", "(_type for _type in token_types.values() if _type != token_type) for", "auth_string = splitted if auth_type != 'Basic': return None return", "OAuth2Authentication request.access_token = access_token return True return False except AccessToken.DoesNotExist:", "is authorized to redirect to the redirect_uri requested. \"\"\" auth_code", "redirect_uri requested. \"\"\" auth_code = AuthorizationCode.objects.get(application=client, code=code) return auth_code.redirect_uri_allowed(redirect_uri) def", "not None def validate_code(self, client_id, code, client, request, *args, **kwargs):", "!= client_secret: return False else: return True def client_authentication_required(self, request,", "AccessToken, AuthorizationCode, RefreshToken, AbstractApplication from oauth_api.settings import oauth_api_settings GRANT_TYPE_MAPPING =", "Credentials Grant, when Client type is Confidential or when Client", "Refresh Token (and related Access Token) try: RefreshToken.objects.get(token=request.refresh_token).revoke() except RefreshToken.DoesNotExist:", "provided client authentication, see `Section 4.1.3`_. - Refresh Token Grant,", "Authorization Endpoint Response Types registry is not supported. See http://tools.ietf.org/html/rfc6749#section-8.4", "\"\"\" if response_type == 'code': return client.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE elif", "the Bearer token. \"\"\" if request.refresh_token: # Revoke Refresh Token", "*args, **kwargs): \"\"\" Ensure the client is authorized access to", "expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) user = request.user if request.grant_type", "return request.client.redirect_uri_allowed(redirect_uri) def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): \"\"\"", "attribute missing from 'request'\" Application = get_application_model() try: request.client =", "authentication, see `Section 6`_ :param request: oauthlib.common.Request :return: True or", "authorized to redirect to the redirect_uri requested. \"\"\" auth_code =", "Invalidate an authorization code after use. \"\"\" auth_code = AuthorizationCode.objects.get(application=request.client,", "to use the grant_type requested. \"\"\" assert (grant_type in GRANT_TYPE_MAPPING)", "in other_types: for token in other_type.objects.filter(token=token, application=request.client): token.revoke() def validate_bearer_token(self,", "See http://tools.ietf.org/html/rfc6749#section-8.4 \"\"\" if response_type == 'code': return client.authorization_grant_type ==", "return auth_string def _authenticate_client_basic(self, request): \"\"\" Try authenticating the client", "if user is not None and user.is_active: request.user = user", "user is not None and user.is_active: request.user = user return", "user = None access_token = AccessToken.objects.create( user=user, scope=token['scope'], expires=expires, token=token['access_token'],", "Lookup from all token types except from already looked up", "not auth_string: return False try: encoding = request.encoding or 'utf-8'", "def authenticate_client(self, request, *args, **kwargs): \"\"\" Try to authenticate the", "AuthorizationCode, RefreshToken, AbstractApplication from oauth_api.settings import oauth_api_settings GRANT_TYPE_MAPPING = {", "base64 import binascii from datetime import timedelta from django.contrib.auth import", "b64_decoded.decode(encoding) except UnicodeDecodeError: return False client_id, client_secret = auth_string_decoded.split(':', 1)", "if oauth_api_settings.REFRESH_TOKEN_EXPIRATION is not None: expires = timezone.now() + timedelta(seconds=oauth_api_settings.REFRESH_TOKEN_EXPIRATION)", "# Lookup from all token types except from already looked", "request.client_secret: return True except AttributeError: # Client id or secret", "for token in other_type.objects.filter(token=token, application=request.client): token.revoke() def validate_bearer_token(self, token, scopes,", "return False try: auth_string_decoded = b64_decoded.decode(encoding) except UnicodeDecodeError: return False", "refresh_token, request, *args, **kwargs): \"\"\" Get the list of scopes", "request) is not None def validate_code(self, client_id, code, client, request,", "authorization_code is valid and assigned to client. \"\"\" try: auth_code", "and authorized access to scopes. \"\"\" try: rt = RefreshToken.objects.select_related('user').get(token=refresh_token)", "use the grant_type requested. \"\"\" assert (grant_type in GRANT_TYPE_MAPPING) return", "if 'refresh_token' in token: if oauth_api_settings.REFRESH_TOKEN_EXPIRATION is not None: expires", "\"\"\" Get the default scopes for the client. \"\"\" return", "code, redirect_uri, client, *args, **kwargs): \"\"\" Ensure client is authorized", "user = request.user if request.grant_type == 'client_credentials': user = None", "*args, **kwargs): \"\"\" Ensure client is authorized to redirect to", "code, client, request, *args, **kwargs): \"\"\" Ensure the authorization_code is", "authenticating the client using values from request body \"\"\" try:", "client_id, client_secret = auth_string_decoded.split(':', 1) if self._get_application(client_id, request) is None:", "import get_application_model, AccessToken, AuthorizationCode, RefreshToken, AbstractApplication from oauth_api.settings import oauth_api_settings", "HTTP Basic Authentication method \"\"\" auth_string = self._get_auth_string(request) if not", "rt return rt.application == client return False except RefreshToken.DoesNotExist: return", "try: RefreshToken.objects.get(token=request.refresh_token).revoke() except RefreshToken.DoesNotExist: # Already revoked? pass expires =", "try: encoding = request.encoding or 'utf-8' except AttributeError: encoding =", "False def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs): \"\"\"", "is None: return False try: access_token = AccessToken.objects.select_related('application', 'user').get(token=token) if", "as using HTTP Basic. \"\"\" if self._get_application(client_id, request) is not", "binascii.Error): return False try: auth_string_decoded = b64_decoded.decode(encoding) except UnicodeDecodeError: return", "client_id, code, request, *args, **kwargs): \"\"\" Invalidate an authorization code", "= access_token.application request.user = access_token.user request.scopes = scopes # Required", "Request (oauthlib.common.Request) \"\"\" if token_type_hint not in ['access_token', 'refresh_token']: token_type_hint", "request.user = auth_code.user return True return False except AuthorizationCode.DoesNotExist: return", "client is authorized to use the grant_type requested. \"\"\" assert", "request: oauthlib.common.Request :return: True or False \"\"\" if self._get_auth_string(request): return", "token=token['access_token'], application=request.client ) if 'refresh_token' in token: if oauth_api_settings.REFRESH_TOKEN_EXPIRATION is", "authorized to use the grant_type requested. \"\"\" assert (grant_type in", "is not supported. See http://tools.ietf.org/html/rfc6749#section-8.4 \"\"\" if response_type == 'code':", "Try authenticating the client using HTTP Basic Authentication method \"\"\"", "for the client. \"\"\" return request.client.default_redirect_uri def get_default_scopes(self, client_id, request,", "expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) AuthorizationCode.objects.create( application=request.client, user=request.user, code=code['code'], expires=expires,", "(AbstractApplication.GRANT_AUTHORIZATION_CODE, AbstractApplication.GRANT_PASSWORD, AbstractApplication.GRANT_CLIENT_CREDENTIALS) } class OAuthValidator(RequestValidator): def _get_application(self, client_id, request):", "\"\"\" return list(oauth_api_settings.SCOPES.keys()) def get_original_scopes(self, refresh_token, request, *args, **kwargs): \"\"\"", "code after use. \"\"\" auth_code = AuthorizationCode.objects.get(application=request.client, code=code) auth_code.delete() def", "GRANT_TYPE_MAPPING) return request.client.authorization_grant_type in GRANT_TYPE_MAPPING[grant_type] def validate_redirect_uri(self, client_id, redirect_uri, request,", "AttributeError: return False if not client_id: return False if self._get_application(client_id,", "user=user, scope=token['scope'], expires=expires, token=token['access_token'], application=request.client ) if 'refresh_token' in token:", "to use the response_type requested. Authorization Endpoint Response Types registry", "scopes. \"\"\" if token is None: return False try: access_token", "is None: return False elif request.client.client_secret != client_secret: return False", "\"\"\" Ensure the client is authorized access to requested scopes.", "= request.encoding or 'utf-8' except AttributeError: encoding = 'utf-8' try:", "b64_decoded = base64.b64decode(auth_string) except (TypeError, binascii.Error): return False try: auth_string_decoded", "= request.client_id client_secret = request.client_secret except AttributeError: return False if", "return False if not client_id: return False if self._get_application(client_id, request)", "the username and password is valid. \"\"\" user = authenticate(username=username,", "django.contrib.auth import authenticate from django.utils import timezone from oauthlib.oauth2 import", "AbstractApplication.GRANT_IMPLICIT else: return False def validate_scopes(self, client_id, scopes, client, request,", "*args, **kwargs): \"\"\" Ensure client_id belong to a non-confidential client.", "authenticated def authenticate_client_id(self, client_id, request, *args, **kwargs): \"\"\" Ensure client_id", "Basic. \"\"\" if self._get_application(client_id, request) is not None: return request.client.client_type", "True def client_authentication_required(self, request, *args, **kwargs): \"\"\" Determine if client", "grant_type, client, request, *args, **kwargs): \"\"\" Ensure client is authorized", "AbstractApplication.GRANT_PASSWORD, AbstractApplication.GRANT_CLIENT_CREDENTIALS) } class OAuthValidator(RequestValidator): def _get_application(self, client_id, request): \"\"\"", "is not None: expires = timezone.now() + timedelta(seconds=oauth_api_settings.REFRESH_TOKEN_EXPIRATION) else: expires", "return False def confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args, **kwargs):", "scope=' '.join(request.scopes) ) return request.redirect_uri def save_bearer_token(self, token, request, *args,", "**kwargs): \"\"\" Ensure client is authorized to use the response_type", "**kwargs): \"\"\" Persist the Bearer token. \"\"\" if request.refresh_token: #", "token: The token string. :param token_type_hint: access_token or refresh_token. :param", "None def _get_auth_string(self, request): auth = request.headers.get('HTTP_AUTHORIZATION', None) if not", "to a non-confidential client. A non-confidential client is one that", "is not None def validate_code(self, client_id, code, client, request, *args,", "= auth.split(' ', 1) if len(splitted) != 2: return None", "except AuthorizationCode.DoesNotExist: return False def validate_grant_type(self, client_id, grant_type, client, request,", "supported. See http://tools.ietf.org/html/rfc6749#section-8.4 \"\"\" if response_type == 'code': return client.authorization_grant_type", "GRANT_TYPE_MAPPING[grant_type] def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs): \"\"\" Ensure", "+ timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) user = request.user if request.grant_type == 'client_credentials': user", "using HTTP Basic. \"\"\" if self._get_application(client_id, request) is not None:", "the list of scopes associated with the refresh token. \"\"\"", "belong to a non-confidential client. A non-confidential client is one", "} token_type = token_types.get(token_type_hint, AccessToken) try: token_type.objects.get(token=token, application=request.client).revoke() except token_type.DoesNotExist:", "def _authenticate_client_body(self, request): \"\"\" Try authenticating the client using values", "client_secret = auth_string_decoded.split(':', 1) if self._get_application(client_id, request) is None: return", "self._get_application(client_id, request) is not None: return request.client.client_type != AbstractApplication.CLIENT_CONFIDENTIAL return", "*args, **kwargs): \"\"\" Persist the Bearer token. \"\"\" if request.refresh_token:", "= request.client_secret except AttributeError: return False if not client_id: return", "auth.split(' ', 1) if len(splitted) != 2: return None auth_type,", "except token_type.DoesNotExist: # Lookup from all token types except from", "token.revoke() def validate_bearer_token(self, token, scopes, request): \"\"\" Ensure the Bearer", "refresh token. \"\"\" return request.refresh_token_object.access_token.scope def invalidate_authorization_code(self, client_id, code, request,", "AuthorizationCode.objects.select_related('user').get(application=client, code=code) if not auth_code.is_expired: request.scopes = auth_code.scope.split(' ') request.user", "assert hasattr(request, 'client'), \"'client' attribute missing from 'request'\" Application =", "in ['access_token', 'refresh_token']: token_type_hint = None token_types = { 'access_token':", "rt.application == client return False except RefreshToken.DoesNotExist: return False def", "the default scopes for the client. \"\"\" return list(oauth_api_settings.SCOPES.keys()) def", "authorized access to scopes. \"\"\" if token is None: return", "authorized to use the response_type requested. Authorization Endpoint Response Types", "== AbstractApplication.GRANT_AUTHORIZATION_CODE elif response_type == 'token': return client.authorization_grant_type == AbstractApplication.GRANT_IMPLICIT", "not client_id: return False if self._get_application(client_id, request) is None: return", "Persist the authorization_code. \"\"\" expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) AuthorizationCode.objects.create(", "None RefreshToken.objects.create( user=request.user, token=token['refresh_token'], expires=expires, application=request.client, access_token=access_token ) return request.client.default_redirect_uri", "client_id. \"\"\" return self._get_application(client_id, request) is not None def validate_code(self,", "= token_types.get(token_type_hint, AccessToken) try: token_type.objects.get(token=token, application=request.client).revoke() except token_type.DoesNotExist: # Lookup", "request.scopes = auth_code.scope.split(' ') request.user = auth_code.user return True return", "or when Client was issued client credentials or whenever Client", "request.client.client_type != AbstractApplication.CLIENT_CONFIDENTIAL return False def confirm_redirect_uri(self, client_id, code, redirect_uri,", "(AbstractApplication.GRANT_PASSWORD,), 'client_credentials': (AbstractApplication.GRANT_CLIENT_CREDENTIALS,), 'refresh_token': (AbstractApplication.GRANT_AUTHORIZATION_CODE, AbstractApplication.GRANT_PASSWORD, AbstractApplication.GRANT_CLIENT_CREDENTIALS) } class OAuthValidator(RequestValidator):", "invalidate_authorization_code(self, client_id, code, request, *args, **kwargs): \"\"\" Invalidate an authorization", "in GRANT_TYPE_MAPPING[grant_type] def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs): \"\"\"", "and assigned to client. \"\"\" try: auth_code = AuthorizationCode.objects.select_related('user').get(application=client, code=code)", "refresh token. :param token: The token string. :param token_type_hint: access_token", "client_id = request.client_id client_secret = request.client_secret except AttributeError: return False", "The token string. :param token_type_hint: access_token or refresh_token. :param request:", "token string. :param token_type_hint: access_token or refresh_token. :param request: The", "AccessToken) try: token_type.objects.get(token=token, application=request.client).revoke() except token_type.DoesNotExist: # Lookup from all", "return None auth_type, auth_string = splitted if auth_type != 'Basic':", "access_token.is_valid(scopes): request.client = access_token.application request.user = access_token.user request.scopes = scopes", "see `Section 6`_ :param request: oauthlib.common.Request :return: True or False", "} class OAuthValidator(RequestValidator): def _get_application(self, client_id, request): \"\"\" Load application", "\"\"\" Try authenticating the client using values from request body", "AbstractApplication.GRANT_AUTHORIZATION_CODE elif response_type == 'token': return client.authorization_grant_type == AbstractApplication.GRANT_IMPLICIT else:", "request.client_secret except AttributeError: return False if not client_id: return False", "list of scopes associated with the refresh token. \"\"\" return", ":return: True or False \"\"\" if self._get_auth_string(request): return True try:", "import base64 import binascii from datetime import timedelta from django.contrib.auth", "return request.refresh_token_object.access_token.scope def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs): \"\"\"", ":param request: The HTTP Request (oauthlib.common.Request) \"\"\" if token_type_hint not", "response_type requested. Authorization Endpoint Response Types registry is not supported.", "auth_string: return False try: encoding = request.encoding or 'utf-8' except", "1) if self._get_application(client_id, request) is None: return False elif request.client.client_secret", "RefreshToken.objects.select_related('user').get(token=refresh_token) if not rt.is_expired: request.user = rt.user request.refresh_token = rt.token", "def get_default_scopes(self, client_id, request, *args, **kwargs): \"\"\" Get the default", "redirect to the redirect_uri requested. \"\"\" auth_code = AuthorizationCode.objects.get(application=client, code=code)", "in token: if oauth_api_settings.REFRESH_TOKEN_EXPIRATION is not None: expires = timezone.now()", "AccessToken.DoesNotExist: return False def validate_client_id(self, client_id, request, *args, **kwargs): \"\"\"", "client_id, request, *args, **kwargs): \"\"\" Check that and Application exists", "not supported. See http://tools.ietf.org/html/rfc6749#section-8.4 \"\"\" if response_type == 'code': return", "from django.utils import timezone from oauthlib.oauth2 import RequestValidator from oauth_api.models", "return False except RefreshToken.DoesNotExist: return False def validate_response_type(self, client_id, response_type,", "in GRANT_TYPE_MAPPING) return request.client.authorization_grant_type in GRANT_TYPE_MAPPING[grant_type] def validate_redirect_uri(self, client_id, redirect_uri,", "token: if oauth_api_settings.REFRESH_TOKEN_EXPIRATION is not None: expires = timezone.now() +", "None token_types = { 'access_token': AccessToken, 'refresh_token': RefreshToken, } token_type", "code, request, *args, **kwargs): \"\"\" Invalidate an authorization code after", "request, *args, **kwargs): \"\"\" Revoke an access or refresh token.", "request.client.client_secret != client_secret: return False else: return True def client_authentication_required(self,", "authenticate the client. \"\"\" authenticated = self._authenticate_client_basic(request) if not authenticated:", "is one that is not required to authenticate through other", "Owner Password Credentials Grant, when Client type is Confidential or", "return client.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE elif response_type == 'token': return client.authorization_grant_type", "request.headers.get('HTTP_AUTHORIZATION', None) if not auth: return None splitted = auth.split('", "encoding = request.encoding or 'utf-8' except AttributeError: encoding = 'utf-8'", "Try to authenticate the client. \"\"\" authenticated = self._authenticate_client_basic(request) if", "False def confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args, **kwargs): \"\"\"", "client_id, code, redirect_uri, client, *args, **kwargs): \"\"\" Ensure client is", "code=code) if not auth_code.is_expired: request.scopes = auth_code.scope.split(' ') request.user =", "request.client = request.client or Application.objects.get(client_id=client_id) return request.client except Application.DoesNotExist: return", "!= 2: return None auth_type, auth_string = splitted if auth_type", "request.refresh_token = rt.token request.refresh_token_object = rt return rt.application == client", "(and related Access Token) try: RefreshToken.objects.get(token=request.refresh_token).revoke() except RefreshToken.DoesNotExist: # Already", "pass expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) user = request.user if", "revoked? pass expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) user = request.user", "= request.headers.get('HTTP_AUTHORIZATION', None) if not auth: return None splitted =", "False if self._get_application(client_id, request) is None: return False elif request.client.client_secret", "if not rt.is_expired: request.user = rt.user request.refresh_token = rt.token request.refresh_token_object", "not auth: return None splitted = auth.split(' ', 1) if", "all token types except from already looked up type other_types", "Required when authenticating using OAuth2Authentication request.access_token = access_token return True", "attribute \"\"\" assert hasattr(request, 'client'), \"'client' attribute missing from 'request'\"", "except UnicodeDecodeError: return False client_id, client_secret = auth_string_decoded.split(':', 1) if", "request. According to the rfc6749, client authentication is required in", "client.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE elif response_type == 'token': return client.authorization_grant_type ==", "Bearer token is valid and authorized access to scopes. \"\"\"", "request.client.redirect_uri_allowed(redirect_uri) def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): \"\"\" Ensure", "return False if self._get_application(client_id, request) is None: return False elif", ":param token_type_hint: access_token or refresh_token. :param request: The HTTP Request", "False \"\"\" if self._get_auth_string(request): return True try: if request.client_id and", "try: if request.client_id and request.client_secret: return True except AttributeError: #", "*args, **kwargs): \"\"\" Invalidate an authorization code after use. \"\"\"", "return False except AccessToken.DoesNotExist: return False def validate_client_id(self, client_id, request,", "'refresh_token': (AbstractApplication.GRANT_AUTHORIZATION_CODE, AbstractApplication.GRANT_PASSWORD, AbstractApplication.GRANT_CLIENT_CREDENTIALS) } class OAuthValidator(RequestValidator): def _get_application(self, client_id,", "was issued client credentials or whenever Client provided client authentication,", "request) is not None: return request.client.client_type != AbstractApplication.CLIENT_CONFIDENTIAL return False", "HTTP Request (oauthlib.common.Request) \"\"\" if token_type_hint not in ['access_token', 'refresh_token']:", "for _type in token_types.values() if _type != token_type) for other_type", "auth_code.scope.split(' ') request.user = auth_code.user return True return False except", "*args, **kwargs): \"\"\" Determine if client authentication is required for", "not auth_code.is_expired: request.scopes = auth_code.scope.split(' ') request.user = auth_code.user return", "client. A non-confidential client is one that is not required", "following cases: - Resource Owner Password Credentials Grant, when Client", "whenever Client provided client authentication, see `Section 4.1.3`_. - Refresh", "request.client.client_secret != client_secret: return False else: return True def _authenticate_client_body(self,", "= AuthorizationCode.objects.get(application=client, code=code) return auth_code.redirect_uri_allowed(redirect_uri) def get_default_redirect_uri(self, client_id, request, *args,", "= timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) user = request.user if request.grant_type ==", "\"'client' attribute missing from 'request'\" Application = get_application_model() try: request.client", "redirect_uri, client, *args, **kwargs): \"\"\" Ensure client is authorized to", "requested. \"\"\" auth_code = AuthorizationCode.objects.get(application=client, code=code) return auth_code.redirect_uri_allowed(redirect_uri) def get_default_redirect_uri(self,", "oauth_api.settings import oauth_api_settings GRANT_TYPE_MAPPING = { 'authorization_code': (AbstractApplication.GRANT_AUTHORIZATION_CODE,), 'password': (AbstractApplication.GRANT_PASSWORD,),", "UnicodeDecodeError: return False client_id, client_secret = auth_string_decoded.split(':', 1) if self._get_application(client_id,", "whenever Client provided client authentication, see `Section 4.3.2`_. - Authorization", "*args, **kwargs): \"\"\" Check that and Application exists with given", "if not auth: return None splitted = auth.split(' ', 1)", "when Client was issued client credentials or whenever Client provided", "required in the following cases: - Resource Owner Password Credentials", ":param token: The token string. :param token_type_hint: access_token or refresh_token.", "False try: auth_string_decoded = b64_decoded.decode(encoding) except UnicodeDecodeError: return False client_id,", "default redirect URI for the client. \"\"\" return request.client.default_redirect_uri def", "Token Grant, when Client type is Confidential or when Client", "request): \"\"\" Try authenticating the client using HTTP Basic Authentication", "if request.refresh_token: # Revoke Refresh Token (and related Access Token)", "with the refresh token. \"\"\" return request.refresh_token_object.access_token.scope def invalidate_authorization_code(self, client_id,", "else: return True def client_authentication_required(self, request, *args, **kwargs): \"\"\" Determine", "authentication is required in the following cases: - Resource Owner", "timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) AuthorizationCode.objects.create( application=request.client, user=request.user, code=code['code'], expires=expires, redirect_uri=request.redirect_uri, scope=' '.join(request.scopes) )", "def _get_application(self, client_id, request): \"\"\" Load application instance for given", "len(splitted) != 2: return None auth_type, auth_string = splitted if", "store it in request as 'client' attribute \"\"\" assert hasattr(request,", "False def validate_client_id(self, client_id, request, *args, **kwargs): \"\"\" Check that", "instance for given client_id and store it in request as", "'client'), \"'client' attribute missing from 'request'\" Application = get_application_model() try:", "try: b64_decoded = base64.b64decode(auth_string) except (TypeError, binascii.Error): return False try:", "client_id, request, *args, **kwargs): \"\"\" Get the default redirect URI", "registry is not supported. See http://tools.ietf.org/html/rfc6749#section-8.4 \"\"\" if response_type ==", "return rt.application == client return False except RefreshToken.DoesNotExist: return False", "validate_bearer_token(self, token, scopes, request): \"\"\" Ensure the Bearer token is", "return False client_id, client_secret = auth_string_decoded.split(':', 1) if self._get_application(client_id, request)", "expires = timezone.now() + timedelta(seconds=oauth_api_settings.REFRESH_TOKEN_EXPIRATION) else: expires = None RefreshToken.objects.create(", "auth_string = self._get_auth_string(request) if not auth_string: return False try: encoding", "self._get_auth_string(request) if not auth_string: return False try: encoding = request.encoding", "Ensure client is authorized to use the response_type requested. Authorization", "return request.client except Application.DoesNotExist: return None def _get_auth_string(self, request): auth", "client authentication, see `Section 6`_ :param request: oauthlib.common.Request :return: True", "OAuthValidator(RequestValidator): def _get_application(self, client_id, request): \"\"\" Load application instance for", "already looked up type other_types = (_type for _type in", "= AccessToken.objects.select_related('application', 'user').get(token=token) if access_token.is_valid(scopes): request.client = access_token.application request.user =", "request, *args, **kwargs): \"\"\" Check that and Application exists with", "= scopes # Required when authenticating using OAuth2Authentication request.access_token =", "**kwargs): \"\"\" Determine if client authentication is required for current", "\"\"\" Ensure client_id belong to a non-confidential client. A non-confidential", "False except AuthorizationCode.DoesNotExist: return False def validate_grant_type(self, client_id, grant_type, client,", "try: client_id = request.client_id client_secret = request.client_secret except AttributeError: return", "request.user = access_token.user request.scopes = scopes # Required when authenticating", "provided client authentication, see `Section 6`_ :param request: oauthlib.common.Request :return:", "auth_string def _authenticate_client_basic(self, request): \"\"\" Try authenticating the client using", "client_id, code, client, request, *args, **kwargs): \"\"\" Ensure the authorization_code", "with given client_id. \"\"\" return self._get_application(client_id, request) is not None", "!= client_secret: return False else: return True def _authenticate_client_body(self, request):", "client_id, response_type, client, request, *args, **kwargs): \"\"\" Ensure client is", "Grant, when Client type is Confidential or when Client was", "Token (and related Access Token) try: RefreshToken.objects.get(token=request.refresh_token).revoke() except RefreshToken.DoesNotExist: #", "True or False \"\"\" if self._get_auth_string(request): return True try: if", "\"\"\" auth_string = self._get_auth_string(request) if not auth_string: return False try:", "to the rfc6749, client authentication is required in the following", "Bearer token. \"\"\" if request.refresh_token: # Revoke Refresh Token (and", "if _type != token_type) for other_type in other_types: for token", "rt.user request.refresh_token = rt.token request.refresh_token_object = rt return rt.application ==", "Revoke an access or refresh token. :param token: The token", "Client was issued client credentials or whenever Client provided client", "the redirect_uri requested. \"\"\" auth_code = AuthorizationCode.objects.get(application=client, code=code) return auth_code.redirect_uri_allowed(redirect_uri)", "URI for the client. \"\"\" return request.client.default_redirect_uri def get_default_scopes(self, client_id,", "import RequestValidator from oauth_api.models import get_application_model, AccessToken, AuthorizationCode, RefreshToken, AbstractApplication", "means, such as using HTTP Basic. \"\"\" if self._get_application(client_id, request)", "**kwargs): \"\"\" Get the list of scopes associated with the", "else: return False def validate_scopes(self, client_id, scopes, client, request, *args,", "authorized access to scopes. \"\"\" try: rt = RefreshToken.objects.select_related('user').get(token=refresh_token) if", "if self._get_auth_string(request): return True try: if request.client_id and request.client_secret: return", "or whenever Client provided client authentication, see `Section 6`_ :param", "when Client type is Confidential or when Client was issued", "# Already revoked? pass expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) user", "request): auth = request.headers.get('HTTP_AUTHORIZATION', None) if not auth: return None", "\"\"\" if self._get_application(client_id, request) is not None: return request.client.client_type !=", "related Access Token) try: RefreshToken.objects.get(token=request.refresh_token).revoke() except RefreshToken.DoesNotExist: # Already revoked?", "None: expires = timezone.now() + timedelta(seconds=oauth_api_settings.REFRESH_TOKEN_EXPIRATION) else: expires = None", "\"\"\" Ensure the Bearer token is valid and authorized access", "auth_type, auth_string = splitted if auth_type != 'Basic': return None", "authorization code after use. \"\"\" auth_code = AuthorizationCode.objects.get(application=request.client, code=code) auth_code.delete()", "auth_string_decoded = b64_decoded.decode(encoding) except UnicodeDecodeError: return False client_id, client_secret =", "1) if len(splitted) != 2: return None auth_type, auth_string =", "except RefreshToken.DoesNotExist: # Already revoked? pass expires = timezone.now() +", "from all token types except from already looked up type", "AuthorizationCode.objects.create( application=request.client, user=request.user, code=code['code'], expires=expires, redirect_uri=request.redirect_uri, scope=' '.join(request.scopes) ) return", "request.user = rt.user request.refresh_token = rt.token request.refresh_token_object = rt return", "return False def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):", "client_authentication_required(self, request, *args, **kwargs): \"\"\" Determine if client authentication is", "or whenever Client provided client authentication, see `Section 4.3.2`_. -", "return True try: if request.client_id and request.client_secret: return True except", "The HTTP Request (oauthlib.common.Request) \"\"\" if token_type_hint not in ['access_token',", "request, *args, **kwargs): \"\"\" Ensure client_id belong to a non-confidential", "type is Confidential or when Client was issued client credentials", "for the client. \"\"\" return list(oauth_api_settings.SCOPES.keys()) def get_original_scopes(self, refresh_token, request,", "None: return False elif request.client.client_secret != client_secret: return False else:", "auth_code.redirect_uri_allowed(redirect_uri) def get_default_redirect_uri(self, client_id, request, *args, **kwargs): \"\"\" Get the", "\"\"\" Get the default redirect URI for the client. \"\"\"", "validate_response_type(self, client_id, response_type, client, request, *args, **kwargs): \"\"\" Ensure client", "valid and authorized access to scopes. \"\"\" if token is", "request, *args, **kwargs): \"\"\" Ensure the client is authorized access", "request.client.default_redirect_uri def get_default_scopes(self, client_id, request, *args, **kwargs): \"\"\" Get the", "is required for current request. According to the rfc6749, client", "request, *args, **kwargs): \"\"\" Get the list of scopes associated", "values from request body \"\"\" try: client_id = request.client_id client_secret", "access_token.application request.user = access_token.user request.scopes = scopes # Required when", "return True return False except AccessToken.DoesNotExist: return False def validate_client_id(self,", "False def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): \"\"\"", "authenticate(username=username, password=password) if user is not None and user.is_active: request.user", "+ timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) AuthorizationCode.objects.create( application=request.client, user=request.user, code=code['code'], expires=expires, redirect_uri=request.redirect_uri, scope=' '.join(request.scopes)", "super(OAuthValidator, self).client_authentication_required(request, *args, **kwargs) def authenticate_client(self, request, *args, **kwargs): \"\"\"", "application instance for given client_id and store it in request", "types except from already looked up type other_types = (_type", "def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): \"\"\" Ensure", "missing from 'request'\" Application = get_application_model() try: request.client = request.client", "Application.DoesNotExist: return None def _get_auth_string(self, request): auth = request.headers.get('HTTP_AUTHORIZATION', None)", "token is None: return False try: access_token = AccessToken.objects.select_related('application', 'user').get(token=token)", "to redirect to the redirect_uri requested. \"\"\" return request.client.redirect_uri_allowed(redirect_uri) def", "return True return False except AuthorizationCode.DoesNotExist: return False def validate_grant_type(self,", "auth_code.is_expired: request.scopes = auth_code.scope.split(' ') request.user = auth_code.user return True", "client. \"\"\" try: auth_code = AuthorizationCode.objects.select_related('user').get(application=client, code=code) if not auth_code.is_expired:", "False def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): \"\"\"", "- Resource Owner Password Credentials Grant, when Client type is", "timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) user = request.user if request.grant_type == 'client_credentials': user =", "def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): \"\"\" Ensure the", "user=request.user, code=code['code'], expires=expires, redirect_uri=request.redirect_uri, scope=' '.join(request.scopes) ) return request.redirect_uri def", "scopes # Required when authenticating using OAuth2Authentication request.access_token = access_token", "Ensure client is authorized to use the grant_type requested. \"\"\"", "authentication, see `Section 4.3.2`_. - Authorization Code Grant, when Client", "requested. \"\"\" return request.client.redirect_uri_allowed(redirect_uri) def validate_refresh_token(self, refresh_token, client, request, *args,", "the authorization_code is valid and assigned to client. \"\"\" try:", "required to authenticate through other means, such as using HTTP", "request: The HTTP Request (oauthlib.common.Request) \"\"\" if token_type_hint not in", "\"\"\" if self._get_auth_string(request): return True try: if request.client_id and request.client_secret:", "request.client.default_redirect_uri def revoke_token(self, token, token_type_hint, request, *args, **kwargs): \"\"\" Revoke", "using HTTP Basic Authentication method \"\"\" auth_string = self._get_auth_string(request) if", "*args, **kwargs): \"\"\" Persist the authorization_code. \"\"\" expires = timezone.now()", "Basic Authentication method \"\"\" auth_string = self._get_auth_string(request) if not auth_string:", "from 'request'\" Application = get_application_model() try: request.client = request.client or", "is not None and user.is_active: request.user = user return True", "if request.client_id and request.client_secret: return True except AttributeError: # Client", "True return False except AccessToken.DoesNotExist: return False def validate_client_id(self, client_id,", "not authenticated: authenticated = self._authenticate_client_body(request) return authenticated def authenticate_client_id(self, client_id,", "confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args, **kwargs): \"\"\" Ensure client", "_get_application(self, client_id, request): \"\"\" Load application instance for given client_id", "\"\"\" Ensure the authorization_code is valid and assigned to client.", "client, *args, **kwargs): \"\"\" Ensure client is authorized to redirect", "authenticated = self._authenticate_client_basic(request) if not authenticated: authenticated = self._authenticate_client_body(request) return", "the following cases: - Resource Owner Password Credentials Grant, when", "\"\"\" authenticated = self._authenticate_client_basic(request) if not authenticated: authenticated = self._authenticate_client_body(request)", "request.scopes = scopes # Required when authenticating using OAuth2Authentication request.access_token", "def validate_code(self, client_id, code, client, request, *args, **kwargs): \"\"\" Ensure", "return None return auth_string def _authenticate_client_basic(self, request): \"\"\" Try authenticating", "'token': return client.authorization_grant_type == AbstractApplication.GRANT_IMPLICIT else: return False def validate_scopes(self,", "not None and user.is_active: request.user = user return True return", "*args, **kwargs): \"\"\" Get the default scopes for the client.", "except Application.DoesNotExist: return None def _get_auth_string(self, request): auth = request.headers.get('HTTP_AUTHORIZATION',", "the client using values from request body \"\"\" try: client_id", "\"\"\" Revoke an access or refresh token. :param token: The", "request body \"\"\" try: client_id = request.client_id client_secret = request.client_secret", "if response_type == 'code': return client.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE elif response_type", "oauth_api_settings.REFRESH_TOKEN_EXPIRATION is not None: expires = timezone.now() + timedelta(seconds=oauth_api_settings.REFRESH_TOKEN_EXPIRATION) else:", "in token_types.values() if _type != token_type) for other_type in other_types:", "'user').get(token=token) if access_token.is_valid(scopes): request.client = access_token.application request.user = access_token.user request.scopes", "other_types: for token in other_type.objects.filter(token=token, application=request.client): token.revoke() def validate_bearer_token(self, token,", "and Application exists with given client_id. \"\"\" return self._get_application(client_id, request)", "= RefreshToken.objects.select_related('user').get(token=refresh_token) if not rt.is_expired: request.user = rt.user request.refresh_token =", "provided client authentication, see `Section 4.3.2`_. - Authorization Code Grant,", "token_types.get(token_type_hint, AccessToken) try: token_type.objects.get(token=token, application=request.client).revoke() except token_type.DoesNotExist: # Lookup from", "!= token_type) for other_type in other_types: for token in other_type.objects.filter(token=token,", "def save_bearer_token(self, token, request, *args, **kwargs): \"\"\" Persist the Bearer", "or secret not provided pass self._get_application(request.client_id, request) if request.client: return", "request.client or Application.objects.get(client_id=client_id) return request.client except Application.DoesNotExist: return None def", "auth_code.user return True return False except AuthorizationCode.DoesNotExist: return False def", "Check that and Application exists with given client_id. \"\"\" return", "client_secret = request.client_secret except AttributeError: return False if not client_id:", "\"\"\" Invalidate an authorization code after use. \"\"\" auth_code =", "if request.client: return request.client.client_type == AbstractApplication.CLIENT_CONFIDENTIAL return super(OAuthValidator, self).client_authentication_required(request, *args,", "request, *args, **kwargs): \"\"\" Invalidate an authorization code after use.", "AuthorizationCode.objects.get(application=client, code=code) return auth_code.redirect_uri_allowed(redirect_uri) def get_default_redirect_uri(self, client_id, request, *args, **kwargs):", "validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs): \"\"\" Ensure client is", "client, request, *args, **kwargs): \"\"\" Ensure the username and password", "request.refresh_token_object.access_token.scope def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs): \"\"\" Invalidate", "'authorization_code': (AbstractApplication.GRANT_AUTHORIZATION_CODE,), 'password': (AbstractApplication.GRANT_PASSWORD,), 'client_credentials': (AbstractApplication.GRANT_CLIENT_CREDENTIALS,), 'refresh_token': (AbstractApplication.GRANT_AUTHORIZATION_CODE, AbstractApplication.GRANT_PASSWORD, AbstractApplication.GRANT_CLIENT_CREDENTIALS)", "see `Section 4.3.2`_. - Authorization Code Grant, when Client type", "import timezone from oauthlib.oauth2 import RequestValidator from oauth_api.models import get_application_model,", "\"\"\" return request.client.redirect_uri_allowed(redirect_uri) def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs):", "using values from request body \"\"\" try: client_id = request.client_id", "client. \"\"\" authenticated = self._authenticate_client_basic(request) if not authenticated: authenticated =", "return request.client.default_redirect_uri def revoke_token(self, token, token_type_hint, request, *args, **kwargs): \"\"\"", "'Basic': return None return auth_string def _authenticate_client_basic(self, request): \"\"\" Try", "AccessToken.objects.select_related('application', 'user').get(token=token) if access_token.is_valid(scopes): request.client = access_token.application request.user = access_token.user", "except RefreshToken.DoesNotExist: return False def validate_response_type(self, client_id, response_type, client, request,", "self._get_application(client_id, request) is None: return False elif request.client.client_secret != client_secret:", "import authenticate from django.utils import timezone from oauthlib.oauth2 import RequestValidator", "credentials or whenever Client provided client authentication, see `Section 4.3.2`_.", "except AttributeError: encoding = 'utf-8' try: b64_decoded = base64.b64decode(auth_string) except", "Ensure client is authorized to redirect to the redirect_uri requested.", "False else: return True def client_authentication_required(self, request, *args, **kwargs): \"\"\"", "*args, **kwargs): \"\"\" Ensure the authorization_code is valid and assigned", "import oauth_api_settings GRANT_TYPE_MAPPING = { 'authorization_code': (AbstractApplication.GRANT_AUTHORIZATION_CODE,), 'password': (AbstractApplication.GRANT_PASSWORD,), 'client_credentials':", "django.utils import timezone from oauthlib.oauth2 import RequestValidator from oauth_api.models import", "client is one that is not required to authenticate through", "the client using HTTP Basic Authentication method \"\"\" auth_string =", "True try: if request.client_id and request.client_secret: return True except AttributeError:", "RequestValidator from oauth_api.models import get_application_model, AccessToken, AuthorizationCode, RefreshToken, AbstractApplication from", "scope=token['scope'], expires=expires, token=token['access_token'], application=request.client ) if 'refresh_token' in token: if", "token_type = token_types.get(token_type_hint, AccessToken) try: token_type.objects.get(token=token, application=request.client).revoke() except token_type.DoesNotExist: #", "the grant_type requested. \"\"\" assert (grant_type in GRANT_TYPE_MAPPING) return request.client.authorization_grant_type", "username and password is valid. \"\"\" user = authenticate(username=username, password=password)", "client authentication is required in the following cases: - Resource", "{ 'access_token': AccessToken, 'refresh_token': RefreshToken, } token_type = token_types.get(token_type_hint, AccessToken)", "the response_type requested. Authorization Endpoint Response Types registry is not", "\"\"\" Ensure the username and password is valid. \"\"\" user", "is authorized to redirect to the redirect_uri requested. \"\"\" return", "or refresh token. :param token: The token string. :param token_type_hint:", "validate_code(self, client_id, code, client, request, *args, **kwargs): \"\"\" Ensure the", "timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) user = request.user if request.grant_type == 'client_credentials':", "except AttributeError: # Client id or secret not provided pass", "valid. \"\"\" user = authenticate(username=username, password=password) if user is not", "auth_code = AuthorizationCode.objects.get(application=request.client, code=code) auth_code.delete() def save_authorization_code(self, client_id, code, request,", "code=code) auth_code.delete() def save_authorization_code(self, client_id, code, request, *args, **kwargs): \"\"\"", "access to scopes. \"\"\" try: rt = RefreshToken.objects.select_related('user').get(token=refresh_token) if not", "True except AttributeError: # Client id or secret not provided", "request.client: return request.client.client_type == AbstractApplication.CLIENT_CONFIDENTIAL return super(OAuthValidator, self).client_authentication_required(request, *args, **kwargs)", "**kwargs): \"\"\" Ensure client_id belong to a non-confidential client. A", "*args, **kwargs) def authenticate_client(self, request, *args, **kwargs): \"\"\" Try to", "Application exists with given client_id. \"\"\" return self._get_application(client_id, request) is", "issued client credentials or whenever Client provided client authentication, see", "Persist the Bearer token. \"\"\" if request.refresh_token: # Revoke Refresh", "`Section 4.1.3`_. - Refresh Token Grant, when Client type is", "not None: expires = timezone.now() + timedelta(seconds=oauth_api_settings.REFRESH_TOKEN_EXPIRATION) else: expires =", "request): \"\"\" Ensure the Bearer token is valid and authorized", "AuthorizationCode.objects.get(application=request.client, code=code) auth_code.delete() def save_authorization_code(self, client_id, code, request, *args, **kwargs):", "return request.client.default_redirect_uri def get_default_scopes(self, client_id, request, *args, **kwargs): \"\"\" Get", "elif response_type == 'token': return client.authorization_grant_type == AbstractApplication.GRANT_IMPLICIT else: return", "self._get_application(client_id, request) is not None def validate_code(self, client_id, code, client,", "authorization_code. \"\"\" expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION) AuthorizationCode.objects.create( application=request.client, user=request.user,", "else: return True def _authenticate_client_body(self, request): \"\"\" Try authenticating the", "authorized access to requested scopes. \"\"\" return set(scopes).issubset(set(oauth_api_settings.SCOPES.keys())) def validate_user(self,", "scopes for the client. \"\"\" return list(oauth_api_settings.SCOPES.keys()) def get_original_scopes(self, refresh_token,", "using OAuth2Authentication request.access_token = access_token return True return False except", "request.client.client_type == AbstractApplication.CLIENT_CONFIDENTIAL return super(OAuthValidator, self).client_authentication_required(request, *args, **kwargs) def authenticate_client(self,", "if len(splitted) != 2: return None auth_type, auth_string = splitted", "'request'\" Application = get_application_model() try: request.client = request.client or Application.objects.get(client_id=client_id)", "Code Grant, when Client type is Confidential or when Client", "try: rt = RefreshToken.objects.select_related('user').get(token=refresh_token) if not rt.is_expired: request.user = rt.user", "Get the default scopes for the client. \"\"\" return list(oauth_api_settings.SCOPES.keys())", "is Confidential or when Client was issued client credentials or", "None def validate_code(self, client_id, code, client, request, *args, **kwargs): \"\"\"", "return request.redirect_uri def save_bearer_token(self, token, request, *args, **kwargs): \"\"\" Persist", "= auth_code.scope.split(' ') request.user = auth_code.user return True return False", "def save_authorization_code(self, client_id, code, request, *args, **kwargs): \"\"\" Persist the", "Client type is Confidential or when Client was issued client", "= AccessToken.objects.create( user=user, scope=token['scope'], expires=expires, token=token['access_token'], application=request.client ) if 'refresh_token'", "= request.user if request.grant_type == 'client_credentials': user = None access_token", "def authenticate_client_id(self, client_id, request, *args, **kwargs): \"\"\" Ensure client_id belong", "RefreshToken.objects.create( user=request.user, token=token['refresh_token'], expires=expires, application=request.client, access_token=access_token ) return request.client.default_redirect_uri def", "token in other_type.objects.filter(token=token, application=request.client): token.revoke() def validate_bearer_token(self, token, scopes, request):", "Ensure the username and password is valid. \"\"\" user =", "code=code['code'], expires=expires, redirect_uri=request.redirect_uri, scope=' '.join(request.scopes) ) return request.redirect_uri def save_bearer_token(self,", "validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): \"\"\" Ensure client", "client_id, grant_type, client, request, *args, **kwargs): \"\"\" Ensure client is", "'code': return client.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE elif response_type == 'token': return", "**kwargs): \"\"\" Get the default scopes for the client. \"\"\"", "def revoke_token(self, token, token_type_hint, request, *args, **kwargs): \"\"\" Revoke an", "except AttributeError: return False if not client_id: return False if", "Password Credentials Grant, when Client type is Confidential or when", "if self._get_application(client_id, request) is not None: return request.client.client_type != AbstractApplication.CLIENT_CONFIDENTIAL", "request, *args, **kwargs): \"\"\" Get the default redirect URI for", "return None def _get_auth_string(self, request): auth = request.headers.get('HTTP_AUTHORIZATION', None) if", "other_type.objects.filter(token=token, application=request.client): token.revoke() def validate_bearer_token(self, token, scopes, request): \"\"\" Ensure", "A non-confidential client is one that is not required to", "access_token or refresh_token. :param request: The HTTP Request (oauthlib.common.Request) \"\"\"", "{ 'authorization_code': (AbstractApplication.GRANT_AUTHORIZATION_CODE,), 'password': (AbstractApplication.GRANT_PASSWORD,), 'client_credentials': (AbstractApplication.GRANT_CLIENT_CREDENTIALS,), 'refresh_token': (AbstractApplication.GRANT_AUTHORIZATION_CODE, AbstractApplication.GRANT_PASSWORD,", "encoding = 'utf-8' try: b64_decoded = base64.b64decode(auth_string) except (TypeError, binascii.Error):", "'access_token': AccessToken, 'refresh_token': RefreshToken, } token_type = token_types.get(token_type_hint, AccessToken) try:", "= None access_token = AccessToken.objects.create( user=user, scope=token['scope'], expires=expires, token=token['access_token'], application=request.client", "\"\"\" try: client_id = request.client_id client_secret = request.client_secret except AttributeError:", "**kwargs): \"\"\" Revoke an access or refresh token. :param token:", "is valid and authorized access to scopes. \"\"\" try: rt", "== AbstractApplication.GRANT_IMPLICIT else: return False def validate_scopes(self, client_id, scopes, client,", "# Required when authenticating using OAuth2Authentication request.access_token = access_token return", "or 'utf-8' except AttributeError: encoding = 'utf-8' try: b64_decoded =", "def client_authentication_required(self, request, *args, **kwargs): \"\"\" Determine if client authentication", "\"\"\" auth_code = AuthorizationCode.objects.get(application=client, code=code) return auth_code.redirect_uri_allowed(redirect_uri) def get_default_redirect_uri(self, client_id,", "*args, **kwargs): \"\"\" Ensure the Bearer token is valid and", "authenticate from django.utils import timezone from oauthlib.oauth2 import RequestValidator from", "elif request.client.client_secret != client_secret: return False else: return True def", "return False def validate_client_id(self, client_id, request, *args, **kwargs): \"\"\" Check", "= rt.token request.refresh_token_object = rt return rt.application == client return", "Access Token) try: RefreshToken.objects.get(token=request.refresh_token).revoke() except RefreshToken.DoesNotExist: # Already revoked? pass", "splitted = auth.split(' ', 1) if len(splitted) != 2: return", "= None RefreshToken.objects.create( user=request.user, token=token['refresh_token'], expires=expires, application=request.client, access_token=access_token ) return", "username, password, client, request, *args, **kwargs): \"\"\" Ensure the username", "hasattr(request, 'client'), \"'client' attribute missing from 'request'\" Application = get_application_model()", "expires = None RefreshToken.objects.create( user=request.user, token=token['refresh_token'], expires=expires, application=request.client, access_token=access_token )", "\"\"\" if token_type_hint not in ['access_token', 'refresh_token']: token_type_hint = None", "client using values from request body \"\"\" try: client_id =", "**kwargs) def authenticate_client(self, request, *args, **kwargs): \"\"\" Try to authenticate", "Application.objects.get(client_id=client_id) return request.client except Application.DoesNotExist: return None def _get_auth_string(self, request):", "through other means, such as using HTTP Basic. \"\"\" if", "if auth_type != 'Basic': return None return auth_string def _authenticate_client_basic(self,", "splitted if auth_type != 'Basic': return None return auth_string def", "else: expires = None RefreshToken.objects.create( user=request.user, token=token['refresh_token'], expires=expires, application=request.client, access_token=access_token", "\"\"\" Persist the authorization_code. \"\"\" expires = timezone.now() + timedelta(seconds=oauth_api_settings.ACCESS_TOKEN_EXPIRATION)", "def _get_auth_string(self, request): auth = request.headers.get('HTTP_AUTHORIZATION', None) if not auth:", "or Application.objects.get(client_id=client_id) return request.client except Application.DoesNotExist: return None def _get_auth_string(self,", "and request.client_secret: return True except AttributeError: # Client id or", "to authenticate through other means, such as using HTTP Basic.", "save_authorization_code(self, client_id, code, request, *args, **kwargs): \"\"\" Persist the authorization_code.", "= { 'authorization_code': (AbstractApplication.GRANT_AUTHORIZATION_CODE,), 'password': (AbstractApplication.GRANT_PASSWORD,), 'client_credentials': (AbstractApplication.GRANT_CLIENT_CREDENTIALS,), 'refresh_token': (AbstractApplication.GRANT_AUTHORIZATION_CODE,", "\"\"\" Determine if client authentication is required for current request.", "According to the rfc6749, client authentication is required in the", "if not auth_string: return False try: encoding = request.encoding or", "'refresh_token': RefreshToken, } token_type = token_types.get(token_type_hint, AccessToken) try: token_type.objects.get(token=token, application=request.client).revoke()", "access_token.user request.scopes = scopes # Required when authenticating using OAuth2Authentication", "auth_code.delete() def save_authorization_code(self, client_id, code, request, *args, **kwargs): \"\"\" Persist", "type other_types = (_type for _type in token_types.values() if _type", "is valid and authorized access to scopes. \"\"\" if token", "application=request.client ) if 'refresh_token' in token: if oauth_api_settings.REFRESH_TOKEN_EXPIRATION is not", "= b64_decoded.decode(encoding) except UnicodeDecodeError: return False client_id, client_secret = auth_string_decoded.split(':',", "Try authenticating the client using values from request body \"\"\"", "request, *args, **kwargs): \"\"\" Ensure the username and password is", "token_type) for other_type in other_types: for token in other_type.objects.filter(token=token, application=request.client):", "client_id, code, request, *args, **kwargs): \"\"\" Persist the authorization_code. \"\"\"", "return False def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs):", "timedelta from django.contrib.auth import authenticate from django.utils import timezone from", "\"\"\" assert hasattr(request, 'client'), \"'client' attribute missing from 'request'\" Application", "['access_token', 'refresh_token']: token_type_hint = None token_types = { 'access_token': AccessToken,", "scopes, client, request, *args, **kwargs): \"\"\" Ensure the client is", "'client' attribute \"\"\" assert hasattr(request, 'client'), \"'client' attribute missing from", "client authentication is required for current request. According to the", "string. :param token_type_hint: access_token or refresh_token. :param request: The HTTP", "the default redirect URI for the client. \"\"\" return request.client.default_redirect_uri", "AbstractApplication from oauth_api.settings import oauth_api_settings GRANT_TYPE_MAPPING = { 'authorization_code': (AbstractApplication.GRANT_AUTHORIZATION_CODE,),", "request, *args, **kwargs): \"\"\" Ensure the authorization_code is valid and", "after use. \"\"\" auth_code = AuthorizationCode.objects.get(application=request.client, code=code) auth_code.delete() def save_authorization_code(self,", "is valid. \"\"\" user = authenticate(username=username, password=password) if user is", "Authentication method \"\"\" auth_string = self._get_auth_string(request) if not auth_string: return", "= self._authenticate_client_basic(request) if not authenticated: authenticated = self._authenticate_client_body(request) return authenticated", "RefreshToken.objects.get(token=request.refresh_token).revoke() except RefreshToken.DoesNotExist: # Already revoked? pass expires = timezone.now()", "request): \"\"\" Try authenticating the client using values from request", "access_token=access_token ) return request.client.default_redirect_uri def revoke_token(self, token, token_type_hint, request, *args,", "!= 'Basic': return None return auth_string def _authenticate_client_basic(self, request): \"\"\"", "request, *args, **kwargs): \"\"\" Get the default scopes for the", "return list(oauth_api_settings.SCOPES.keys()) def get_original_scopes(self, refresh_token, request, *args, **kwargs): \"\"\" Get", "response_type, client, request, *args, **kwargs): \"\"\" Ensure client is authorized", "the redirect_uri requested. \"\"\" return request.client.redirect_uri_allowed(redirect_uri) def validate_refresh_token(self, refresh_token, client,", "def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs): \"\"\" Invalidate an", "code, request, *args, **kwargs): \"\"\" Persist the authorization_code. \"\"\" expires", "list(oauth_api_settings.SCOPES.keys()) def get_original_scopes(self, refresh_token, request, *args, **kwargs): \"\"\" Get the", "if request.grant_type == 'client_credentials': user = None access_token = AccessToken.objects.create(", "or refresh_token. :param request: The HTTP Request (oauthlib.common.Request) \"\"\" if", "redirect to the redirect_uri requested. \"\"\" return request.client.redirect_uri_allowed(redirect_uri) def validate_refresh_token(self,", "token types except from already looked up type other_types =", "not rt.is_expired: request.user = rt.user request.refresh_token = rt.token request.refresh_token_object =", "validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): \"\"\" Ensure the", "and store it in request as 'client' attribute \"\"\" assert", "return None splitted = auth.split(' ', 1) if len(splitted) !=", "client authentication, see `Section 4.3.2`_. - Authorization Code Grant, when", "token, scopes, request): \"\"\" Ensure the Bearer token is valid", "'utf-8' try: b64_decoded = base64.b64decode(auth_string) except (TypeError, binascii.Error): return False", "*args, **kwargs): \"\"\" Get the list of scopes associated with", "*args, **kwargs): \"\"\" Ensure client is authorized to use the", "# Client id or secret not provided pass self._get_application(request.client_id, request)", "token, request, *args, **kwargs): \"\"\" Persist the Bearer token. \"\"\"", ") return request.client.default_redirect_uri def revoke_token(self, token, token_type_hint, request, *args, **kwargs):", "`Section 6`_ :param request: oauthlib.common.Request :return: True or False \"\"\"", "expires=expires, token=token['access_token'], application=request.client ) if 'refresh_token' in token: if oauth_api_settings.REFRESH_TOKEN_EXPIRATION", "for given client_id and store it in request as 'client'", "return client.authorization_grant_type == AbstractApplication.GRANT_IMPLICIT else: return False def validate_scopes(self, client_id,", "'refresh_token' in token: if oauth_api_settings.REFRESH_TOKEN_EXPIRATION is not None: expires =", "request.refresh_token_object = rt return rt.application == client return False except", "response_type == 'code': return client.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE elif response_type ==", "if access_token.is_valid(scopes): request.client = access_token.application request.user = access_token.user request.scopes =", "authenticate_client(self, request, *args, **kwargs): \"\"\" Try to authenticate the client.", "rfc6749, client authentication is required in the following cases: -", "try: auth_code = AuthorizationCode.objects.select_related('user').get(application=client, code=code) if not auth_code.is_expired: request.scopes =", "client is authorized access to requested scopes. \"\"\" return set(scopes).issubset(set(oauth_api_settings.SCOPES.keys()))", "method \"\"\" auth_string = self._get_auth_string(request) if not auth_string: return False", "AuthorizationCode.DoesNotExist: return False def validate_grant_type(self, client_id, grant_type, client, request, *args,", "save_bearer_token(self, token, request, *args, **kwargs): \"\"\" Persist the Bearer token.", "client_id, redirect_uri, request, *args, **kwargs): \"\"\" Ensure client is authorized", "authenticating the client using HTTP Basic Authentication method \"\"\" auth_string", "refresh_token, client, request, *args, **kwargs): \"\"\" Ensure the Bearer token", "4.1.3`_. - Refresh Token Grant, when Client type is Confidential", "= self._get_auth_string(request) if not auth_string: return False try: encoding =", "application=request.client).revoke() except token_type.DoesNotExist: # Lookup from all token types except", "\"\"\" Persist the Bearer token. \"\"\" if request.refresh_token: # Revoke", "request.encoding or 'utf-8' except AttributeError: encoding = 'utf-8' try: b64_decoded", "client. \"\"\" return request.client.default_redirect_uri def get_default_scopes(self, client_id, request, *args, **kwargs):", "validate_user(self, username, password, client, request, *args, **kwargs): \"\"\" Ensure the", "== 'code': return client.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE elif response_type == 'token':", "set(scopes).issubset(set(oauth_api_settings.SCOPES.keys())) def validate_user(self, username, password, client, request, *args, **kwargs): \"\"\"", "**kwargs): \"\"\" Ensure the username and password is valid. \"\"\"", "auth: return None splitted = auth.split(' ', 1) if len(splitted)", "required for current request. According to the rfc6749, client authentication", "except (TypeError, binascii.Error): return False try: auth_string_decoded = b64_decoded.decode(encoding) except", "if client authentication is required for current request. According to", "token_type.DoesNotExist: # Lookup from all token types except from already", "\"\"\" return request.refresh_token_object.access_token.scope def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs):", "to scopes. \"\"\" try: rt = RefreshToken.objects.select_related('user').get(token=refresh_token) if not rt.is_expired:", "False except RefreshToken.DoesNotExist: return False def validate_response_type(self, client_id, response_type, client,", "client is authorized to redirect to the redirect_uri requested. \"\"\"", "\"\"\" assert (grant_type in GRANT_TYPE_MAPPING) return request.client.authorization_grant_type in GRANT_TYPE_MAPPING[grant_type] def", "return request.client.client_type == AbstractApplication.CLIENT_CONFIDENTIAL return super(OAuthValidator, self).client_authentication_required(request, *args, **kwargs) def", "requested. Authorization Endpoint Response Types registry is not supported. See", "request, *args, **kwargs): \"\"\" Try to authenticate the client. \"\"\"", "not provided pass self._get_application(request.client_id, request) if request.client: return request.client.client_type ==", "Get the list of scopes associated with the refresh token.", "client credentials or whenever Client provided client authentication, see `Section", "timezone from oauthlib.oauth2 import RequestValidator from oauth_api.models import get_application_model, AccessToken,", "Application = get_application_model() try: request.client = request.client or Application.objects.get(client_id=client_id) return", "request.client_id and request.client_secret: return True except AttributeError: # Client id", "== AbstractApplication.CLIENT_CONFIDENTIAL return super(OAuthValidator, self).client_authentication_required(request, *args, **kwargs) def authenticate_client(self, request,", "requested. \"\"\" assert (grant_type in GRANT_TYPE_MAPPING) return request.client.authorization_grant_type in GRANT_TYPE_MAPPING[grant_type]", "is required in the following cases: - Resource Owner Password", "'.join(request.scopes) ) return request.redirect_uri def save_bearer_token(self, token, request, *args, **kwargs):", "AbstractApplication.CLIENT_CONFIDENTIAL return super(OAuthValidator, self).client_authentication_required(request, *args, **kwargs) def authenticate_client(self, request, *args,", "Ensure the Bearer token is valid and authorized access to", "to scopes. \"\"\" if token is None: return False try:", "scopes associated with the refresh token. \"\"\" return request.refresh_token_object.access_token.scope def", "= rt.user request.refresh_token = rt.token request.refresh_token_object = rt return rt.application", "None auth_type, auth_string = splitted if auth_type != 'Basic': return", "', 1) if len(splitted) != 2: return None auth_type, auth_string", "request.client_id client_secret = request.client_secret except AttributeError: return False if not", "!= AbstractApplication.CLIENT_CONFIDENTIAL return False def confirm_redirect_uri(self, client_id, code, redirect_uri, client,", "== 'token': return client.authorization_grant_type == AbstractApplication.GRANT_IMPLICIT else: return False def", "self).client_authentication_required(request, *args, **kwargs) def authenticate_client(self, request, *args, **kwargs): \"\"\" Try", "the Bearer token is valid and authorized access to scopes.", "given client_id and store it in request as 'client' attribute", "not required to authenticate through other means, such as using", "exists with given client_id. \"\"\" return self._get_application(client_id, request) is not", "one that is not required to authenticate through other means,", "False try: encoding = request.encoding or 'utf-8' except AttributeError: encoding", "self._authenticate_client_basic(request) if not authenticated: authenticated = self._authenticate_client_body(request) return authenticated def", "client_id: return False if self._get_application(client_id, request) is None: return False", "token. \"\"\" return request.refresh_token_object.access_token.scope def invalidate_authorization_code(self, client_id, code, request, *args,", "*args, **kwargs): \"\"\" Revoke an access or refresh token. :param", "Client provided client authentication, see `Section 4.3.2`_. - Authorization Code", "try: token_type.objects.get(token=token, application=request.client).revoke() except token_type.DoesNotExist: # Lookup from all token", "oauthlib.oauth2 import RequestValidator from oauth_api.models import get_application_model, AccessToken, AuthorizationCode, RefreshToken,", "current request. According to the rfc6749, client authentication is required", "\"\"\" if request.refresh_token: # Revoke Refresh Token (and related Access", "not in ['access_token', 'refresh_token']: token_type_hint = None token_types = {", "from oauth_api.models import get_application_model, AccessToken, AuthorizationCode, RefreshToken, AbstractApplication from oauth_api.settings", "from datetime import timedelta from django.contrib.auth import authenticate from django.utils", "**kwargs): \"\"\" Get the default redirect URI for the client.", "rt.token request.refresh_token_object = rt return rt.application == client return False", "the client. \"\"\" return request.client.default_redirect_uri def get_default_scopes(self, client_id, request, *args,", "client_id, request, *args, **kwargs): \"\"\" Get the default scopes for", "if token is None: return False try: access_token = AccessToken.objects.select_related('application',", "request.client = access_token.application request.user = access_token.user request.scopes = scopes #", "**kwargs): \"\"\" Ensure the authorization_code is valid and assigned to", "token is valid and authorized access to scopes. \"\"\" try:", "request.redirect_uri def save_bearer_token(self, token, request, *args, **kwargs): \"\"\" Persist the", "return set(scopes).issubset(set(oauth_api_settings.SCOPES.keys())) def validate_user(self, username, password, client, request, *args, **kwargs):", "other_types = (_type for _type in token_types.values() if _type !=", "= self._authenticate_client_body(request) return authenticated def authenticate_client_id(self, client_id, request, *args, **kwargs):", "True return False except AuthorizationCode.DoesNotExist: return False def validate_grant_type(self, client_id,", "**kwargs): \"\"\" Ensure client is authorized to use the grant_type", "**kwargs): \"\"\" Invalidate an authorization code after use. \"\"\" auth_code", "False client_id, client_secret = auth_string_decoded.split(':', 1) if self._get_application(client_id, request) is", "auth_string_decoded.split(':', 1) if self._get_application(client_id, request) is None: return False elif", "False try: access_token = AccessToken.objects.select_related('application', 'user').get(token=token) if access_token.is_valid(scopes): request.client =", "Ensure the client is authorized access to requested scopes. \"\"\"", "client return False except RefreshToken.DoesNotExist: return False def validate_response_type(self, client_id,", "return False def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs):", "token=token['refresh_token'], expires=expires, application=request.client, access_token=access_token ) return request.client.default_redirect_uri def revoke_token(self, token,", "\"\"\" Check that and Application exists with given client_id. \"\"\"", "expires=expires, redirect_uri=request.redirect_uri, scope=' '.join(request.scopes) ) return request.redirect_uri def save_bearer_token(self, token,", "is valid and assigned to client. \"\"\" try: auth_code =", "request) if request.client: return request.client.client_type == AbstractApplication.CLIENT_CONFIDENTIAL return super(OAuthValidator, self).client_authentication_required(request," ]
[ "3] y = modify(x) print(\"x == y\", x == y)", "== y\", x == y) print(\"x == y\", x is", "= [1, 2, 3] y = modify(x) print(\"x == y\",", "y\", x == y) print(\"x == y\", x is y)", "return y # returns same reference. No new object is", "modify(y): return y # returns same reference. No new object", "object is created x = [1, 2, 3] y =", "2, 3] y = modify(x) print(\"x == y\", x ==", "is created x = [1, 2, 3] y = modify(x)", "def modify(y): return y # returns same reference. No new", "No new object is created x = [1, 2, 3]", "same reference. No new object is created x = [1,", "x = [1, 2, 3] y = modify(x) print(\"x ==", "y = modify(x) print(\"x == y\", x == y) print(\"x", "[1, 2, 3] y = modify(x) print(\"x == y\", x", "# returns same reference. No new object is created x", "modify(x) print(\"x == y\", x == y) print(\"x == y\",", "returns same reference. No new object is created x =", "reference. No new object is created x = [1, 2,", "created x = [1, 2, 3] y = modify(x) print(\"x", "= modify(x) print(\"x == y\", x == y) print(\"x ==", "y # returns same reference. No new object is created", "print(\"x == y\", x == y) print(\"x == y\", x", "new object is created x = [1, 2, 3] y" ]
[ "import _write_comp_video from edx_gen import _xml_google_doc from edx_gen import _markdown", "meta_tag settings = _read_metadata.getMetaSettings( md_filepath, meta_tag, _edx_consts.COMP_VIDEO_REQ, _edx_consts.COMP_VIDEO_OPT ) #", "setting is not recognised:', md_filepath) print(WARNING, ' Found:', comp_type) print(WARNING,", "return the component tag instead return _xml_google_doc.tagForGoogleDocComp(comp_filename, settings, unit_filename) else:", "blank') # get the type for this component comp_type =", ".xml file to COMP_HTML_FOLDER # return the list of files", "have settings if not settings: print(WARNING, 'There seem to be", "the h1 tags h1_tags = list(tree_snippet.iter('h1')) if len(h1_tags) == 0:", "== 0: print(WARNING, 'The snippet does not start with any", "to either units folder or problems folder, depending on the", "_markdown.convertMd(md_filepath) # check we have at least 2 snippets, the", "meta_text != 'UNIT': # print(WARNING, 'The markdown file must start", "type def _writeFilesForSnippet(md_filepath, comp_filename, tree_snippet, unit_filename, unit_display_name): meta_tag = None", "print(WARNING, 'The markdown file does not seem to contain any", "snippets, the header and one component if len(tree_snippets) <= 1:", "the snippet meta_tag = h1_tags[0] # the first h1 the", "options:', _edx_consts.METADATA_ENUMS['type']) # write xml and/or html files if comp_type", "# return the list of files return _write_comp_video.writeXmlForVidComp( md_filepath, comp_filename,", "check the meta tag text # meta_text = meta_tag.text.strip() #", "None comp_type = None # meta_text = None # get", "setting out of the meta_tag settings = _read_metadata.getMetaSettings( md_filepath, meta_tag,", "setting out of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_HTML_REQ,", "to COMP_HTML_FOLDER # return the list of files return _write_comp_html.writeXmlForHtmlComp(", "comp_type == 'google-doc': print(\" |_ GOOGLE DOC COMP\") # get", "have at least 2 snippets, the header and one component", "component_path) # generate the files in the right folders tree_snippets", "to COMP_VIDS_FOLDER # for each language # write .html file", "line of the markdown file is blank') # get the", "be no settings for this \"problem-checkboxes\" component:', md_filepath) return #", "unit_display_name = first_h1_tag.get('display_name') # list to store all files unit_comps", "unit_filename, unit_display_name) unit_comps.extend(comp_files) # return the result return unit_comps #--------------------------------------------------------------------------------------------------", "meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_PROB_QUIZ_REQ, _edx_consts.COMP_PROB_QUIZ_OPT ) # check", "_read_metadata.getMetaSettings( md_filepath, meta_tag, _edx_consts.COMP_VIDEO_REQ, _edx_consts.COMP_VIDEO_OPT ) # check that we", "of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_HTML_REQ, _edx_consts.COMP_HTML_OPT )", "\"problem-checkboxes\" component:', md_filepath) return # remove h1 meta_tag from the", "__SETTINGS__ #-------------------------------------------------------------------------------------------------- # Text strings WARNING = \" WARNING:\" #--------------------------------------------------------------------------------------------------", "unit_filename) elif comp_type == 'google-doc': print(\" |_ GOOGLE DOC COMP\")", "== 'video': print(\" |_ VIDEO COMP\") # get the setting", "write .xml file to COMP_HTML_FOLDER # return the list of", "meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_GOOGLE_DOC_REQ, _edx_consts.COMP_GOOGLE_DOC_OPT) # check that", "component if len(tree_snippets) <= 1: print(WARNING, 'The markdown file does", "to COMP_HTML_FOLDER # return the list of files return _write_comp_video.writeXmlForVidComp(", "+ str(i) comp_files = _writeFilesForSnippet(md_filepath, new_filename, tree_snippet, unit_filename, unit_display_name) unit_comps.extend(comp_files)", "for this component comp_type = meta_tag.get('type') if comp_type == None", "print(WARNING, 'The markdown file must start with the \"UNIT\" settings:',", "the markdown file is blank') # get the type for", "WARNING:\" #-------------------------------------------------------------------------------------------------- # write to either units folder or problems", "this \"video\" component:', md_filepath) return # remove h1 meta_tag from", "unit_filename + '_c' + str(i) comp_files = _writeFilesForSnippet(md_filepath, new_filename, tree_snippet,", "the tree so it does not end up in the", "recognised:', md_filepath) print(WARNING, ' Found:', comp_type) print(WARNING, ' Valid options:',", "= [] # process components for i in range(1, len(tree_snippets)):", "xml and/or html files if comp_type == 'html': print(\" |_", "is not recognised:', md_filepath) print(WARNING, ' Found:', comp_type) print(WARNING, '", "'There seem to be no settings for this \"problem-checkboxes\" component:',", "1: print(WARNING, 'The markdown file does not seem to contain", "the setting out of the meta_tag settings = _read_metadata.getMetaSettings( md_filepath,", "|_ GOOGLE DOC COMP\") # get the setting out of", "== 'html': print(\" |_ HTML COMP\") # get the setting", "output tree_snippet.remove(meta_tag) # write .xml file to COMP_VIDS_FOLDER # for", "the type def writeCompsForUnit(md_filepath, unit_filename): # print(\"component_path\", component_path) # generate", "the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_GOOGLE_DOC_REQ, _edx_consts.COMP_GOOGLE_DOC_OPT) # check", "output tree_snippet.remove(meta_tag) # write .xml file to COMP_PROBS_FOLDER # return", "settings, unit_filename) elif comp_type == 'video': print(\" |_ VIDEO COMP\")", "file to COMP_HTML_FOLDER # return the list of files return", "settings, unit_filename) elif comp_type == 'problem-checkboxes': print(\" |_ PROBLEM CHECKBOXES\")", "to be no settings for this \"html\" component:', md_filepath) return", "list of files return _write_comp_html.writeXmlForHtmlComp( md_filepath, comp_filename, tree_snippet, settings, unit_filename)", "from edx_gen import _write_structure from edx_gen import _write_comps from edx_gen", "if len(tree_snippets) <= 1: print(WARNING, 'The markdown file does not", "markdown file must start with the \"UNIT\" settings:', component_path) #", "unit_filename): # print(\"component_path\", component_path) # generate the files in the", "edx_gen import _write_comp_checkboxes from edx_gen import _write_comp_video from edx_gen import", "unit_comps.extend(comp_files) # return the result return unit_comps #-------------------------------------------------------------------------------------------------- # write", "unit_filename, unit_display_name): meta_tag = None comp_type = None # meta_text", "h1 tags h1_tags = list(tree_snippet.iter('h1')) if len(h1_tags) == 0: print(WARNING,", "return # in this case, no files are written #", "\"type\" setting is not recognised:', md_filepath) print(WARNING, ' Found:', comp_type)", "_write_comp_video from edx_gen import _xml_google_doc from edx_gen import _markdown from", "output tree_snippet.remove(meta_tag) # write .html file to COMP_HTML_FOLDER # write", "start with the \"UNIT\" settings:', component_path) # print(WARNING, 'Make sure", "# write .xml file to COMP_VIDS_FOLDER # for each language", "of files return _write_comp_checkboxes.writeXmlForProbCheckboxesComp( md_filepath, comp_filename, tree_snippet, settings, unit_filename) elif", "+ '_c' + str(i) comp_files = _writeFilesForSnippet(md_filepath, new_filename, tree_snippet, unit_filename,", "depending on the type def writeCompsForUnit(md_filepath, unit_filename): # print(\"component_path\", component_path)", "tree_snippet.remove(meta_tag) # write .html file to COMP_HTML_FOLDER # write .xml", "'google-doc': print(\" |_ GOOGLE DOC COMP\") # get the setting", "units folder or problems folder, depending on the type def", "= _read_metadata.getMetaSettings( md_filepath, meta_tag, _edx_consts.COMP_VIDEO_REQ, _edx_consts.COMP_VIDEO_OPT ) # check that", "or problems folder, depending on the type def _writeFilesForSnippet(md_filepath, comp_filename,", "that the first line of the markdown file is blank')", "out of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_PROB_QUIZ_REQ, _edx_consts.COMP_PROB_QUIZ_OPT", "str(i) comp_files = _writeFilesForSnippet(md_filepath, new_filename, tree_snippet, unit_filename, unit_display_name) unit_comps.extend(comp_files) #", "this component comp_type = meta_tag.get('type') if comp_type == None or", "header and one component if len(tree_snippets) <= 1: print(WARNING, 'The", "== None or meta_text != 'UNIT': # print(WARNING, 'The markdown", "md_filepath, comp_filename, tree_snippet, settings, unit_filename) elif comp_type == 'problem-checkboxes': print(\"", "md_filepath) return # in this case, no files are written", "snippet does not start with any settings:', md_filepath) return #", "meta tag for the snippet meta_tag = h1_tags[0] # the", "result return unit_comps #-------------------------------------------------------------------------------------------------- # write to either units folder", "snippet meta_tag = h1_tags[0] # the first h1 the should", "are written # we return the component tag instead return", "_write_comp_html.writeXmlForHtmlComp( md_filepath, comp_filename, tree_snippet, settings, unit_filename) elif comp_type == 'problem-checkboxes':", "no settings for this \"video\" component:', md_filepath) return # remove", "in the output tree_snippet.remove(meta_tag) # write .xml file to COMP_PROBS_FOLDER", "# check the meta tag text # meta_text = meta_tag.text.strip()", "print(WARNING, 'There seem to be no settings for this \"Google", "h1_tags = list(tree_snippet.iter('h1')) if len(h1_tags) == 0: print(WARNING, 'The snippet", "_edx_consts.METADATA_ENUMS['type']: print(WARNING, 'The \"type\" setting is not recognised:', md_filepath) print(WARNING,", "file to COMP_VIDS_FOLDER # for each language # write .html", "'The markdown file must start with the \"UNIT\" settings:', component_path)", "in _edx_consts.METADATA_ENUMS['type']: print(WARNING, 'The \"type\" setting is not recognised:', md_filepath)", ".html file to COMP_HTML_FOLDER # write .xml file to COMP_HTML_FOLDER", "== None or comp_type not in _edx_consts.METADATA_ENUMS['type']: print(WARNING, 'The \"type\"", "= h1_tags[0] # the first h1 the should contain the", "if not settings: print(WARNING, 'There seem to be no settings", "the output tree_snippet.remove(meta_tag) # write .xml file to COMP_PROBS_FOLDER #", "edx_gen import _edx_consts from edx_gen import _read_metadata from edx_gen import", "component tag instead return _xml_google_doc.tagForGoogleDocComp(comp_filename, settings, unit_filename) else: print(WARNING, 'Component", "_write_comp_checkboxes.writeXmlForProbCheckboxesComp( md_filepath, comp_filename, tree_snippet, settings, unit_filename) elif comp_type == 'video':", "file to COMP_PROBS_FOLDER # return the list of files return", "sure that the first line of the markdown file is", "must start with the \"UNIT\" settings:', component_path) # print(WARNING, 'Make", "from edx_gen import _xml_google_doc from edx_gen import _markdown from edx_gen", "return _xml_google_doc.tagForGoogleDocComp(comp_filename, settings, unit_filename) else: print(WARNING, 'Component type not recognised:',", "get the meta tag for the snippet meta_tag = h1_tags[0]", "'_c' + str(i) comp_files = _writeFilesForSnippet(md_filepath, new_filename, tree_snippet, unit_filename, unit_display_name)", "meta_text = None # get the h1 tags h1_tags =", "no files are written # we return the component tag", "elif comp_type == 'google-doc': print(\" |_ GOOGLE DOC COMP\") #", "print(WARNING, ' Found:', comp_type) print(WARNING, ' Valid options:', _edx_consts.METADATA_ENUMS['type']) #", "= list(tree_snippet.iter('h1')) if len(h1_tags) == 0: print(WARNING, 'The snippet does", "the list of files return _write_comp_checkboxes.writeXmlForProbCheckboxesComp( md_filepath, comp_filename, tree_snippet, settings,", "the first line of the markdown file is blank') #", "Valid options:', _edx_consts.METADATA_ENUMS['type']) # write xml and/or html files if", "COMP_HTML_FOLDER # return the list of files return _write_comp_video.writeXmlForVidComp( md_filepath,", "' Found:', comp_type) print(WARNING, ' Valid options:', _edx_consts.METADATA_ENUMS['type']) # write", "|_ PROBLEM CHECKBOXES\") # get the setting out of the", "print(\" |_ GOOGLE DOC COMP\") # get the setting out", "os import tarfile import shutil from edx_gen import _edx_consts from", "tree_snippet = tree_snippets[i] # generate the files new_filename = unit_filename", "COMP_HTML_FOLDER # write .xml file to COMP_HTML_FOLDER # return the", "generate the files new_filename = unit_filename + '_c' + str(i)", "the meta_tag settings = _read_metadata.getMetaSettings( md_filepath, meta_tag, _edx_consts.COMP_VIDEO_REQ, _edx_consts.COMP_VIDEO_OPT )", "end up in the output tree_snippet.remove(meta_tag) # write .html file", "_edx_consts.COMP_VIDEO_REQ, _edx_consts.COMP_VIDEO_OPT ) # check that we have settings if", "check we have at least 2 snippets, the header and", "print(\" |_ HTML COMP\") # get the setting out of", "return the list of files return _write_comp_video.writeXmlForVidComp( md_filepath, comp_filename, settings,", "not seem to contain any components:', md_filepath) # get the", "components for i in range(1, len(tree_snippets)): tree_snippet = tree_snippets[i] #", "= _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_PROB_QUIZ_REQ, _edx_consts.COMP_PROB_QUIZ_OPT ) # check that we", "None or meta_text != 'UNIT': # print(WARNING, 'The markdown file", "settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_HTML_REQ, _edx_consts.COMP_HTML_OPT ) # check that", "_edx_consts.COMP_PROB_QUIZ_OPT ) # check that we have settings if not", "meta data # # check the meta tag text #", "data # # check the meta tag text # meta_text", "of the meta_tag settings = _read_metadata.getMetaSettings( md_filepath, meta_tag, _edx_consts.COMP_VIDEO_REQ, _edx_consts.COMP_VIDEO_OPT", "the component tag instead return _xml_google_doc.tagForGoogleDocComp(comp_filename, settings, unit_filename) else: print(WARNING,", "COMP\") # get the setting out of the meta_tag settings", "h1 the should contain the meta data # # check", "problems folder, depending on the type def _writeFilesForSnippet(md_filepath, comp_filename, tree_snippet,", "h1 meta_tag from the tree so it does not end", "edx_gen import _write_comps from edx_gen import _write_comp_html from edx_gen import", "type for this component comp_type = meta_tag.get('type') if comp_type ==", "import __SETTINGS__ #-------------------------------------------------------------------------------------------------- # Text strings WARNING = \" WARNING:\"", "# generate the files new_filename = unit_filename + '_c' +", "the result return unit_comps #-------------------------------------------------------------------------------------------------- # write to either units", "len(h1_tags) == 0: print(WARNING, 'The snippet does not start with", "files return _write_comp_html.writeXmlForHtmlComp( md_filepath, comp_filename, tree_snippet, settings, unit_filename) elif comp_type", "None or comp_type not in _edx_consts.METADATA_ENUMS['type']: print(WARNING, 'The \"type\" setting", "# get the meta tag for the snippet meta_tag =", "_edx_consts from edx_gen import _read_metadata from edx_gen import _write_structure from", "meta_text = meta_tag.text.strip() # if meta_text == None or meta_text", "not start with any settings:', md_filepath) return # get the", "PROBLEM CHECKBOXES\") # get the setting out of the meta_tag", "= _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_HTML_REQ, _edx_consts.COMP_HTML_OPT ) # check that we", "= _markdown.convertMd(md_filepath) # check we have at least 2 snippets,", "_writeFilesForSnippet(md_filepath, comp_filename, tree_snippet, unit_filename, unit_display_name): meta_tag = None comp_type =", "we have settings if not settings: print(WARNING, 'There seem to", "_read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_GOOGLE_DOC_REQ, _edx_consts.COMP_GOOGLE_DOC_OPT) # check that we have settings", "'UNIT': # print(WARNING, 'The markdown file must start with the", "Doc\" component:', md_filepath) return # in this case, no files", "meta_tag, _edx_consts.COMP_HTML_REQ, _edx_consts.COMP_HTML_OPT ) # check that we have settings", "'problem-checkboxes': print(\" |_ PROBLEM CHECKBOXES\") # get the setting out", "markdown file does not seem to contain any components:', md_filepath)", "print(WARNING, 'The \"type\" setting is not recognised:', md_filepath) print(WARNING, '", "least 2 snippets, the header and one component if len(tree_snippets)", "of the unit first_h1_tag = list(tree_snippets[0].iter('h1'))[0] unit_display_name = first_h1_tag.get('display_name') #", "write .xml file to COMP_VIDS_FOLDER # for each language #", "# get the h1 tags h1_tags = list(tree_snippet.iter('h1')) if len(h1_tags)", "comp_filename, tree_snippet, unit_filename, unit_display_name): meta_tag = None comp_type = None", "the should contain the meta data # # check the", "unit_filename) else: print(WARNING, 'Component type not recognised:', comp_type, \"in\", md_filepath)", "# print(WARNING, 'The markdown file must start with the \"UNIT\"", "= tree_snippets[i] # generate the files new_filename = unit_filename +", "import sys, os import tarfile import shutil from edx_gen import", "does not end up in the output tree_snippet.remove(meta_tag) # write", "_edx_consts.METADATA_ENUMS['type']) # write xml and/or html files if comp_type ==", "file to COMP_HTML_FOLDER # write .xml file to COMP_HTML_FOLDER #", "case, no files are written # we return the component", "first h1 the should contain the meta data # #", "right folders tree_snippets = _markdown.convertMd(md_filepath) # check we have at", "component_path) # print(WARNING, 'Make sure that the first line of", "print(WARNING, 'Make sure that the first line of the markdown", "list of files return _write_comp_checkboxes.writeXmlForProbCheckboxesComp( md_filepath, comp_filename, tree_snippet, settings, unit_filename)", "md_filepath) return # get the meta tag for the snippet", "or problems folder, depending on the type def writeCompsForUnit(md_filepath, unit_filename):", "settings:', md_filepath) return # get the meta tag for the", "# write .xml file to COMP_HTML_FOLDER # return the list", "meta_tag, _edx_consts.COMP_VIDEO_REQ, _edx_consts.COMP_VIDEO_OPT ) # check that we have settings", "list of files return _write_comp_video.writeXmlForVidComp( md_filepath, comp_filename, settings, unit_filename) elif", "display name of the unit first_h1_tag = list(tree_snippets[0].iter('h1'))[0] unit_display_name =", "seem to contain any components:', md_filepath) # get the display", "any components:', md_filepath) # get the display name of the", "_util import __SETTINGS__ #-------------------------------------------------------------------------------------------------- # Text strings WARNING = \"", "# return the result return unit_comps #-------------------------------------------------------------------------------------------------- # write to", "sys, os import tarfile import shutil from edx_gen import _edx_consts", "text # meta_text = meta_tag.text.strip() # if meta_text == None", "# we return the component tag instead return _xml_google_doc.tagForGoogleDocComp(comp_filename, settings,", "'video': print(\" |_ VIDEO COMP\") # get the setting out", "the setting out of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag,", "_markdown from edx_gen import _util import __SETTINGS__ #-------------------------------------------------------------------------------------------------- # Text", "tag for the snippet meta_tag = h1_tags[0] # the first", "_edx_consts.COMP_HTML_OPT ) # check that we have settings if not", "# check that we have settings if not settings: print(WARNING,", "not settings: print(WARNING, 'There seem to be no settings for", "= None comp_type = None # meta_text = None #", "remove h1 meta_tag from the tree so it does not", "unit_comps = [] # process components for i in range(1,", "this \"html\" component:', md_filepath) return # remove h1 meta_tag from", "[] # process components for i in range(1, len(tree_snippets)): tree_snippet", "no settings for this \"html\" component:', md_filepath) return # remove", "unit_display_name): meta_tag = None comp_type = None # meta_text =", "|_ VIDEO COMP\") # get the setting out of the", "comp_type = meta_tag.get('type') if comp_type == None or comp_type not", "unit first_h1_tag = list(tree_snippets[0].iter('h1'))[0] unit_display_name = first_h1_tag.get('display_name') # list to", "component comp_type = meta_tag.get('type') if comp_type == None or comp_type", "files in the right folders tree_snippets = _markdown.convertMd(md_filepath) # check", "' Valid options:', _edx_consts.METADATA_ENUMS['type']) # write xml and/or html files", "and/or html files if comp_type == 'html': print(\" |_ HTML", "to COMP_PROBS_FOLDER # return the list of files return _write_comp_checkboxes.writeXmlForProbCheckboxesComp(", "language # write .html file to COMP_HTML_FOLDER # write .xml", "meta_tag.get('type') if comp_type == None or comp_type not in _edx_consts.METADATA_ENUMS['type']:", "the meta data # # check the meta tag text", "# # check the meta tag text # meta_text =", "the right folders tree_snippets = _markdown.convertMd(md_filepath) # check we have", "# meta_text = meta_tag.text.strip() # if meta_text == None or", "be no settings for this \"video\" component:', md_filepath) return #", "= meta_tag.get('type') if comp_type == None or comp_type not in", "settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_PROB_QUIZ_REQ, _edx_consts.COMP_PROB_QUIZ_OPT ) # check that", "not in _edx_consts.METADATA_ENUMS['type']: print(WARNING, 'The \"type\" setting is not recognised:',", "comp_type == 'html': print(\" |_ HTML COMP\") # get the", "comp_filename, tree_snippet, settings, unit_filename) elif comp_type == 'video': print(\" |_", "_read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_PROB_QUIZ_REQ, _edx_consts.COMP_PROB_QUIZ_OPT ) # check that we have", "seem to be no settings for this \"html\" component:', md_filepath)", "folder or problems folder, depending on the type def _writeFilesForSnippet(md_filepath,", "i in range(1, len(tree_snippets)): tree_snippet = tree_snippets[i] # generate the", "should contain the meta data # # check the meta", "# process components for i in range(1, len(tree_snippets)): tree_snippet =", "# return the list of files return _write_comp_checkboxes.writeXmlForProbCheckboxesComp( md_filepath, comp_filename,", "return _write_comp_video.writeXmlForVidComp( md_filepath, comp_filename, settings, unit_filename) elif comp_type == 'google-doc':", "seem to be no settings for this \"problem-checkboxes\" component:', md_filepath)", "tree_snippets = _markdown.convertMd(md_filepath) # check we have at least 2", "_edx_consts.COMP_PROB_QUIZ_REQ, _edx_consts.COMP_PROB_QUIZ_OPT ) # check that we have settings if", "# get the display name of the unit first_h1_tag =", "out of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_HTML_REQ, _edx_consts.COMP_HTML_OPT", "tarfile import shutil from edx_gen import _edx_consts from edx_gen import", "from edx_gen import _markdown from edx_gen import _util import __SETTINGS__", "name of the unit first_h1_tag = list(tree_snippets[0].iter('h1'))[0] unit_display_name = first_h1_tag.get('display_name')", "components:', md_filepath) # get the display name of the unit", "print(WARNING, 'There seem to be no settings for this \"video\"", "VIDEO COMP\") # get the setting out of the meta_tag", "tree_snippets[i] # generate the files new_filename = unit_filename + '_c'", "from edx_gen import _util import __SETTINGS__ #-------------------------------------------------------------------------------------------------- # Text strings", "we have at least 2 snippets, the header and one", "settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_GOOGLE_DOC_REQ, _edx_consts.COMP_GOOGLE_DOC_OPT) # check that we", "tree_snippet, unit_filename, unit_display_name): meta_tag = None comp_type = None #", "component:', md_filepath) return # remove h1 meta_tag from the tree", "import _xml_google_doc from edx_gen import _markdown from edx_gen import _util", "new_filename, tree_snippet, unit_filename, unit_display_name) unit_comps.extend(comp_files) # return the result return", "# write .xml file to COMP_PROBS_FOLDER # return the list", "problems folder, depending on the type def writeCompsForUnit(md_filepath, unit_filename): #", "folders tree_snippets = _markdown.convertMd(md_filepath) # check we have at least", "on the type def _writeFilesForSnippet(md_filepath, comp_filename, tree_snippet, unit_filename, unit_display_name): meta_tag", "md_filepath, comp_filename, tree_snippet, settings, unit_filename) elif comp_type == 'video': print(\"", "# write to either units folder or problems folder, depending", "# for each language # write .html file to COMP_HTML_FOLDER", "return the list of files return _write_comp_checkboxes.writeXmlForProbCheckboxesComp( md_filepath, comp_filename, tree_snippet,", ") # check that we have settings if not settings:", "store all files unit_comps = [] # process components for", "get the setting out of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath,", "not end up in the output tree_snippet.remove(meta_tag) # write .xml", "with the \"UNIT\" settings:', component_path) # print(WARNING, 'Make sure that", "is blank') # get the type for this component comp_type", "md_filepath) return # remove h1 meta_tag from the tree so", "up in the output tree_snippet.remove(meta_tag) # write .html file to", "of files return _write_comp_html.writeXmlForHtmlComp( md_filepath, comp_filename, tree_snippet, settings, unit_filename) elif", "seem to be no settings for this \"Google Doc\" component:',", "None # meta_text = None # get the h1 tags", "settings, unit_filename) elif comp_type == 'google-doc': print(\" |_ GOOGLE DOC", "be no settings for this \"Google Doc\" component:', md_filepath) return", "print(WARNING, 'The snippet does not start with any settings:', md_filepath)", "tags h1_tags = list(tree_snippet.iter('h1')) if len(h1_tags) == 0: print(WARNING, 'The", "generate the files in the right folders tree_snippets = _markdown.convertMd(md_filepath)", "_write_structure from edx_gen import _write_comps from edx_gen import _write_comp_html from", "edx_gen import _write_comp_video from edx_gen import _xml_google_doc from edx_gen import", "html files if comp_type == 'html': print(\" |_ HTML COMP\")", "does not seem to contain any components:', md_filepath) # get", "md_filepath, meta_tag, _edx_consts.COMP_VIDEO_REQ, _edx_consts.COMP_VIDEO_OPT ) # check that we have", "does not start with any settings:', md_filepath) return # get", "for this \"html\" component:', md_filepath) return # remove h1 meta_tag", "the output tree_snippet.remove(meta_tag) # write .html file to COMP_HTML_FOLDER #", "file does not seem to contain any components:', md_filepath) #", "meta_tag, _edx_consts.COMP_PROB_QUIZ_REQ, _edx_consts.COMP_PROB_QUIZ_OPT ) # check that we have settings", "unit_filename) elif comp_type == 'video': print(\" |_ VIDEO COMP\") #", "comp_type not in _edx_consts.METADATA_ENUMS['type']: print(WARNING, 'The \"type\" setting is not", "# check we have at least 2 snippets, the header", "# return the list of files return _write_comp_html.writeXmlForHtmlComp( md_filepath, comp_filename,", "print(WARNING, 'There seem to be no settings for this \"problem-checkboxes\"", "comp_filename, tree_snippet, settings, unit_filename) elif comp_type == 'problem-checkboxes': print(\" |_", "\" WARNING:\" #-------------------------------------------------------------------------------------------------- # write to either units folder or", "files unit_comps = [] # process components for i in", "unit_display_name) unit_comps.extend(comp_files) # return the result return unit_comps #-------------------------------------------------------------------------------------------------- #", "in the right folders tree_snippets = _markdown.convertMd(md_filepath) # check we", "files are written # we return the component tag instead", "contain the meta data # # check the meta tag", "import _write_comp_html from edx_gen import _write_comp_checkboxes from edx_gen import _write_comp_video", "meta_text == None or meta_text != 'UNIT': # print(WARNING, 'The", "meta_tag, _edx_consts.COMP_GOOGLE_DOC_REQ, _edx_consts.COMP_GOOGLE_DOC_OPT) # check that we have settings if", "write .xml file to COMP_PROBS_FOLDER # return the list of", "write to either units folder or problems folder, depending on", "print(\" |_ PROBLEM CHECKBOXES\") # get the setting out of", "2 snippets, the header and one component if len(tree_snippets) <=", "print(WARNING, ' Valid options:', _edx_consts.METADATA_ENUMS['type']) # write xml and/or html", "comp_filename, settings, unit_filename) elif comp_type == 'google-doc': print(\" |_ GOOGLE", "# print(\"component_path\", component_path) # generate the files in the right", "HTML COMP\") # get the setting out of the meta_tag", "from edx_gen import _write_comp_html from edx_gen import _write_comp_checkboxes from edx_gen", "for this \"video\" component:', md_filepath) return # remove h1 meta_tag", "no settings for this \"problem-checkboxes\" component:', md_filepath) return # remove", "\"html\" component:', md_filepath) return # remove h1 meta_tag from the", "for i in range(1, len(tree_snippets)): tree_snippet = tree_snippets[i] # generate", "None # get the h1 tags h1_tags = list(tree_snippet.iter('h1')) if", "to store all files unit_comps = [] # process components", "type def writeCompsForUnit(md_filepath, unit_filename): # print(\"component_path\", component_path) # generate the", "to contain any components:', md_filepath) # get the display name", "settings = _read_metadata.getMetaSettings( md_filepath, meta_tag, _edx_consts.COMP_VIDEO_REQ, _edx_consts.COMP_VIDEO_OPT ) # check", "we return the component tag instead return _xml_google_doc.tagForGoogleDocComp(comp_filename, settings, unit_filename)", "the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_HTML_REQ, _edx_consts.COMP_HTML_OPT ) #", "writeCompsForUnit(md_filepath, unit_filename): # print(\"component_path\", component_path) # generate the files in", "return _write_comp_html.writeXmlForHtmlComp( md_filepath, comp_filename, tree_snippet, settings, unit_filename) elif comp_type ==", "for this \"problem-checkboxes\" component:', md_filepath) return # remove h1 meta_tag", "md_filepath, comp_filename, settings, unit_filename) elif comp_type == 'google-doc': print(\" |_", "be no settings for this \"html\" component:', md_filepath) return #", "files return _write_comp_checkboxes.writeXmlForProbCheckboxesComp( md_filepath, comp_filename, tree_snippet, settings, unit_filename) elif comp_type", "in this case, no files are written # we return", "!= 'UNIT': # print(WARNING, 'The markdown file must start with", "GOOGLE DOC COMP\") # get the setting out of the", "== 'google-doc': print(\" |_ GOOGLE DOC COMP\") # get the", "all files unit_comps = [] # process components for i", "folder or problems folder, depending on the type def writeCompsForUnit(md_filepath,", "len(tree_snippets) <= 1: print(WARNING, 'The markdown file does not seem", "= _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_GOOGLE_DOC_REQ, _edx_consts.COMP_GOOGLE_DOC_OPT) # check that we have", "#-------------------------------------------------------------------------------------------------- # write to either units folder or problems folder,", "no settings for this \"Google Doc\" component:', md_filepath) return #", "md_filepath) # get the display name of the unit first_h1_tag", "tag text # meta_text = meta_tag.text.strip() # if meta_text ==", "write xml and/or html files if comp_type == 'html': print(\"", "len(tree_snippets)): tree_snippet = tree_snippets[i] # generate the files new_filename =", "'The snippet does not start with any settings:', md_filepath) return", "for the snippet meta_tag = h1_tags[0] # the first h1", "if meta_text == None or meta_text != 'UNIT': # print(WARNING,", "'There seem to be no settings for this \"html\" component:',", "the output tree_snippet.remove(meta_tag) # write .xml file to COMP_VIDS_FOLDER #", "list(tree_snippet.iter('h1')) if len(h1_tags) == 0: print(WARNING, 'The snippet does not", "\"video\" component:', md_filepath) return # remove h1 meta_tag from the", "to COMP_HTML_FOLDER # write .xml file to COMP_HTML_FOLDER # return", "write .html file to COMP_HTML_FOLDER # write .xml file to", "COMP_HTML_FOLDER # return the list of files return _write_comp_html.writeXmlForHtmlComp( md_filepath,", "import _write_comps from edx_gen import _write_comp_html from edx_gen import _write_comp_checkboxes", "= unit_filename + '_c' + str(i) comp_files = _writeFilesForSnippet(md_filepath, new_filename,", "COMP_VIDS_FOLDER # for each language # write .html file to", "one component if len(tree_snippets) <= 1: print(WARNING, 'The markdown file", "settings for this \"html\" component:', md_filepath) return # remove h1", "first_h1_tag.get('display_name') # list to store all files unit_comps = []", "first_h1_tag = list(tree_snippets[0].iter('h1'))[0] unit_display_name = first_h1_tag.get('display_name') # list to store", "comp_type == 'problem-checkboxes': print(\" |_ PROBLEM CHECKBOXES\") # get the", "edx_gen import _markdown from edx_gen import _util import __SETTINGS__ #--------------------------------------------------------------------------------------------------", "start with any settings:', md_filepath) return # get the meta", "edx_gen import _xml_google_doc from edx_gen import _markdown from edx_gen import", "the unit first_h1_tag = list(tree_snippets[0].iter('h1'))[0] unit_display_name = first_h1_tag.get('display_name') # list", "file must start with the \"UNIT\" settings:', component_path) # print(WARNING,", "each language # write .html file to COMP_HTML_FOLDER # write", "return unit_comps #-------------------------------------------------------------------------------------------------- # write to either units folder or", "# get the setting out of the meta_tag settings =", "this case, no files are written # we return the", "out of the meta_tag settings = _read_metadata.getMetaSettings( md_filepath, meta_tag, _edx_consts.COMP_VIDEO_REQ,", "settings: print(WARNING, 'There seem to be no settings for this", "of files return _write_comp_video.writeXmlForVidComp( md_filepath, comp_filename, settings, unit_filename) elif comp_type", "comp_type = None # meta_text = None # get the", "# if meta_text == None or meta_text != 'UNIT': #", "0: print(WARNING, 'The snippet does not start with any settings:',", "_write_comp_video.writeXmlForVidComp( md_filepath, comp_filename, settings, unit_filename) elif comp_type == 'google-doc': print(\"", "settings for this \"problem-checkboxes\" component:', md_filepath) return # remove h1", "this \"problem-checkboxes\" component:', md_filepath) return # remove h1 meta_tag from", "first line of the markdown file is blank') # get", "check that we have settings if not settings: print(WARNING, 'There", "seem to be no settings for this \"video\" component:', md_filepath)", "component:', md_filepath) return # in this case, no files are", "_edx_consts.COMP_VIDEO_OPT ) # check that we have settings if not", "else: print(WARNING, 'Component type not recognised:', comp_type, \"in\", md_filepath) #--------------------------------------------------------------------------------------------------", "out of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_GOOGLE_DOC_REQ, _edx_consts.COMP_GOOGLE_DOC_OPT)", "= None # meta_text = None # get the h1", "# print(WARNING, 'Make sure that the first line of the", "return the result return unit_comps #-------------------------------------------------------------------------------------------------- # write to either", "_read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_HTML_REQ, _edx_consts.COMP_HTML_OPT ) # check that we have", "if len(h1_tags) == 0: print(WARNING, 'The snippet does not start", "either units folder or problems folder, depending on the type", "contain any components:', md_filepath) # get the display name of", "\"UNIT\" settings:', component_path) # print(WARNING, 'Make sure that the first", "_xml_google_doc from edx_gen import _markdown from edx_gen import _util import", "the files in the right folders tree_snippets = _markdown.convertMd(md_filepath) #", "edx_gen import _write_comp_html from edx_gen import _write_comp_checkboxes from edx_gen import", "unit_filename) elif comp_type == 'problem-checkboxes': print(\" |_ PROBLEM CHECKBOXES\") #", "for each language # write .html file to COMP_HTML_FOLDER #", "written # we return the component tag instead return _xml_google_doc.tagForGoogleDocComp(comp_filename,", "<= 1: print(WARNING, 'The markdown file does not seem to", "in range(1, len(tree_snippets)): tree_snippet = tree_snippets[i] # generate the files", "# list to store all files unit_comps = [] #", "shutil from edx_gen import _edx_consts from edx_gen import _read_metadata from", "the type def _writeFilesForSnippet(md_filepath, comp_filename, tree_snippet, unit_filename, unit_display_name): meta_tag =", "print(\"component_path\", component_path) # generate the files in the right folders", "setting out of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_PROB_QUIZ_REQ,", ".xml file to COMP_PROBS_FOLDER # return the list of files", "or comp_type not in _edx_consts.METADATA_ENUMS['type']: print(WARNING, 'The \"type\" setting is", "import _read_metadata from edx_gen import _write_structure from edx_gen import _write_comps", "return _write_comp_checkboxes.writeXmlForProbCheckboxesComp( md_filepath, comp_filename, tree_snippet, settings, unit_filename) elif comp_type ==", "meta_tag.text.strip() # if meta_text == None or meta_text != 'UNIT':", "new_filename = unit_filename + '_c' + str(i) comp_files = _writeFilesForSnippet(md_filepath,", "if comp_type == None or comp_type not in _edx_consts.METADATA_ENUMS['type']: print(WARNING,", "import shutil from edx_gen import _edx_consts from edx_gen import _read_metadata", "from edx_gen import _read_metadata from edx_gen import _write_structure from edx_gen", "# write xml and/or html files if comp_type == 'html':", "of the markdown file is blank') # get the type", "get the h1 tags h1_tags = list(tree_snippet.iter('h1')) if len(h1_tags) ==", "'Make sure that the first line of the markdown file", "tree_snippet, settings, unit_filename) elif comp_type == 'problem-checkboxes': print(\" |_ PROBLEM", "tree_snippet, settings, unit_filename) elif comp_type == 'video': print(\" |_ VIDEO", "= _writeFilesForSnippet(md_filepath, new_filename, tree_snippet, unit_filename, unit_display_name) unit_comps.extend(comp_files) # return the", "return # get the meta tag for the snippet meta_tag", "import _markdown from edx_gen import _util import __SETTINGS__ #-------------------------------------------------------------------------------------------------- #", "get the type for this component comp_type = meta_tag.get('type') if", "if comp_type == 'html': print(\" |_ HTML COMP\") # get", "import _edx_consts from edx_gen import _read_metadata from edx_gen import _write_structure", "_edx_consts.COMP_HTML_REQ, _edx_consts.COMP_HTML_OPT ) # check that we have settings if", "settings, unit_filename) else: print(WARNING, 'Component type not recognised:', comp_type, \"in\",", "or meta_text != 'UNIT': # print(WARNING, 'The markdown file must", "strings WARNING = \" WARNING:\" #-------------------------------------------------------------------------------------------------- # write to either", "WARNING = \" WARNING:\" #-------------------------------------------------------------------------------------------------- # write to either units", "for this \"Google Doc\" component:', md_filepath) return # in this", "setting out of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_GOOGLE_DOC_REQ,", "= \" WARNING:\" #-------------------------------------------------------------------------------------------------- # write to either units folder", "'There seem to be no settings for this \"video\" component:',", "of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_GOOGLE_DOC_REQ, _edx_consts.COMP_GOOGLE_DOC_OPT) #", "# meta_text = None # get the h1 tags h1_tags", "the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_PROB_QUIZ_REQ, _edx_consts.COMP_PROB_QUIZ_OPT ) #", "to be no settings for this \"Google Doc\" component:', md_filepath)", "on the type def writeCompsForUnit(md_filepath, unit_filename): # print(\"component_path\", component_path) #", "tree_snippet.remove(meta_tag) # write .xml file to COMP_VIDS_FOLDER # for each", "not end up in the output tree_snippet.remove(meta_tag) # write .html", "any settings:', md_filepath) return # get the meta tag for", "_write_comp_checkboxes from edx_gen import _write_comp_video from edx_gen import _xml_google_doc from", "comp_files = _writeFilesForSnippet(md_filepath, new_filename, tree_snippet, unit_filename, unit_display_name) unit_comps.extend(comp_files) # return", "process components for i in range(1, len(tree_snippets)): tree_snippet = tree_snippets[i]", "the list of files return _write_comp_html.writeXmlForHtmlComp( md_filepath, comp_filename, tree_snippet, settings,", "markdown file is blank') # get the type for this", "meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_HTML_REQ, _edx_consts.COMP_HTML_OPT ) # check", "= None # get the h1 tags h1_tags = list(tree_snippet.iter('h1'))", "meta tag text # meta_text = meta_tag.text.strip() # if meta_text", "'The \"type\" setting is not recognised:', md_filepath) print(WARNING, ' Found:',", "import _write_comp_checkboxes from edx_gen import _write_comp_video from edx_gen import _xml_google_doc", "folder, depending on the type def writeCompsForUnit(md_filepath, unit_filename): # print(\"component_path\",", "import tarfile import shutil from edx_gen import _edx_consts from edx_gen", "from edx_gen import _write_comp_checkboxes from edx_gen import _write_comp_video from edx_gen", "import _util import __SETTINGS__ #-------------------------------------------------------------------------------------------------- # Text strings WARNING =", "list(tree_snippets[0].iter('h1'))[0] unit_display_name = first_h1_tag.get('display_name') # list to store all files", "the first h1 the should contain the meta data #", "up in the output tree_snippet.remove(meta_tag) # write .xml file to", "instead return _xml_google_doc.tagForGoogleDocComp(comp_filename, settings, unit_filename) else: print(WARNING, 'Component type not", "COMP_PROBS_FOLDER # return the list of files return _write_comp_checkboxes.writeXmlForProbCheckboxesComp( md_filepath,", "depending on the type def _writeFilesForSnippet(md_filepath, comp_filename, tree_snippet, unit_filename, unit_display_name):", "= first_h1_tag.get('display_name') # list to store all files unit_comps =", "the meta tag for the snippet meta_tag = h1_tags[0] #", "files return _write_comp_video.writeXmlForVidComp( md_filepath, comp_filename, settings, unit_filename) elif comp_type ==", "_edx_consts.COMP_GOOGLE_DOC_OPT) # check that we have settings if not settings:", "_edx_consts.COMP_GOOGLE_DOC_REQ, _edx_consts.COMP_GOOGLE_DOC_OPT) # check that we have settings if not", "import _write_structure from edx_gen import _write_comps from edx_gen import _write_comp_html", "meta_tag = None comp_type = None # meta_text = None", "so it does not end up in the output tree_snippet.remove(meta_tag)", "this \"Google Doc\" component:', md_filepath) return # in this case,", ".xml file to COMP_VIDS_FOLDER # for each language # write", "from edx_gen import _edx_consts from edx_gen import _read_metadata from edx_gen", "== 'problem-checkboxes': print(\" |_ PROBLEM CHECKBOXES\") # get the setting", "_write_comps from edx_gen import _write_comp_html from edx_gen import _write_comp_checkboxes from", "the type for this component comp_type = meta_tag.get('type') if comp_type", "with any settings:', md_filepath) return # get the meta tag", "'The markdown file does not seem to contain any components:',", "end up in the output tree_snippet.remove(meta_tag) # write .xml file", "elif comp_type == 'video': print(\" |_ VIDEO COMP\") # get", "_write_comp_html from edx_gen import _write_comp_checkboxes from edx_gen import _write_comp_video from", "# in this case, no files are written # we", "list to store all files unit_comps = [] # process", "of the meta_tag settings = _read_metadata.getMetaSettings(md_filepath, meta_tag, _edx_consts.COMP_PROB_QUIZ_REQ, _edx_consts.COMP_PROB_QUIZ_OPT )", "in the output tree_snippet.remove(meta_tag) # write .html file to COMP_HTML_FOLDER", "def writeCompsForUnit(md_filepath, unit_filename): # print(\"component_path\", component_path) # generate the files", "print(\" |_ VIDEO COMP\") # get the setting out of", "not recognised:', md_filepath) print(WARNING, ' Found:', comp_type) print(WARNING, ' Valid", "files if comp_type == 'html': print(\" |_ HTML COMP\") #", "# get the type for this component comp_type = meta_tag.get('type')", "folder, depending on the type def _writeFilesForSnippet(md_filepath, comp_filename, tree_snippet, unit_filename,", "from the tree so it does not end up in", "#-------------------------------------------------------------------------------------------------- # Text strings WARNING = \" WARNING:\" #-------------------------------------------------------------------------------------------------- #", "# remove h1 meta_tag from the tree so it does", "to be no settings for this \"video\" component:', md_filepath) return", "at least 2 snippets, the header and one component if", "the files new_filename = unit_filename + '_c' + str(i) comp_files", "elif comp_type == 'problem-checkboxes': print(\" |_ PROBLEM CHECKBOXES\") # get", "return the list of files return _write_comp_html.writeXmlForHtmlComp( md_filepath, comp_filename, tree_snippet,", "the header and one component if len(tree_snippets) <= 1: print(WARNING,", "comp_type == None or comp_type not in _edx_consts.METADATA_ENUMS['type']: print(WARNING, 'The", "settings if not settings: print(WARNING, 'There seem to be no", "h1_tags[0] # the first h1 the should contain the meta", "tree so it does not end up in the output", "meta_tag from the tree so it does not end up", "settings for this \"Google Doc\" component:', md_filepath) return # in", "to be no settings for this \"problem-checkboxes\" component:', md_filepath) return", "settings for this \"video\" component:', md_filepath) return # remove h1", "tag instead return _xml_google_doc.tagForGoogleDocComp(comp_filename, settings, unit_filename) else: print(WARNING, 'Component type", "from edx_gen import _write_comp_video from edx_gen import _xml_google_doc from edx_gen", "_read_metadata from edx_gen import _write_structure from edx_gen import _write_comps from", "def _writeFilesForSnippet(md_filepath, comp_filename, tree_snippet, unit_filename, unit_display_name): meta_tag = None comp_type", "and one component if len(tree_snippets) <= 1: print(WARNING, 'The markdown", "unit_comps #-------------------------------------------------------------------------------------------------- # write to either units folder or problems", "= meta_tag.text.strip() # if meta_text == None or meta_text !=", "# write .html file to COMP_HTML_FOLDER # write .xml file", "'html': print(\" |_ HTML COMP\") # get the setting out", "edx_gen import _util import __SETTINGS__ #-------------------------------------------------------------------------------------------------- # Text strings WARNING", "|_ HTML COMP\") # get the setting out of the", "edx_gen import _write_structure from edx_gen import _write_comps from edx_gen import", "get the display name of the unit first_h1_tag = list(tree_snippets[0].iter('h1'))[0]", "Text strings WARNING = \" WARNING:\" #-------------------------------------------------------------------------------------------------- # write to", "print(WARNING, 'There seem to be no settings for this \"html\"", "that we have settings if not settings: print(WARNING, 'There seem", "edx_gen import _read_metadata from edx_gen import _write_structure from edx_gen import", "get the setting out of the meta_tag settings = _read_metadata.getMetaSettings(", "tree_snippet, unit_filename, unit_display_name) unit_comps.extend(comp_files) # return the result return unit_comps", "# generate the files in the right folders tree_snippets =", "settings:', component_path) # print(WARNING, 'Make sure that the first line", "\"Google Doc\" component:', md_filepath) return # in this case, no", "= list(tree_snippets[0].iter('h1'))[0] unit_display_name = first_h1_tag.get('display_name') # list to store all", "it does not end up in the output tree_snippet.remove(meta_tag) #", "files new_filename = unit_filename + '_c' + str(i) comp_files =", "the display name of the unit first_h1_tag = list(tree_snippets[0].iter('h1'))[0] unit_display_name", "# Text strings WARNING = \" WARNING:\" #-------------------------------------------------------------------------------------------------- # write", "Found:', comp_type) print(WARNING, ' Valid options:', _edx_consts.METADATA_ENUMS['type']) # write xml", "'There seem to be no settings for this \"Google Doc\"", "tree_snippet.remove(meta_tag) # write .xml file to COMP_PROBS_FOLDER # return the", "_writeFilesForSnippet(md_filepath, new_filename, tree_snippet, unit_filename, unit_display_name) unit_comps.extend(comp_files) # return the result", "# the first h1 the should contain the meta data", "_xml_google_doc.tagForGoogleDocComp(comp_filename, settings, unit_filename) else: print(WARNING, 'Component type not recognised:', comp_type,", "CHECKBOXES\") # get the setting out of the meta_tag settings", "DOC COMP\") # get the setting out of the meta_tag", "meta_tag = h1_tags[0] # the first h1 the should contain", "range(1, len(tree_snippets)): tree_snippet = tree_snippets[i] # generate the files new_filename", "the \"UNIT\" settings:', component_path) # print(WARNING, 'Make sure that the", "md_filepath) print(WARNING, ' Found:', comp_type) print(WARNING, ' Valid options:', _edx_consts.METADATA_ENUMS['type'])", "return # remove h1 meta_tag from the tree so it", "in the output tree_snippet.remove(meta_tag) # write .xml file to COMP_VIDS_FOLDER", "from edx_gen import _write_comps from edx_gen import _write_comp_html from edx_gen", "comp_type == 'video': print(\" |_ VIDEO COMP\") # get the", "comp_type) print(WARNING, ' Valid options:', _edx_consts.METADATA_ENUMS['type']) # write xml and/or", "the meta tag text # meta_text = meta_tag.text.strip() # if", "file is blank') # get the type for this component", "the list of files return _write_comp_video.writeXmlForVidComp( md_filepath, comp_filename, settings, unit_filename)" ]
[ "elif score in range(40, 50): students_score[student] = \"D\" else: students_score[student]", "students_score[student] score = int(score) if score >= 90: students_score[student] =", "input(\"Please input student's name. \\n\") check_name(name) # 2.3 Check if", "input(f\"Please input {name}'s score.(0 ~ 100)\\n\") while score.isdigit() == False", "check_name(name) != True: name = input(\"Please input student's name. (Alphabet", "another_student = input(\"Please input Y/N only.\\n\") if another_student.lower() in (\"yes\",", "input is correct. (Alphabet, period, and blank only.) # 2.1", "!= True: name = input(\"Please input student's name. (Alphabet and", "input( \"Do you want to input another student's information as", "input valid numbers only.(Number from zero to 100.)\\n\") students_score[name] =", "in range(40, 50): students_score[student] = \"D\" else: students_score[student] = \"F\"", "elif another_student.lower() in (\"no\", \"n\"): break for student in students_score:", "70): students_score[student] = \"C\" elif score in range(40, 50): students_score[student]", "is Alphabet. return list_to_string.isalpha() while True: # 2.2 Input student's", "range(0, 101): score = input(\"Please input valid numbers only.(Number from", "return list_to_string.isalpha() while True: # 2.2 Input student's name. name", "if the input is valid. another_student = input(\"Please input Y/N", "if another_student.lower() in (\"yes\", \"y\"): continue elif another_student.lower() in (\"no\",", ">= 90: students_score[student] = \"A\" elif score in range(70, 90):", "\".\" in list_of_spelling: list_of_spelling.remove(\".\") while \" \" in list_of_spelling: list_of_spelling.remove(\"", "3. Input student's score and check if input is correct.", "period and blank from the list. while \".\" in list_of_spelling:", "with only Alphabet. # 2.1.1.1 Make a list of spelling", "while \" \" in list_of_spelling: list_of_spelling.remove(\" \") # 2.1.1.3 Convert", "blank from the list. while \".\" in list_of_spelling: list_of_spelling.remove(\".\") while", "while check_name(name) != True: name = input(\"Please input student's name.", "in range(50, 70): students_score[student] = \"C\" elif score in range(40,", "Convert the list to a string. list_to_string = \"\" list_to_string", "If not, ask to input correct name again. while check_name(name)", "student's score and check if input is correct. (digits only", "want to input another student's information as well? (Y/N)\\n\" )", "and check if input is correct. (digits only and between", "in (\"yes\", \"y\", \"n\", \"no\"): # 4.1 Check if the", "score in range(70, 90): students_score[student] = \"B\" elif score in", "name. (Alphabet and period only.)\\n\") # 3. Input student's score", "check if input is correct. (Alphabet, period, and blank only.)", "blank and check it if the name is comprised with", "90): students_score[student] = \"B\" elif score in range(50, 70): students_score[student]", "correct. (Alphabet, period, and blank only.) # 2.1 Creat a", "another_student.lower() in (\"yes\", \"y\"): continue elif another_student.lower() in (\"no\", \"n\"):", "= \"C\" elif score in range(40, 50): students_score[student] = \"D\"", "input(\"Please input student's name. (Alphabet and period only.)\\n\") # 3.", "# 2.1 Creat a function that evaluate the validity of", "the input is valid. another_student = input(\"Please input Y/N only.\\n\")", "is correct. (Alphabet, period, and blank only.) # 2.1 Creat", "only and between zero and 100) score = input(f\"Please input", "the list. while \".\" in list_of_spelling: list_of_spelling.remove(\".\") while \" \"", "to input correct name again. while check_name(name) != True: name", "numbers only.(Number from zero to 100.)\\n\") students_score[name] = score #", "students_score[student] = \"B\" elif score in range(50, 70): students_score[student] =", "that evaluate the validity of name. def check_name(name): # 2.1.1", "name. list_of_spelling = list(name) # 2.1.1.2 Remove period and blank", "\"y\", \"n\", \"no\"): # 4.1 Check if the input is", "is correct. (digits only and between zero and 100) score", "2.1.1.1 Make a list of spelling in the name. list_of_spelling", "list_of_spelling: list_of_spelling.remove(\" \") # 2.1.1.3 Convert the list to a", "and check if input is correct. (Alphabet, period, and blank", "the name. list_of_spelling = list(name) # 2.1.1.2 Remove period and", "score = students_score[student] score = int(score) if score >= 90:", "~ 100)\\n\") while score.isdigit() == False or int(score) not in", "4. Ask another student's information. another_student = input( \"Do you", "not in (\"yes\", \"y\", \"n\", \"no\"): # 4.1 Check if", "while \".\" in list_of_spelling: list_of_spelling.remove(\".\") while \" \" in list_of_spelling:", "\"C\" elif score in range(40, 50): students_score[student] = \"D\" else:", "range(40, 50): students_score[student] = \"D\" else: students_score[student] = \"F\" print(students_score)", "valid. another_student = input(\"Please input Y/N only.\\n\") if another_student.lower() in", "in list_of_spelling: list_of_spelling.remove(\".\") while \" \" in list_of_spelling: list_of_spelling.remove(\" \")", "and blank only.) # 2.1 Creat a function that evaluate", "check_name(name) # 2.3 Check if the name is alphabet. If", "= {} # 2. Input student's name and check if", "if input is correct. (digits only and between zero and", "not in range(0, 101): score = input(\"Please input valid numbers", "input student's name. \\n\") check_name(name) # 2.3 Check if the", "list_to_string.isalpha() while True: # 2.2 Input student's name. name =", "it if the name is comprised with only Alphabet. #", "= input( \"Do you want to input another student's information", "= input(f\"Please input {name}'s score.(0 ~ 100)\\n\") while score.isdigit() ==", "name is alphabet. If not, ask to input correct name", "\\n\") check_name(name) # 2.3 Check if the name is alphabet.", "name. \\n\") check_name(name) # 2.3 Check if the name is", "and check it if the name is comprised with only", "score.isdigit() == False or int(score) not in range(0, 101): score", "# 2.1.1.2 Remove period and blank from the list. while", "list to a string. list_to_string = \"\" list_to_string = list_to_string.join(list_of_spelling)", "information as well? (Y/N)\\n\" ) while another_student.lower() not in (\"yes\",", "# 2.2 Input student's name. name = input(\"Please input student's", ") while another_student.lower() not in (\"yes\", \"y\", \"n\", \"no\"): #", "the list to a string. list_to_string = \"\" list_to_string =", "is comprised with only Alphabet. # 2.1.1.1 Make a list", "= input(\"Please input student's name. (Alphabet and period only.)\\n\") #", "input is correct. (digits only and between zero and 100)", "score = input(\"Please input valid numbers only.(Number from zero to", "# 2.3 Check if the name is alphabet. If not,", "the name is alphabet. If not, ask to input correct", "and 100) score = input(f\"Please input {name}'s score.(0 ~ 100)\\n\")", "(Y/N)\\n\" ) while another_student.lower() not in (\"yes\", \"y\", \"n\", \"no\"):", "(\"yes\", \"y\", \"n\", \"no\"): # 4.1 Check if the input", "in range(70, 90): students_score[student] = \"B\" elif score in range(50,", "zero to 100.)\\n\") students_score[name] = score # 4. Ask another", "list_to_string = \"\" list_to_string = list_to_string.join(list_of_spelling) # 2.1.1.4 Return if", "student in students_score: score = students_score[student] score = int(score) if", "and blank from the list. while \".\" in list_of_spelling: list_of_spelling.remove(\".\")", "is alphabet. If not, ask to input correct name again.", "students_score: score = students_score[student] score = int(score) if score >=", "= \"\" list_to_string = list_to_string.join(list_of_spelling) # 2.1.1.4 Return if the", "score.(0 ~ 100)\\n\") while score.isdigit() == False or int(score) not", "= list(name) # 2.1.1.2 Remove period and blank from the", "is valid. another_student = input(\"Please input Y/N only.\\n\") if another_student.lower()", "you want to input another student's information as well? (Y/N)\\n\"", "student's name and check if input is correct. (Alphabet, period,", "(\"yes\", \"y\"): continue elif another_student.lower() in (\"no\", \"n\"): break for", "if score >= 90: students_score[student] = \"A\" elif score in", "list_of_spelling.remove(\".\") while \" \" in list_of_spelling: list_of_spelling.remove(\" \") # 2.1.1.3", "score dictionary. students_score = {} # 2. Input student's name", "blank only.) # 2.1 Creat a function that evaluate the", "input(\"Please input valid numbers only.(Number from zero to 100.)\\n\") students_score[name]", "score and check if input is correct. (digits only and", "from zero to 100.)\\n\") students_score[name] = score # 4. Ask", "= input(\"Please input Y/N only.\\n\") if another_student.lower() in (\"yes\", \"y\"):", "continue elif another_student.lower() in (\"no\", \"n\"): break for student in", "in (\"no\", \"n\"): break for student in students_score: score =", "period and blank and check it if the name is", "2.3 Check if the name is alphabet. If not, ask", "ask to input correct name again. while check_name(name) != True:", "100.)\\n\") students_score[name] = score # 4. Ask another student's information.", "input another student's information as well? (Y/N)\\n\" ) while another_student.lower()", "input Y/N only.\\n\") if another_student.lower() in (\"yes\", \"y\"): continue elif", "(digits only and between zero and 100) score = input(f\"Please", "if the name is comprised with only Alphabet. # 2.1.1.1", "\"\" list_to_string = list_to_string.join(list_of_spelling) # 2.1.1.4 Return if the string", "in range(0, 101): score = input(\"Please input valid numbers only.(Number", "for student in students_score: score = students_score[student] score = int(score)", "\"A\" elif score in range(70, 90): students_score[student] = \"B\" elif", "= int(score) if score >= 90: students_score[student] = \"A\" elif", "= input(\"Please input student's name. \\n\") check_name(name) # 2.3 Check", "= \"B\" elif score in range(50, 70): students_score[student] = \"C\"", "name and check if input is correct. (Alphabet, period, and", "int(score) not in range(0, 101): score = input(\"Please input valid", "name is comprised with only Alphabet. # 2.1.1.1 Make a", "score = input(f\"Please input {name}'s score.(0 ~ 100)\\n\") while score.isdigit()", "valid numbers only.(Number from zero to 100.)\\n\") students_score[name] = score", "# 2.1.1.1 Make a list of spelling in the name.", "to 100.)\\n\") students_score[name] = score # 4. Ask another student's", "validity of name. def check_name(name): # 2.1.1 Remove period and", "in list_of_spelling: list_of_spelling.remove(\" \") # 2.1.1.3 Convert the list to", "a string. list_to_string = \"\" list_to_string = list_to_string.join(list_of_spelling) # 2.1.1.4", "student's information. another_student = input( \"Do you want to input", "another_student = input( \"Do you want to input another student's", "2.1.1 Remove period and blank and check it if the", "list. while \".\" in list_of_spelling: list_of_spelling.remove(\".\") while \" \" in", "\"n\", \"no\"): # 4.1 Check if the input is valid.", "score = int(score) if score >= 90: students_score[student] = \"A\"", "\" \" in list_of_spelling: list_of_spelling.remove(\" \") # 2.1.1.3 Convert the", "100)\\n\") while score.isdigit() == False or int(score) not in range(0,", "= students_score[student] score = int(score) if score >= 90: students_score[student]", "another student's information. another_student = input( \"Do you want to", "in the name. list_of_spelling = list(name) # 2.1.1.2 Remove period", "if the name is alphabet. If not, ask to input", "Alphabet. return list_to_string.isalpha() while True: # 2.2 Input student's name.", "name = input(\"Please input student's name. (Alphabet and period only.)\\n\")", "student's name. name = input(\"Please input student's name. \\n\") check_name(name)", "range(50, 70): students_score[student] = \"C\" elif score in range(40, 50):", "while True: # 2.2 Input student's name. name = input(\"Please", "{name}'s score.(0 ~ 100)\\n\") while score.isdigit() == False or int(score)", "\"Do you want to input another student's information as well?", "student's information as well? (Y/N)\\n\" ) while another_student.lower() not in", "name. name = input(\"Please input student's name. \\n\") check_name(name) #", "well? (Y/N)\\n\" ) while another_student.lower() not in (\"yes\", \"y\", \"n\",", "information. another_student = input( \"Do you want to input another", "while another_student.lower() not in (\"yes\", \"y\", \"n\", \"no\"): # 4.1", "False or int(score) not in range(0, 101): score = input(\"Please", "the validity of name. def check_name(name): # 2.1.1 Remove period", "2. Input student's name and check if input is correct.", "and between zero and 100) score = input(f\"Please input {name}'s", "= \"A\" elif score in range(70, 90): students_score[student] = \"B\"", "or int(score) not in range(0, 101): score = input(\"Please input", "list_to_string.join(list_of_spelling) # 2.1.1.4 Return if the string is Alphabet. return", "Y/N only.\\n\") if another_student.lower() in (\"yes\", \"y\"): continue elif another_student.lower()", "2.1.1.3 Convert the list to a string. list_to_string = \"\"", "# 2.1.1 Remove period and blank and check it if", "Alphabet. # 2.1.1.1 Make a list of spelling in the", "90: students_score[student] = \"A\" elif score in range(70, 90): students_score[student]", "students_score[student] = \"A\" elif score in range(70, 90): students_score[student] =", "2.1.1.2 Remove period and blank from the list. while \".\"", "list(name) # 2.1.1.2 Remove period and blank from the list.", "check if input is correct. (digits only and between zero", "only.\\n\") if another_student.lower() in (\"yes\", \"y\"): continue elif another_student.lower() in", "score in range(40, 50): students_score[student] = \"D\" else: students_score[student] =", "student's name. \\n\") check_name(name) # 2.3 Check if the name", "list_of_spelling: list_of_spelling.remove(\".\") while \" \" in list_of_spelling: list_of_spelling.remove(\" \") #", "students_score = {} # 2. Input student's name and check", "input correct name again. while check_name(name) != True: name =", "4.1 Check if the input is valid. another_student = input(\"Please", "Remove period and blank and check it if the name", "\") # 2.1.1.3 Convert the list to a string. list_to_string", "# 4. Ask another student's information. another_student = input( \"Do", "correct name again. while check_name(name) != True: name = input(\"Please", "the name is comprised with only Alphabet. # 2.1.1.1 Make", "input student's name. (Alphabet and period only.)\\n\") # 3. Input", "101): score = input(\"Please input valid numbers only.(Number from zero", "2.1.1.4 Return if the string is Alphabet. return list_to_string.isalpha() while", "Creat a function that evaluate the validity of name. def", "Check if the input is valid. another_student = input(\"Please input", "only.(Number from zero to 100.)\\n\") students_score[name] = score # 4.", "2.1 Creat a function that evaluate the validity of name.", "\"n\"): break for student in students_score: score = students_score[student] score", "elif score in range(70, 90): students_score[student] = \"B\" elif score", "1. Create students score dictionary. students_score = {} # 2.", "# 2. Input student's name and check if input is", "Create students score dictionary. students_score = {} # 2. Input", "another_student.lower() not in (\"yes\", \"y\", \"n\", \"no\"): # 4.1 Check", "list_to_string = list_to_string.join(list_of_spelling) # 2.1.1.4 Return if the string is", "a function that evaluate the validity of name. def check_name(name):", "{} # 2. Input student's name and check if input", "Check if the name is alphabet. If not, ask to", "of spelling in the name. list_of_spelling = list(name) # 2.1.1.2", "(Alphabet and period only.)\\n\") # 3. Input student's score and", "and period only.)\\n\") # 3. Input student's score and check", "# 2.1.1.4 Return if the string is Alphabet. return list_to_string.isalpha()", "another student's information as well? (Y/N)\\n\" ) while another_student.lower() not", "Make a list of spelling in the name. list_of_spelling =", "again. while check_name(name) != True: name = input(\"Please input student's", "\"B\" elif score in range(50, 70): students_score[student] = \"C\" elif", "a list of spelling in the name. list_of_spelling = list(name)", "Input student's name and check if input is correct. (Alphabet,", "range(70, 90): students_score[student] = \"B\" elif score in range(50, 70):", "\" in list_of_spelling: list_of_spelling.remove(\" \") # 2.1.1.3 Convert the list", "if input is correct. (Alphabet, period, and blank only.) #", "list_of_spelling = list(name) # 2.1.1.2 Remove period and blank from", "check_name(name): # 2.1.1 Remove period and blank and check it", "student's name. (Alphabet and period only.)\\n\") # 3. Input student's", "score >= 90: students_score[student] = \"A\" elif score in range(70,", "def check_name(name): # 2.1.1 Remove period and blank and check", "evaluate the validity of name. def check_name(name): # 2.1.1 Remove", "only.)\\n\") # 3. Input student's score and check if input", "Ask another student's information. another_student = input( \"Do you want", "# 3. Input student's score and check if input is", "100) score = input(f\"Please input {name}'s score.(0 ~ 100)\\n\") while", "name. def check_name(name): # 2.1.1 Remove period and blank and", "another_student.lower() in (\"no\", \"n\"): break for student in students_score: score", "from the list. while \".\" in list_of_spelling: list_of_spelling.remove(\".\") while \"", "string is Alphabet. return list_to_string.isalpha() while True: # 2.2 Input", "Input student's score and check if input is correct. (digits", "in (\"yes\", \"y\"): continue elif another_student.lower() in (\"no\", \"n\"): break", "Return if the string is Alphabet. return list_to_string.isalpha() while True:", "name = input(\"Please input student's name. \\n\") check_name(name) # 2.3", "only.) # 2.1 Creat a function that evaluate the validity", "dictionary. students_score = {} # 2. Input student's name and", "input(\"Please input Y/N only.\\n\") if another_student.lower() in (\"yes\", \"y\"): continue", "as well? (Y/N)\\n\" ) while another_student.lower() not in (\"yes\", \"y\",", "in students_score: score = students_score[student] score = int(score) if score", "name again. while check_name(name) != True: name = input(\"Please input", "between zero and 100) score = input(f\"Please input {name}'s score.(0", "not, ask to input correct name again. while check_name(name) !=", "to a string. list_to_string = \"\" list_to_string = list_to_string.join(list_of_spelling) #", "Remove period and blank from the list. while \".\" in", "# 4.1 Check if the input is valid. another_student =", "students score dictionary. students_score = {} # 2. Input student's", "correct. (digits only and between zero and 100) score =", "\"y\"): continue elif another_student.lower() in (\"no\", \"n\"): break for student", "to input another student's information as well? (Y/N)\\n\" ) while", "the string is Alphabet. return list_to_string.isalpha() while True: # 2.2", "list_of_spelling.remove(\" \") # 2.1.1.3 Convert the list to a string.", "# 2.1.1.3 Convert the list to a string. list_to_string =", "students_score[student] = \"C\" elif score in range(40, 50): students_score[student] =", "period only.)\\n\") # 3. Input student's score and check if", "(\"no\", \"n\"): break for student in students_score: score = students_score[student]", "elif score in range(50, 70): students_score[student] = \"C\" elif score", "2.2 Input student's name. name = input(\"Please input student's name.", "zero and 100) score = input(f\"Please input {name}'s score.(0 ~", "= list_to_string.join(list_of_spelling) # 2.1.1.4 Return if the string is Alphabet.", "= score # 4. Ask another student's information. another_student =", "\"no\"): # 4.1 Check if the input is valid. another_student", "input {name}'s score.(0 ~ 100)\\n\") while score.isdigit() == False or", "function that evaluate the validity of name. def check_name(name): #", "period, and blank only.) # 2.1 Creat a function that", "string. list_to_string = \"\" list_to_string = list_to_string.join(list_of_spelling) # 2.1.1.4 Return", "while score.isdigit() == False or int(score) not in range(0, 101):", "comprised with only Alphabet. # 2.1.1.1 Make a list of", "(Alphabet, period, and blank only.) # 2.1 Creat a function", "list of spelling in the name. list_of_spelling = list(name) #", "# 1. Create students score dictionary. students_score = {} #", "students_score[name] = score # 4. Ask another student's information. another_student", "score in range(50, 70): students_score[student] = \"C\" elif score in", "True: name = input(\"Please input student's name. (Alphabet and period", "and blank and check it if the name is comprised", "True: # 2.2 Input student's name. name = input(\"Please input", "== False or int(score) not in range(0, 101): score =", "break for student in students_score: score = students_score[student] score =", "input is valid. another_student = input(\"Please input Y/N only.\\n\") if", "score # 4. Ask another student's information. another_student = input(", "Input student's name. name = input(\"Please input student's name. \\n\")", "int(score) if score >= 90: students_score[student] = \"A\" elif score", "spelling in the name. list_of_spelling = list(name) # 2.1.1.2 Remove", "= input(\"Please input valid numbers only.(Number from zero to 100.)\\n\")", "check it if the name is comprised with only Alphabet.", "if the string is Alphabet. return list_to_string.isalpha() while True: #", "of name. def check_name(name): # 2.1.1 Remove period and blank", "only Alphabet. # 2.1.1.1 Make a list of spelling in", "alphabet. If not, ask to input correct name again. while" ]
[ "import utils class UtilTestCase(unittest.TestCase): def test_valid_project_slug(self): project_slug = \"Recipe0123456789_mock\" self.assertTrue(utils.valid_project_slug(project_slug))", "project_slug = \"\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug = \"Recipe000000000000000000000000000000000000000000001\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug =", "= \"\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug = \"Recipe000000000000000000000000000000000000000000001\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug = \"-!@#$%^&*()_+\"", "\"\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug = \"Recipe000000000000000000000000000000000000000000001\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug = \"-!@#$%^&*()_+\" self.assertFalse(utils.valid_project_slug(project_slug))", "recipe import utils class UtilTestCase(unittest.TestCase): def test_valid_project_slug(self): project_slug = \"Recipe0123456789_mock\"", "\"Recipe0123456789_mock\" self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = 'Recipe00000000000000000000000000000000000000000000' self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = \"\" self.assertFalse(utils.valid_project_slug(project_slug))", "from recipe import utils class UtilTestCase(unittest.TestCase): def test_valid_project_slug(self): project_slug =", "UtilTestCase(unittest.TestCase): def test_valid_project_slug(self): project_slug = \"Recipe0123456789_mock\" self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = 'Recipe00000000000000000000000000000000000000000000'", "test_valid_project_slug(self): project_slug = \"Recipe0123456789_mock\" self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = 'Recipe00000000000000000000000000000000000000000000' self.assertTrue(utils.valid_project_slug(project_slug)) project_slug", "project_slug = 'Recipe00000000000000000000000000000000000000000000' self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = \"\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug =", "import unittest from recipe import utils class UtilTestCase(unittest.TestCase): def test_valid_project_slug(self):", "unittest from recipe import utils class UtilTestCase(unittest.TestCase): def test_valid_project_slug(self): project_slug", "= 'Recipe00000000000000000000000000000000000000000000' self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = \"\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug = \"Recipe000000000000000000000000000000000000000000001\"", "'Recipe00000000000000000000000000000000000000000000' self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = \"\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug = \"Recipe000000000000000000000000000000000000000000001\" self.assertFalse(utils.valid_project_slug(project_slug))", "def test_valid_project_slug(self): project_slug = \"Recipe0123456789_mock\" self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = 'Recipe00000000000000000000000000000000000000000000' self.assertTrue(utils.valid_project_slug(project_slug))", "self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = \"\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug = \"Recipe000000000000000000000000000000000000000000001\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug", "project_slug = \"Recipe0123456789_mock\" self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = 'Recipe00000000000000000000000000000000000000000000' self.assertTrue(utils.valid_project_slug(project_slug)) project_slug =", "class UtilTestCase(unittest.TestCase): def test_valid_project_slug(self): project_slug = \"Recipe0123456789_mock\" self.assertTrue(utils.valid_project_slug(project_slug)) project_slug =", "utils class UtilTestCase(unittest.TestCase): def test_valid_project_slug(self): project_slug = \"Recipe0123456789_mock\" self.assertTrue(utils.valid_project_slug(project_slug)) project_slug", "self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = 'Recipe00000000000000000000000000000000000000000000' self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = \"\" self.assertFalse(utils.valid_project_slug(project_slug)) project_slug", "= \"Recipe0123456789_mock\" self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = 'Recipe00000000000000000000000000000000000000000000' self.assertTrue(utils.valid_project_slug(project_slug)) project_slug = \"\"" ]
[ "= np.zeros(63) for i in range(0, pose_body_mats.shape[0]): rot_vec, jac =", "== 69: pose_body = loaded[:, 0:32] else: vposer, _ =", "* 1e2 betas = np.load(part_path + '/betas.npy') fid_lst = np.load(part_path", "1), dtype=dtype, device=device) K = torch.cat([zeros, -rz, ry, rz, zeros,", "'/poses.npy')[:-1] face_expressions = np.load(part_path + '/expressions.npy')[:-1] * 1e2 betas =", "assert len(fid_lst) == len(face_expressions), f'{len(fid_lst)} != {len(face_expressions)}' n = len(poses)", "req_srt = req_ids[req_sort] req_srt_pos = -1 * np.ones(len(req_srt), dtype=int) i", "-6:-3] result['n'] = len(loaded) else: result[k] = loaded return result", "req_ids_ans = -1 * np.ones(len(req_srt), dtype=int) req_ids_ans[req_sort] = req_srt_pos return", "= config['is_vposer'] # gender of a subject is_male = config['is_male']", "the vposer model if loaded.shape[1] == 69: pose_body = loaded[:,", "axis-angle parameters ''' batch_size = rot_vecs.shape[0] device = rot_vecs.device angle", "req_srt_pos[j] = id_ss_pos[i] i += 1 j += 1 elif", "None dev_trans = None if dev_id > 0: dev_orient =", "req_srt[j]: i += 1 req_ids_ans = -1 * np.ones(len(req_srt), dtype=int)", "json.load(f) # do we use vposer embeddings is_vposer = config['is_vposer']", "+ '/betas.npy') fid_lst = np.load(part_path + '/fid_lst.npy') with open(part_path +", "device=device) K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry,", "0:63] pose_jaw = poses[:, 63:66] pose_eye = poses[:, 66:72] pose_hand", "torch.tensor(poses[:, 0:32]) # convert from vposer to rotation matrices pose_body_list", "human_body_prior.tools.model_loader import load_vposer import torch vposer_ckpt = '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/' def load_avakhitov_fits_vposer(vposer,", "else: pose_body = poses[:, 0:63] pose_jaw = poses[:, 63:66] pose_eye", "'/config.json', 'r') as f: config = json.load(f) # do we", "'n': n, 'frame_index2fit_index': frame_index2fit_index, 'is_male': is_male, 'is_vposer': is_vposer } return", "= torch.zeros((batch_size, 1), dtype=dtype, device=device) K = torch.cat([zeros, -rz, ry,", "req_sort = np.argsort(req_ids) id_ss_srt = id_sel_set[ss_sort] id_ss_pos = np.arange(0, len(id_sel_set))[ss_sort]", "dtype=dtype, device=device) zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) K =", "if dev_orient is not None: for i in range(n): rot_mat", "'expressions'], [load_fid_lst, 'fid_lst', 'fid_lst'] ]: if flag: load_fp = osp.join(dp,", "else: vposer, _ = load_vposer(vposer_ckpt, vp_model='snapshot') vposer.eval() pose_body_vp = torch.tensor(loaded[:,", "is_vposer: pose_body_vp = torch.tensor(poses[:, 0:32]) # convert from vposer to", "'/fid_lst.npy') with open(part_path + '/config.json', 'r') as f: config =", ".view((batch_size, 3, 3)) ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat =", "= loaded return result def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): ''' Calculates", "= np.load(load_fp) except: print(load_fp) raise Exception() if fn_no_ext == 'poses':", "= dev_mat @ rot_mat rot[i] = cv2.Rodrigues(rot_mat)[0].reshape(-1) trans[i] = (dev_mat", "35:41] pose_hand = poses[:, 41:-6] else: pose_body = poses[:, 0:63]", "loaded = np.load(load_fp) except: print(load_fp) raise Exception() if fn_no_ext ==", "vposer, _ = load_vposer(vposer_ckpt, vp_model='snapshot') vposer.eval() pose_body_vp = torch.tensor(loaded[:, 0:32])", "in range(0, pose_body_mats.shape[0]): for j in range(0, pose_body_mats.shape[1]): rot_vec, jac", "not None: for i in range(n): rot_mat = cv2.Rodrigues(rot[i].reshape(3, 1))[0]", "Exception() if fn_no_ext == 'poses': #load the vposer model if", "'body_pose': pose_body, 'hand_pose': pose_hand, 'jaw_pose': pose_jaw, 'eye_pose': pose_eye, 'face_expression': face_expressions,", "= torch.tensor(poses[:, 0:32]) # convert from vposer to rotation matrices", "if dev_id > 0: dev_orient = np.load(part_path + '/dev_orient.npy') dev_trans", "pose_body_mats = vposer.decode(pose_body_vp[i]).reshape(-1, 3, 3).detach().cpu().numpy() pose_body = np.zeros(63) for i", "parameters ''' batch_size = rot_vecs.shape[0] device = rot_vecs.device angle =", "torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) zeros = torch.zeros((batch_size, 1), dtype=dtype,", "rot_mat = cv2.Rodrigues(rot[i].reshape(3, 1))[0] dev_mat = cv2.Rodrigues(dev_orient.reshape(3, 1))[0] rot_mat =", "dim=1, keepdim=True) rot_dir = rot_vecs / angle cos = torch.unsqueeze(torch.cos(angle),", "subject is_male = config['is_male'] # id of a device (used", "'fid_lst', 'fid_lst'] ]: if flag: load_fp = osp.join(dp, f'{fn_no_ext}.npy') try:", "1))[0] rot_mat = dev_mat @ rot_mat rot[i] = cv2.Rodrigues(rot_mat)[0].reshape(-1) trans[i]", "rotation matrices for the given axis-angle parameters ''' batch_size =", "result = { 'global_rvec': rot, 'global_tvec': trans, 'body_pose': pose_body, 'hand_pose':", "rot_mat = dev_mat @ rot_mat rot[i] = cv2.Rodrigues(rot_mat)[0].reshape(-1) trans[i] =", "range(0, pose_body_mats.shape[1]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i,j]) pose_body[i, 3*j : 3*j+3]", "as np import cv2 import os.path as osp import json", "fn_no_ext == 'poses': #load the vposer model if loaded.shape[1] ==", "+ sin * K + (1 - cos) * torch.bmm(K,", "1 req_ids_ans = -1 * np.ones(len(req_srt), dtype=int) req_ids_ans[req_sort] = req_srt_pos", "= (dev_mat @ trans[i].reshape(3, 1) + dev_trans.reshape(3, 1)).reshape(-1) result =", "'body_poses', 'poses'], [load_expressions, 'expressions', 'expressions'], [load_fid_lst, 'fid_lst', 'fid_lst'] ]: if", "pose_jaw = poses[:, 63:66] pose_eye = poses[:, 66:72] pose_hand =", "= { fid_lst[i]: i for i in range(n) } #", "open(part_path + '/config.json', 'r') as f: config = json.load(f) #", "if fn_no_ext == 'poses': #load the vposer model if loaded.shape[1]", "pose_eye, 'face_expression': face_expressions, 'betas': betas, 'n': n, 'frame_index2fit_index': frame_index2fit_index, 'is_male':", "device = rot_vecs.device angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True)", "-1 * np.ones(len(req_srt), dtype=int) i = 0 j = 0", "len(req_srt): if req_srt[j] == id_ss_srt[i]: req_srt_pos[j] = id_ss_pos[i] i +=", "torch.split(rot_dir, 1, dim=1) K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device)", "+ (1 - cos) * torch.bmm(K, K) return rot_mat def", "import load_vposer import torch vposer_ckpt = '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/' def load_avakhitov_fits_vposer(vposer, part_path,", "69: pose_body = loaded[:, 0:32] else: vposer, _ = load_vposer(vposer_ckpt,", "i: 3 * i + 3] = rot_vec.reshape(-1) pose_body_list.append(pose_body) pose_body", "of N axis-angle vectors Returns ------- R: torch.tensor Nx3x3 The", "id_ss_pos = np.arange(0, len(id_sel_set))[ss_sort] req_srt = req_ids[req_sort] req_srt_pos = -1", "3] = rot_vec.reshape(-1) pose_body_list.append(pose_body) pose_body = np.array(pose_body_list) pose_jaw = poses[:,", "a batch of rotation vectors Parameters ---------- rot_vecs: torch.tensor Nx3", "poses[:, -6:-3] if is_vposer: pose_body_vp = torch.tensor(poses[:, 0:32]) # convert", "id_sel_set[ss_sort] id_ss_pos = np.arange(0, len(id_sel_set))[ss_sort] req_srt = req_ids[req_sort] req_srt_pos =", "and j < len(req_srt): if req_srt[j] == id_ss_srt[i]: req_srt_pos[j] =", "the rotation matrices for a batch of rotation vectors Parameters", "N axis-angle vectors Returns ------- R: torch.tensor Nx3x3 The rotation", "np.load(part_path + '/betas.npy') fid_lst = np.load(part_path + '/fid_lst.npy') with open(part_path", "= config['dev_lst'] dev_id = 0 while dev_lst[dev_id] != dev_lbl: dev_id", "@ rot_mat rot[i] = cv2.Rodrigues(rot_mat)[0].reshape(-1) trans[i] = (dev_mat @ trans[i].reshape(3,", "for flag, k, fn_no_ext in [ [load_betas, 'betas', 'betas'], [load_body_poses,", "rot_vecs.device angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) rot_dir =", "np.arange(0, len(id_sel_set))[ss_sort] req_srt = req_ids[req_sort] req_srt_pos = -1 * np.ones(len(req_srt),", "in range(n) } # load the device pose dev_lst =", "device pose dev_lst = config['dev_lst'] dev_id = 0 while dev_lst[dev_id]", "array of N axis-angle vectors Returns ------- R: torch.tensor Nx3x3", "i in range(0, pose_body_mats.shape[0]): for j in range(0, pose_body_mats.shape[1]): rot_vec,", "osp import json from human_body_prior.tools.model_loader import load_vposer import torch vposer_ckpt", "matrices for the given axis-angle parameters ''' batch_size = rot_vecs.shape[0]", "rigid pose of the device) assert len(fid_lst) == len(poses), f'{len(fid_lst)}", "fid_lst = np.load(part_path + '/fid_lst.npy') with open(part_path + '/config.json', 'r')", "rot_vecs: torch.tensor Nx3 array of N axis-angle vectors Returns -------", "= [] for i in range(n): pose_body_mats = vposer.decode(pose_body_vp[i]).reshape(-1, 3,", "= '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/' def load_avakhitov_fits_vposer(vposer, part_path, dev_lbl): poses = np.load(part_path +", "-rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\", "pose_body result['global_rvecs'] = loaded[:, -3:] result['global_tvecs'] = loaded[:, -6:-3] result['n']", "= np.argsort(id_sel_set) req_sort = np.argsort(req_ids) id_ss_srt = id_sel_set[ss_sort] id_ss_pos =", "for a batch of rotation vectors Parameters ---------- rot_vecs: torch.tensor", "= np.load(part_path + '/expressions.npy')[:-1] * 1e2 betas = np.load(part_path +", "print(load_fp) raise Exception() if fn_no_ext == 'poses': #load the vposer", "np import cv2 import os.path as osp import json from", "of a device (used to decode the rigid pose of", "vposer model if loaded.shape[1] == 69: pose_body = loaded[:, 0:32]", "pose_body = np.zeros(63) for i in range(0, pose_body_mats.shape[0]): rot_vec, jac", "id of a device (used to decode the rigid pose", "torch.tensor(loaded[:, 0:32]) #convert from vposer to rotation matrices pose_body_mats =", "pose_body_vp = torch.tensor(loaded[:, 0:32]) #convert from vposer to rotation matrices", "trans, 'body_pose': pose_body, 'hand_pose': pose_hand, 'jaw_pose': pose_jaw, 'eye_pose': pose_eye, 'face_expression':", "= poses[:, 0:63] pose_jaw = poses[:, 63:66] pose_eye = poses[:,", "epsilon=1e-8, dtype=torch.float32): ''' Calculates the rotation matrices for a batch", "= torch.unsqueeze(torch.sin(angle), dim=1) # Bx1 arrays rx, ry, rz =", "dev_trans = None if dev_id > 0: dev_orient = np.load(part_path", "= None if dev_id > 0: dev_orient = np.load(part_path +", "* i: 3 * i + 3] = rot_vec.reshape(-1) pose_body_list.append(pose_body)", "Returns ------- R: torch.tensor Nx3x3 The rotation matrices for the", "rot_vecs / angle cos = torch.unsqueeze(torch.cos(angle), dim=1) sin = torch.unsqueeze(torch.sin(angle),", "'poses': #load the vposer model if loaded.shape[1] == 69: pose_body", "dim=1) sin = torch.unsqueeze(torch.sin(angle), dim=1) # Bx1 arrays rx, ry,", "63)) for i in range(0, pose_body_mats.shape[0]): for j in range(0,", "vposer to rotation matrices pose_body_mats = vposer.decode(pose_body_vp).reshape(len(loaded), -1, 3, 3).detach().cpu().numpy()", "device=device) zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) K = torch.cat([zeros,", "pose_hand, 'jaw_pose': pose_jaw, 'eye_pose': pose_eye, 'face_expression': face_expressions, 'betas': betas, 'n':", "!= dev_lbl: dev_id += 1 dev_orient = None dev_trans =", "keepdim=True) rot_dir = rot_vecs / angle cos = torch.unsqueeze(torch.cos(angle), dim=1)", "embeddings is_vposer = config['is_vposer'] # gender of a subject is_male", "'betas'], [load_body_poses, 'body_poses', 'poses'], [load_expressions, 'expressions', 'expressions'], [load_fid_lst, 'fid_lst', 'fid_lst']", "else: result[k] = loaded return result def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32):", "import os.path as osp import json from human_body_prior.tools.model_loader import load_vposer", "cv2 import os.path as osp import json from human_body_prior.tools.model_loader import", "[ [load_betas, 'betas', 'betas'], [load_body_poses, 'body_poses', 'poses'], [load_expressions, 'expressions', 'expressions'],", "= np.load(part_path + '/betas.npy') fid_lst = np.load(part_path + '/fid_lst.npy') with", "i += 1 req_ids_ans = -1 * np.ones(len(req_srt), dtype=int) req_ids_ans[req_sort]", "= poses[:, -3:] trans = poses[:, -6:-3] if is_vposer: pose_body_vp", "1 elif id_ss_srt[i] < req_srt[j]: i += 1 req_ids_ans =", "torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) rot_dir = rot_vecs / angle", "3, 3)) ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat = ident", "zeros, -rx, -ry, rx, zeros], dim=1) \\ .view((batch_size, 3, 3))", "+= 1 elif req_srt[j] < id_ss_srt[i]: j += 1 elif", "None if dev_id > 0: dev_orient = np.load(part_path + '/dev_orient.npy')", "do we use vposer embeddings is_vposer = config['is_vposer'] # gender", "= np.zeros((pose_body_mats.shape[0], 63)) for i in range(0, pose_body_mats.shape[0]): for j", "= osp.join(dp, f'{fn_no_ext}.npy') try: loaded = np.load(load_fp) except: print(load_fp) raise", "= 0 while i < len(id_ss_srt) and j < len(req_srt):", "'betas': betas, 'n': n, 'frame_index2fit_index': frame_index2fit_index, 'is_male': is_male, 'is_vposer': is_vposer", "batch of rotation vectors Parameters ---------- rot_vecs: torch.tensor Nx3 array", "zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) K = torch.cat([zeros, -rz,", "result[k] = pose_body result['global_rvecs'] = loaded[:, -3:] result['global_tvecs'] = loaded[:,", "load_betas=True, load_body_poses=True, load_expressions=False, load_fid_lst=True): result = dict() for flag, k,", "{ fid_lst[i]: i for i in range(n) } # load", "= np.load(part_path + '/dev_trans.npy') rot = poses[:, -3:] trans =", "f'{len(fid_lst)} != {len(face_expressions)}' n = len(poses) frame_index2fit_index = { fid_lst[i]:", "is_male, 'is_vposer': is_vposer } return result def load_avakhitov_fits(dp, load_betas=True, load_body_poses=True,", "poses[:, 0:63] pose_jaw = poses[:, 63:66] pose_eye = poses[:, 66:72]", "loaded[:, -6:-3] result['n'] = len(loaded) else: result[k] = loaded return", "= len(poses) frame_index2fit_index = { fid_lst[i]: i for i in", "for i in range(n): pose_body_mats = vposer.decode(pose_body_vp[i]).reshape(-1, 3, 3).detach().cpu().numpy() pose_body", "raise Exception() if fn_no_ext == 'poses': #load the vposer model", "dev_lst = config['dev_lst'] dev_id = 0 while dev_lst[dev_id] != dev_lbl:", "= len(loaded) else: result[k] = loaded return result def batch_rodrigues(rot_vecs,", "the given axis-angle parameters ''' batch_size = rot_vecs.shape[0] device =", "+= 1 dev_orient = None dev_trans = None if dev_id", "k, fn_no_ext in [ [load_betas, 'betas', 'betas'], [load_body_poses, 'body_poses', 'poses'],", "dev_trans.reshape(3, 1)).reshape(-1) result = { 'global_rvec': rot, 'global_tvec': trans, 'body_pose':", "= dict() for flag, k, fn_no_ext in [ [load_betas, 'betas',", "result['global_tvecs'] = loaded[:, -6:-3] result['n'] = len(loaded) else: result[k] =", "(used to decode the rigid pose of the device) assert", "vposer to rotation matrices pose_body_list = [] for i in", "matrices for a batch of rotation vectors Parameters ---------- rot_vecs:", "in range(0, pose_body_mats.shape[0]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i]) pose_body[3 * i:", "np.load(part_path + '/dev_orient.npy') dev_trans = np.load(part_path + '/dev_trans.npy') rot =", "rx, ry, rz = torch.split(rot_dir, 1, dim=1) K = torch.zeros((batch_size,", "len(poses) frame_index2fit_index = { fid_lst[i]: i for i in range(n)", "63:66] pose_eye = poses[:, 66:72] pose_hand = poses[:, 72:-6] if", "= cv2.Rodrigues(dev_orient.reshape(3, 1))[0] rot_mat = dev_mat @ rot_mat rot[i] =", "[load_expressions, 'expressions', 'expressions'], [load_fid_lst, 'fid_lst', 'fid_lst'] ]: if flag: load_fp", "dtype=int) i = 0 j = 0 while i <", "poses[:, 41:-6] else: pose_body = poses[:, 0:63] pose_jaw = poses[:,", ": 3*j+3] = rot_vec.reshape(-1) result[k] = pose_body result['global_rvecs'] = loaded[:,", "# load the device pose dev_lst = config['dev_lst'] dev_id =", "# convert from vposer to rotation matrices pose_body_list = []", "3).detach().cpu().numpy() pose_body = np.zeros((pose_body_mats.shape[0], 63)) for i in range(0, pose_body_mats.shape[0]):", "result def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): ''' Calculates the rotation matrices", "zeros], dim=1) \\ .view((batch_size, 3, 3)) ident = torch.eye(3, dtype=dtype,", "use vposer embeddings is_vposer = config['is_vposer'] # gender of a", "dict() for flag, k, fn_no_ext in [ [load_betas, 'betas', 'betas'],", "= id_ss_pos[i] i += 1 j += 1 elif req_srt[j]", "= poses[:, -6:-3] if is_vposer: pose_body_vp = torch.tensor(poses[:, 0:32]) #", "+= 1 req_ids_ans = -1 * np.ones(len(req_srt), dtype=int) req_ids_ans[req_sort] =", "rz, zeros, -rx, -ry, rx, zeros], dim=1) \\ .view((batch_size, 3,", "req_srt[j] < id_ss_srt[i]: j += 1 elif id_ss_srt[i] < req_srt[j]:", "rot_vec.reshape(-1) pose_body_list.append(pose_body) pose_body = np.array(pose_body_list) pose_jaw = poses[:, 32:35] pose_eye", "pose_body_list.append(pose_body) pose_body = np.array(pose_body_list) pose_jaw = poses[:, 32:35] pose_eye =", "loaded.shape[1] == 69: pose_body = loaded[:, 0:32] else: vposer, _", "= np.argsort(req_ids) id_ss_srt = id_sel_set[ss_sort] id_ss_pos = np.arange(0, len(id_sel_set))[ss_sort] req_srt", "'face_expression': face_expressions, 'betas': betas, 'n': n, 'frame_index2fit_index': frame_index2fit_index, 'is_male': is_male,", "# Bx1 arrays rx, ry, rz = torch.split(rot_dir, 1, dim=1)", "3, 3).detach().cpu().numpy() pose_body = np.zeros(63) for i in range(0, pose_body_mats.shape[0]):", "j < len(req_srt): if req_srt[j] == id_ss_srt[i]: req_srt_pos[j] = id_ss_pos[i]", "pose_body_mats = vposer.decode(pose_body_vp).reshape(len(loaded), -1, 3, 3).detach().cpu().numpy() pose_body = np.zeros((pose_body_mats.shape[0], 63))", "dev_lbl: dev_id += 1 dev_orient = None dev_trans = None", "vposer.decode(pose_body_vp).reshape(len(loaded), -1, 3, 3).detach().cpu().numpy() pose_body = np.zeros((pose_body_mats.shape[0], 63)) for i", "-3:] result['global_tvecs'] = loaded[:, -6:-3] result['n'] = len(loaded) else: result[k]", "> 0: dev_orient = np.load(part_path + '/dev_orient.npy') dev_trans = np.load(part_path", "0:32]) # convert from vposer to rotation matrices pose_body_list =", "except: print(load_fp) raise Exception() if fn_no_ext == 'poses': #load the", "0:32]) #convert from vposer to rotation matrices pose_body_mats = vposer.decode(pose_body_vp).reshape(len(loaded),", "ss_sort = np.argsort(id_sel_set) req_sort = np.argsort(req_ids) id_ss_srt = id_sel_set[ss_sort] id_ss_pos", "cv2.Rodrigues(rot[i].reshape(3, 1))[0] dev_mat = cv2.Rodrigues(dev_orient.reshape(3, 1))[0] rot_mat = dev_mat @", "loaded[:, -3:] result['global_tvecs'] = loaded[:, -6:-3] result['n'] = len(loaded) else:", "1e2 betas = np.load(part_path + '/betas.npy') fid_lst = np.load(part_path +", "[load_body_poses, 'body_poses', 'poses'], [load_expressions, 'expressions', 'expressions'], [load_fid_lst, 'fid_lst', 'fid_lst'] ]:", "req_ids[req_sort] req_srt_pos = -1 * np.ones(len(req_srt), dtype=int) i = 0", "batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): ''' Calculates the rotation matrices for a", "pose_body = loaded[:, 0:32] else: vposer, _ = load_vposer(vposer_ckpt, vp_model='snapshot')", "0: dev_orient = np.load(part_path + '/dev_orient.npy') dev_trans = np.load(part_path +", "ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat = ident + sin", "dev_lst[dev_id] != dev_lbl: dev_id += 1 dev_orient = None dev_trans", "-3:] trans = poses[:, -6:-3] if is_vposer: pose_body_vp = torch.tensor(poses[:,", "range(0, pose_body_mats.shape[0]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i]) pose_body[3 * i: 3", "= torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros],", "[load_betas, 'betas', 'betas'], [load_body_poses, 'body_poses', 'poses'], [load_expressions, 'expressions', 'expressions'], [load_fid_lst,", "np.load(part_path + '/expressions.npy')[:-1] * 1e2 betas = np.load(part_path + '/betas.npy')", "given axis-angle parameters ''' batch_size = rot_vecs.shape[0] device = rot_vecs.device", "= loaded[:, 0:32] else: vposer, _ = load_vposer(vposer_ckpt, vp_model='snapshot') vposer.eval()", "rot_vec, jac = cv2.Rodrigues(pose_body_mats[i,j]) pose_body[i, 3*j : 3*j+3] = rot_vec.reshape(-1)", "!= {len(poses)}' assert len(fid_lst) == len(face_expressions), f'{len(fid_lst)} != {len(face_expressions)}' n", "ident + sin * K + (1 - cos) *", "we use vposer embeddings is_vposer = config['is_vposer'] # gender of", "cv2.Rodrigues(rot_mat)[0].reshape(-1) trans[i] = (dev_mat @ trans[i].reshape(3, 1) + dev_trans.reshape(3, 1)).reshape(-1)", "load_vposer(vposer_ckpt, vp_model='snapshot') vposer.eval() pose_body_vp = torch.tensor(loaded[:, 0:32]) #convert from vposer", "dev_id > 0: dev_orient = np.load(part_path + '/dev_orient.npy') dev_trans =", "import json from human_body_prior.tools.model_loader import load_vposer import torch vposer_ckpt =", "rotation matrices pose_body_list = [] for i in range(n): pose_body_mats", "cv2.Rodrigues(pose_body_mats[i,j]) pose_body[i, 3*j : 3*j+3] = rot_vec.reshape(-1) result[k] = pose_body", "R: torch.tensor Nx3x3 The rotation matrices for the given axis-angle", "loaded[:, 0:32] else: vposer, _ = load_vposer(vposer_ckpt, vp_model='snapshot') vposer.eval() pose_body_vp", "poses[:, -3:] trans = poses[:, -6:-3] if is_vposer: pose_body_vp =", "angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) rot_dir = rot_vecs", "i in range(n): rot_mat = cv2.Rodrigues(rot[i].reshape(3, 1))[0] dev_mat = cv2.Rodrigues(dev_orient.reshape(3,", "json from human_body_prior.tools.model_loader import load_vposer import torch vposer_ckpt = '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/'", "j += 1 elif req_srt[j] < id_ss_srt[i]: j += 1", "numpy as np import cv2 import os.path as osp import", "the device) assert len(fid_lst) == len(poses), f'{len(fid_lst)} != {len(poses)}' assert", "K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) zeros = torch.zeros((batch_size,", "dim=1) # Bx1 arrays rx, ry, rz = torch.split(rot_dir, 1,", "i + 3] = rot_vec.reshape(-1) pose_body_list.append(pose_body) pose_body = np.array(pose_body_list) pose_jaw", "-ry, rx, zeros], dim=1) \\ .view((batch_size, 3, 3)) ident =", "= np.array(pose_body_list) pose_jaw = poses[:, 32:35] pose_eye = poses[:, 35:41]", "# gender of a subject is_male = config['is_male'] # id", "elif id_ss_srt[i] < req_srt[j]: i += 1 req_ids_ans = -1", "if loaded.shape[1] == 69: pose_body = loaded[:, 0:32] else: vposer,", "== len(face_expressions), f'{len(fid_lst)} != {len(face_expressions)}' n = len(poses) frame_index2fit_index =", "vectors Returns ------- R: torch.tensor Nx3x3 The rotation matrices for", "pose_body_mats.shape[0]): for j in range(0, pose_body_mats.shape[1]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i,j])", "'/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/' def load_avakhitov_fits_vposer(vposer, part_path, dev_lbl): poses = np.load(part_path + '/poses.npy')[:-1]", "+ 1e-8, dim=1, keepdim=True) rot_dir = rot_vecs / angle cos", "+ 3] = rot_vec.reshape(-1) pose_body_list.append(pose_body) pose_body = np.array(pose_body_list) pose_jaw =", "rot = poses[:, -3:] trans = poses[:, -6:-3] if is_vposer:", "72:-6] if dev_orient is not None: for i in range(n):", "dtype=torch.float32): ''' Calculates the rotation matrices for a batch of", "device=device).unsqueeze(dim=0) rot_mat = ident + sin * K + (1", "range(n) } # load the device pose dev_lst = config['dev_lst']", "+ '/poses.npy')[:-1] face_expressions = np.load(part_path + '/expressions.npy')[:-1] * 1e2 betas", "---------- rot_vecs: torch.tensor Nx3 array of N axis-angle vectors Returns", "load_avakhitov_fits(dp, load_betas=True, load_body_poses=True, load_expressions=False, load_fid_lst=True): result = dict() for flag,", "a device (used to decode the rigid pose of the", "f'{len(fid_lst)} != {len(poses)}' assert len(fid_lst) == len(face_expressions), f'{len(fid_lst)} != {len(face_expressions)}'", "1 j += 1 elif req_srt[j] < id_ss_srt[i]: j +=", "of a subject is_male = config['is_male'] # id of a", "range(n): pose_body_mats = vposer.decode(pose_body_vp[i]).reshape(-1, 3, 3).detach().cpu().numpy() pose_body = np.zeros(63) for", "pose dev_lst = config['dev_lst'] dev_id = 0 while dev_lst[dev_id] !=", "torch.zeros((batch_size, 1), dtype=dtype, device=device) K = torch.cat([zeros, -rz, ry, rz,", "+ dev_trans.reshape(3, 1)).reshape(-1) result = { 'global_rvec': rot, 'global_tvec': trans,", "rx, zeros], dim=1) \\ .view((batch_size, 3, 3)) ident = torch.eye(3,", "len(face_expressions), f'{len(fid_lst)} != {len(face_expressions)}' n = len(poses) frame_index2fit_index = {", "n = len(poses) frame_index2fit_index = { fid_lst[i]: i for i", "fn_no_ext in [ [load_betas, 'betas', 'betas'], [load_body_poses, 'body_poses', 'poses'], [load_expressions,", "Calculates the rotation matrices for a batch of rotation vectors", "len(poses), f'{len(fid_lst)} != {len(poses)}' assert len(fid_lst) == len(face_expressions), f'{len(fid_lst)} !=", "cos) * torch.bmm(K, K) return rot_mat def get_selected_ids(id_sel_set, req_ids): ss_sort", "dev_mat = cv2.Rodrigues(dev_orient.reshape(3, 1))[0] rot_mat = dev_mat @ rot_mat rot[i]", "Bx1 arrays rx, ry, rz = torch.split(rot_dir, 1, dim=1) K", "as f: config = json.load(f) # do we use vposer", "len(fid_lst) == len(poses), f'{len(fid_lst)} != {len(poses)}' assert len(fid_lst) == len(face_expressions),", "matrices pose_body_list = [] for i in range(n): pose_body_mats =", "angle cos = torch.unsqueeze(torch.cos(angle), dim=1) sin = torch.unsqueeze(torch.sin(angle), dim=1) #", "pose_body[3 * i: 3 * i + 3] = rot_vec.reshape(-1)", "pose_body_list = [] for i in range(n): pose_body_mats = vposer.decode(pose_body_vp[i]).reshape(-1,", "np.zeros(63) for i in range(0, pose_body_mats.shape[0]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i])", "'fid_lst'] ]: if flag: load_fp = osp.join(dp, f'{fn_no_ext}.npy') try: loaded", "the rigid pose of the device) assert len(fid_lst) == len(poses),", "load_fid_lst=True): result = dict() for flag, k, fn_no_ext in [", "torch.unsqueeze(torch.cos(angle), dim=1) sin = torch.unsqueeze(torch.sin(angle), dim=1) # Bx1 arrays rx,", "3).detach().cpu().numpy() pose_body = np.zeros(63) for i in range(0, pose_body_mats.shape[0]): rot_vec,", "torch.tensor Nx3x3 The rotation matrices for the given axis-angle parameters", "3*j : 3*j+3] = rot_vec.reshape(-1) result[k] = pose_body result['global_rvecs'] =", "part_path, dev_lbl): poses = np.load(part_path + '/poses.npy')[:-1] face_expressions = np.load(part_path", "sin * K + (1 - cos) * torch.bmm(K, K)", "is_vposer } return result def load_avakhitov_fits(dp, load_betas=True, load_body_poses=True, load_expressions=False, load_fid_lst=True):", "np.load(part_path + '/poses.npy')[:-1] face_expressions = np.load(part_path + '/expressions.npy')[:-1] * 1e2", "in range(n): rot_mat = cv2.Rodrigues(rot[i].reshape(3, 1))[0] dev_mat = cv2.Rodrigues(dev_orient.reshape(3, 1))[0]", "- cos) * torch.bmm(K, K) return rot_mat def get_selected_ids(id_sel_set, req_ids):", "@ trans[i].reshape(3, 1) + dev_trans.reshape(3, 1)).reshape(-1) result = { 'global_rvec':", "j += 1 elif id_ss_srt[i] < req_srt[j]: i += 1", "_ = load_vposer(vposer_ckpt, vp_model='snapshot') vposer.eval() pose_body_vp = torch.tensor(loaded[:, 0:32]) #convert", "= rot_vec.reshape(-1) result[k] = pose_body result['global_rvecs'] = loaded[:, -3:] result['global_tvecs']", "config = json.load(f) # do we use vposer embeddings is_vposer", "'/betas.npy') fid_lst = np.load(part_path + '/fid_lst.npy') with open(part_path + '/config.json',", "j = 0 while i < len(id_ss_srt) and j <", "'frame_index2fit_index': frame_index2fit_index, 'is_male': is_male, 'is_vposer': is_vposer } return result def", "= poses[:, 35:41] pose_hand = poses[:, 41:-6] else: pose_body =", "return rot_mat def get_selected_ids(id_sel_set, req_ids): ss_sort = np.argsort(id_sel_set) req_sort =", "0 while i < len(id_ss_srt) and j < len(req_srt): if", "= torch.split(rot_dir, 1, dim=1) K = torch.zeros((batch_size, 3, 3), dtype=dtype,", "trans[i].reshape(3, 1) + dev_trans.reshape(3, 1)).reshape(-1) result = { 'global_rvec': rot,", "-6:-3] if is_vposer: pose_body_vp = torch.tensor(poses[:, 0:32]) # convert from", "= -1 * np.ones(len(req_srt), dtype=int) req_ids_ans[req_sort] = req_srt_pos return req_ids_ans", "3, 3).detach().cpu().numpy() pose_body = np.zeros((pose_body_mats.shape[0], 63)) for i in range(0,", "+ '/config.json', 'r') as f: config = json.load(f) # do", "np.load(part_path + '/fid_lst.npy') with open(part_path + '/config.json', 'r') as f:", "= pose_body result['global_rvecs'] = loaded[:, -3:] result['global_tvecs'] = loaded[:, -6:-3]", "pose_body, 'hand_pose': pose_hand, 'jaw_pose': pose_jaw, 'eye_pose': pose_eye, 'face_expression': face_expressions, 'betas':", "len(id_sel_set))[ss_sort] req_srt = req_ids[req_sort] req_srt_pos = -1 * np.ones(len(req_srt), dtype=int)", "1) + dev_trans.reshape(3, 1)).reshape(-1) result = { 'global_rvec': rot, 'global_tvec':", "import cv2 import os.path as osp import json from human_body_prior.tools.model_loader", "== len(poses), f'{len(fid_lst)} != {len(poses)}' assert len(fid_lst) == len(face_expressions), f'{len(fid_lst)}", "ry, rz = torch.split(rot_dir, 1, dim=1) K = torch.zeros((batch_size, 3,", "load the device pose dev_lst = config['dev_lst'] dev_id = 0", "arrays rx, ry, rz = torch.split(rot_dir, 1, dim=1) K =", "Parameters ---------- rot_vecs: torch.tensor Nx3 array of N axis-angle vectors", "3 * i + 3] = rot_vec.reshape(-1) pose_body_list.append(pose_body) pose_body =", "< len(req_srt): if req_srt[j] == id_ss_srt[i]: req_srt_pos[j] = id_ss_pos[i] i", "0 while dev_lst[dev_id] != dev_lbl: dev_id += 1 dev_orient =", "'global_rvec': rot, 'global_tvec': trans, 'body_pose': pose_body, 'hand_pose': pose_hand, 'jaw_pose': pose_jaw,", "face_expressions, 'betas': betas, 'n': n, 'frame_index2fit_index': frame_index2fit_index, 'is_male': is_male, 'is_vposer':", "rotation vectors Parameters ---------- rot_vecs: torch.tensor Nx3 array of N", "id_ss_srt = id_sel_set[ss_sort] id_ss_pos = np.arange(0, len(id_sel_set))[ss_sort] req_srt = req_ids[req_sort]", "pose_body[i, 3*j : 3*j+3] = rot_vec.reshape(-1) result[k] = pose_body result['global_rvecs']", "= load_vposer(vposer_ckpt, vp_model='snapshot') vposer.eval() pose_body_vp = torch.tensor(loaded[:, 0:32]) #convert from", "i in range(n): pose_body_mats = vposer.decode(pose_body_vp[i]).reshape(-1, 3, 3).detach().cpu().numpy() pose_body =", "for i in range(n): rot_mat = cv2.Rodrigues(rot[i].reshape(3, 1))[0] dev_mat =", "(dev_mat @ trans[i].reshape(3, 1) + dev_trans.reshape(3, 1)).reshape(-1) result = {", "K) return rot_mat def get_selected_ids(id_sel_set, req_ids): ss_sort = np.argsort(id_sel_set) req_sort", "torch.tensor Nx3 array of N axis-angle vectors Returns ------- R:", "import numpy as np import cv2 import os.path as osp", "poses[:, 32:35] pose_eye = poses[:, 35:41] pose_hand = poses[:, 41:-6]", "rotation matrices pose_body_mats = vposer.decode(pose_body_vp).reshape(len(loaded), -1, 3, 3).detach().cpu().numpy() pose_body =", "for i in range(n) } # load the device pose", "np.argsort(id_sel_set) req_sort = np.argsort(req_ids) id_ss_srt = id_sel_set[ss_sort] id_ss_pos = np.arange(0,", "'poses'], [load_expressions, 'expressions', 'expressions'], [load_fid_lst, 'fid_lst', 'fid_lst'] ]: if flag:", "result def load_avakhitov_fits(dp, load_betas=True, load_body_poses=True, load_expressions=False, load_fid_lst=True): result = dict()", "32:35] pose_eye = poses[:, 35:41] pose_hand = poses[:, 41:-6] else:", "3*j+3] = rot_vec.reshape(-1) result[k] = pose_body result['global_rvecs'] = loaded[:, -3:]", "with open(part_path + '/config.json', 'r') as f: config = json.load(f)", "i in range(0, pose_body_mats.shape[0]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i]) pose_body[3 *", "'global_tvec': trans, 'body_pose': pose_body, 'hand_pose': pose_hand, 'jaw_pose': pose_jaw, 'eye_pose': pose_eye,", "'/dev_orient.npy') dev_trans = np.load(part_path + '/dev_trans.npy') rot = poses[:, -3:]", "vposer embeddings is_vposer = config['is_vposer'] # gender of a subject", "pose_eye = poses[:, 66:72] pose_hand = poses[:, 72:-6] if dev_orient", "= vposer.decode(pose_body_vp[i]).reshape(-1, 3, 3).detach().cpu().numpy() pose_body = np.zeros(63) for i in", "while i < len(id_ss_srt) and j < len(req_srt): if req_srt[j]", "torch.bmm(K, K) return rot_mat def get_selected_ids(id_sel_set, req_ids): ss_sort = np.argsort(id_sel_set)", "= json.load(f) # do we use vposer embeddings is_vposer =", "req_srt[j] == id_ss_srt[i]: req_srt_pos[j] = id_ss_pos[i] i += 1 j", "frame_index2fit_index = { fid_lst[i]: i for i in range(n) }", "result[k] = loaded return result def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): '''", "id_ss_srt[i] < req_srt[j]: i += 1 req_ids_ans = -1 *", "''' Calculates the rotation matrices for a batch of rotation", "result['global_rvecs'] = loaded[:, -3:] result['global_tvecs'] = loaded[:, -6:-3] result['n'] =", "= None dev_trans = None if dev_id > 0: dev_orient", "#convert from vposer to rotation matrices pose_body_mats = vposer.decode(pose_body_vp).reshape(len(loaded), -1,", "= rot_vecs.device angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) rot_dir", "face_expressions = np.load(part_path + '/expressions.npy')[:-1] * 1e2 betas = np.load(part_path", "* K + (1 - cos) * torch.bmm(K, K) return", "i for i in range(n) } # load the device", "result['n'] = len(loaded) else: result[k] = loaded return result def", "= id_sel_set[ss_sort] id_ss_pos = np.arange(0, len(id_sel_set))[ss_sort] req_srt = req_ids[req_sort] req_srt_pos", "assert len(fid_lst) == len(poses), f'{len(fid_lst)} != {len(poses)}' assert len(fid_lst) ==", "elif req_srt[j] < id_ss_srt[i]: j += 1 elif id_ss_srt[i] <", "convert from vposer to rotation matrices pose_body_list = [] for", "rot_vecs.shape[0] device = rot_vecs.device angle = torch.norm(rot_vecs + 1e-8, dim=1,", "= np.arange(0, len(id_sel_set))[ss_sort] req_srt = req_ids[req_sort] req_srt_pos = -1 *", "= np.load(part_path + '/fid_lst.npy') with open(part_path + '/config.json', 'r') as", "# id of a device (used to decode the rigid", "{len(poses)}' assert len(fid_lst) == len(face_expressions), f'{len(fid_lst)} != {len(face_expressions)}' n =", "config['dev_lst'] dev_id = 0 while dev_lst[dev_id] != dev_lbl: dev_id +=", "cv2.Rodrigues(pose_body_mats[i]) pose_body[3 * i: 3 * i + 3] =", "pose_body = np.array(pose_body_list) pose_jaw = poses[:, 32:35] pose_eye = poses[:,", "+ '/fid_lst.npy') with open(part_path + '/config.json', 'r') as f: config", "0 j = 0 while i < len(id_ss_srt) and j", "< id_ss_srt[i]: j += 1 elif id_ss_srt[i] < req_srt[j]: i", "dtype=dtype, device=device).unsqueeze(dim=0) rot_mat = ident + sin * K +", "betas, 'n': n, 'frame_index2fit_index': frame_index2fit_index, 'is_male': is_male, 'is_vposer': is_vposer }", "from vposer to rotation matrices pose_body_list = [] for i", "= rot_vecs / angle cos = torch.unsqueeze(torch.cos(angle), dim=1) sin =", "to rotation matrices pose_body_list = [] for i in range(n):", "dev_orient = np.load(part_path + '/dev_orient.npy') dev_trans = np.load(part_path + '/dev_trans.npy')", "1e-8, dim=1, keepdim=True) rot_dir = rot_vecs / angle cos =", "if req_srt[j] == id_ss_srt[i]: req_srt_pos[j] = id_ss_pos[i] i += 1", "pose_body_vp = torch.tensor(poses[:, 0:32]) # convert from vposer to rotation", "+ '/dev_orient.npy') dev_trans = np.load(part_path + '/dev_trans.npy') rot = poses[:,", "== id_ss_srt[i]: req_srt_pos[j] = id_ss_pos[i] i += 1 j +=", "{len(face_expressions)}' n = len(poses) frame_index2fit_index = { fid_lst[i]: i for", "'jaw_pose': pose_jaw, 'eye_pose': pose_eye, 'face_expression': face_expressions, 'betas': betas, 'n': n,", "< req_srt[j]: i += 1 req_ids_ans = -1 * np.ones(len(req_srt),", "1))[0] dev_mat = cv2.Rodrigues(dev_orient.reshape(3, 1))[0] rot_mat = dev_mat @ rot_mat", "torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1)", "} # load the device pose dev_lst = config['dev_lst'] dev_id", "pose_jaw, 'eye_pose': pose_eye, 'face_expression': face_expressions, 'betas': betas, 'n': n, 'frame_index2fit_index':", "== 'poses': #load the vposer model if loaded.shape[1] == 69:", "is not None: for i in range(n): rot_mat = cv2.Rodrigues(rot[i].reshape(3,", "in [ [load_betas, 'betas', 'betas'], [load_body_poses, 'body_poses', 'poses'], [load_expressions, 'expressions',", "= cv2.Rodrigues(rot_mat)[0].reshape(-1) trans[i] = (dev_mat @ trans[i].reshape(3, 1) + dev_trans.reshape(3,", "if is_vposer: pose_body_vp = torch.tensor(poses[:, 0:32]) # convert from vposer", "= config['is_male'] # id of a device (used to decode", "load_body_poses=True, load_expressions=False, load_fid_lst=True): result = dict() for flag, k, fn_no_ext", "vposer.eval() pose_body_vp = torch.tensor(loaded[:, 0:32]) #convert from vposer to rotation", "import torch vposer_ckpt = '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/' def load_avakhitov_fits_vposer(vposer, part_path, dev_lbl): poses", "load_expressions=False, load_fid_lst=True): result = dict() for flag, k, fn_no_ext in", "} return result def load_avakhitov_fits(dp, load_betas=True, load_body_poses=True, load_expressions=False, load_fid_lst=True): result", "'r') as f: config = json.load(f) # do we use", "dev_orient = None dev_trans = None if dev_id > 0:", "j in range(0, pose_body_mats.shape[1]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i,j]) pose_body[i, 3*j", "* i + 3] = rot_vec.reshape(-1) pose_body_list.append(pose_body) pose_body = np.array(pose_body_list)", "'/expressions.npy')[:-1] * 1e2 betas = np.load(part_path + '/betas.npy') fid_lst =", "+= 1 j += 1 elif req_srt[j] < id_ss_srt[i]: j", "None: for i in range(n): rot_mat = cv2.Rodrigues(rot[i].reshape(3, 1))[0] dev_mat", "{ 'global_rvec': rot, 'global_tvec': trans, 'body_pose': pose_body, 'hand_pose': pose_hand, 'jaw_pose':", "np.load(load_fp) except: print(load_fp) raise Exception() if fn_no_ext == 'poses': #load", "for j in range(0, pose_body_mats.shape[1]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i,j]) pose_body[i,", "np.zeros((pose_body_mats.shape[0], 63)) for i in range(0, pose_body_mats.shape[0]): for j in", "i in range(n) } # load the device pose dev_lst", "load_fp = osp.join(dp, f'{fn_no_ext}.npy') try: loaded = np.load(load_fp) except: print(load_fp)", "rz = torch.split(rot_dir, 1, dim=1) K = torch.zeros((batch_size, 3, 3),", "poses[:, 35:41] pose_hand = poses[:, 41:-6] else: pose_body = poses[:,", "f: config = json.load(f) # do we use vposer embeddings", "= cv2.Rodrigues(pose_body_mats[i,j]) pose_body[i, 3*j : 3*j+3] = rot_vec.reshape(-1) result[k] =", "= ident + sin * K + (1 - cos)", "(1 - cos) * torch.bmm(K, K) return rot_mat def get_selected_ids(id_sel_set,", "a subject is_male = config['is_male'] # id of a device", "= torch.unsqueeze(torch.cos(angle), dim=1) sin = torch.unsqueeze(torch.sin(angle), dim=1) # Bx1 arrays", "= np.load(part_path + '/poses.npy')[:-1] face_expressions = np.load(part_path + '/expressions.npy')[:-1] *", "= torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat = ident + sin *", "+ '/expressions.npy')[:-1] * 1e2 betas = np.load(part_path + '/betas.npy') fid_lst", "np.ones(len(req_srt), dtype=int) i = 0 j = 0 while i", "Nx3x3 The rotation matrices for the given axis-angle parameters '''", "def get_selected_ids(id_sel_set, req_ids): ss_sort = np.argsort(id_sel_set) req_sort = np.argsort(req_ids) id_ss_srt", "len(id_ss_srt) and j < len(req_srt): if req_srt[j] == id_ss_srt[i]: req_srt_pos[j]", "config['is_vposer'] # gender of a subject is_male = config['is_male'] #", "torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat = ident + sin * K", "= poses[:, 72:-6] if dev_orient is not None: for i", "[load_fid_lst, 'fid_lst', 'fid_lst'] ]: if flag: load_fp = osp.join(dp, f'{fn_no_ext}.npy')", "trans = poses[:, -6:-3] if is_vposer: pose_body_vp = torch.tensor(poses[:, 0:32])", "K + (1 - cos) * torch.bmm(K, K) return rot_mat", "def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): ''' Calculates the rotation matrices for", "frame_index2fit_index, 'is_male': is_male, 'is_vposer': is_vposer } return result def load_avakhitov_fits(dp,", "id_ss_srt[i]: j += 1 elif id_ss_srt[i] < req_srt[j]: i +=", "= -1 * np.ones(len(req_srt), dtype=int) i = 0 j =", "pose_jaw = poses[:, 32:35] pose_eye = poses[:, 35:41] pose_hand =", "pose_body_mats.shape[1]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i,j]) pose_body[i, 3*j : 3*j+3] =", "1 elif req_srt[j] < id_ss_srt[i]: j += 1 elif id_ss_srt[i]", "of the device) assert len(fid_lst) == len(poses), f'{len(fid_lst)} != {len(poses)}'", "dev_mat @ rot_mat rot[i] = cv2.Rodrigues(rot_mat)[0].reshape(-1) trans[i] = (dev_mat @", "to rotation matrices pose_body_mats = vposer.decode(pose_body_vp).reshape(len(loaded), -1, 3, 3).detach().cpu().numpy() pose_body", "3)) ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat = ident +", "rot_vec, jac = cv2.Rodrigues(pose_body_mats[i]) pose_body[3 * i: 3 * i", "'/dev_trans.npy') rot = poses[:, -3:] trans = poses[:, -6:-3] if", "vp_model='snapshot') vposer.eval() pose_body_vp = torch.tensor(loaded[:, 0:32]) #convert from vposer to", "dev_lbl): poses = np.load(part_path + '/poses.npy')[:-1] face_expressions = np.load(part_path +", "trans[i] = (dev_mat @ trans[i].reshape(3, 1) + dev_trans.reshape(3, 1)).reshape(-1) result", "range(n): rot_mat = cv2.Rodrigues(rot[i].reshape(3, 1))[0] dev_mat = cv2.Rodrigues(dev_orient.reshape(3, 1))[0] rot_mat", "fid_lst[i]: i for i in range(n) } # load the", "to decode the rigid pose of the device) assert len(fid_lst)", "= cv2.Rodrigues(pose_body_mats[i]) pose_body[3 * i: 3 * i + 3]", "load_vposer import torch vposer_ckpt = '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/' def load_avakhitov_fits_vposer(vposer, part_path, dev_lbl):", "rot[i] = cv2.Rodrigues(rot_mat)[0].reshape(-1) trans[i] = (dev_mat @ trans[i].reshape(3, 1) +", "poses = np.load(part_path + '/poses.npy')[:-1] face_expressions = np.load(part_path + '/expressions.npy')[:-1]", "sin = torch.unsqueeze(torch.sin(angle), dim=1) # Bx1 arrays rx, ry, rz", "is_vposer = config['is_vposer'] # gender of a subject is_male =", "3), dtype=dtype, device=device) zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) K", "osp.join(dp, f'{fn_no_ext}.npy') try: loaded = np.load(load_fp) except: print(load_fp) raise Exception()", "pose_hand = poses[:, 41:-6] else: pose_body = poses[:, 0:63] pose_jaw", "= poses[:, 66:72] pose_hand = poses[:, 72:-6] if dev_orient is", "------- R: torch.tensor Nx3x3 The rotation matrices for the given", "= loaded[:, -6:-3] result['n'] = len(loaded) else: result[k] = loaded", "\\ .view((batch_size, 3, 3)) ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat", "41:-6] else: pose_body = poses[:, 0:63] pose_jaw = poses[:, 63:66]", "rot, 'global_tvec': trans, 'body_pose': pose_body, 'hand_pose': pose_hand, 'jaw_pose': pose_jaw, 'eye_pose':", "get_selected_ids(id_sel_set, req_ids): ss_sort = np.argsort(id_sel_set) req_sort = np.argsort(req_ids) id_ss_srt =", "= loaded[:, -3:] result['global_tvecs'] = loaded[:, -6:-3] result['n'] = len(loaded)", "= { 'global_rvec': rot, 'global_tvec': trans, 'body_pose': pose_body, 'hand_pose': pose_hand,", "gender of a subject is_male = config['is_male'] # id of", "dev_id += 1 dev_orient = None dev_trans = None if", "os.path as osp import json from human_body_prior.tools.model_loader import load_vposer import", "np.array(pose_body_list) pose_jaw = poses[:, 32:35] pose_eye = poses[:, 35:41] pose_hand", "n, 'frame_index2fit_index': frame_index2fit_index, 'is_male': is_male, 'is_vposer': is_vposer } return result", "= rot_vecs.shape[0] device = rot_vecs.device angle = torch.norm(rot_vecs + 1e-8,", "< len(id_ss_srt) and j < len(req_srt): if req_srt[j] == id_ss_srt[i]:", "-1, 3, 3).detach().cpu().numpy() pose_body = np.zeros((pose_body_mats.shape[0], 63)) for i in", "id_ss_srt[i]: req_srt_pos[j] = id_ss_pos[i] i += 1 j += 1", "= torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) rot_dir = rot_vecs /", "flag, k, fn_no_ext in [ [load_betas, 'betas', 'betas'], [load_body_poses, 'body_poses',", "id_ss_pos[i] i += 1 j += 1 elif req_srt[j] <", "= np.load(part_path + '/dev_orient.npy') dev_trans = np.load(part_path + '/dev_trans.npy') rot", "dev_orient is not None: for i in range(n): rot_mat =", "load_avakhitov_fits_vposer(vposer, part_path, dev_lbl): poses = np.load(part_path + '/poses.npy')[:-1] face_expressions =", "vposer.decode(pose_body_vp[i]).reshape(-1, 3, 3).detach().cpu().numpy() pose_body = np.zeros(63) for i in range(0,", "= poses[:, 41:-6] else: pose_body = poses[:, 0:63] pose_jaw =", "-rx, -ry, rx, zeros], dim=1) \\ .view((batch_size, 3, 3)) ident", "range(0, pose_body_mats.shape[0]): for j in range(0, pose_body_mats.shape[1]): rot_vec, jac =", "= req_ids[req_sort] req_srt_pos = -1 * np.ones(len(req_srt), dtype=int) i =", "dev_trans = np.load(part_path + '/dev_trans.npy') rot = poses[:, -3:] trans", "model if loaded.shape[1] == 69: pose_body = loaded[:, 0:32] else:", "The rotation matrices for the given axis-angle parameters ''' batch_size", "if flag: load_fp = osp.join(dp, f'{fn_no_ext}.npy') try: loaded = np.load(load_fp)", "]: if flag: load_fp = osp.join(dp, f'{fn_no_ext}.npy') try: loaded =", "req_ids): ss_sort = np.argsort(id_sel_set) req_sort = np.argsort(req_ids) id_ss_srt = id_sel_set[ss_sort]", "def load_avakhitov_fits_vposer(vposer, part_path, dev_lbl): poses = np.load(part_path + '/poses.npy')[:-1] face_expressions", "pose_hand = poses[:, 72:-6] if dev_orient is not None: for", "poses[:, 72:-6] if dev_orient is not None: for i in", "1 dev_orient = None dev_trans = None if dev_id >", "Nx3 array of N axis-angle vectors Returns ------- R: torch.tensor", "from human_body_prior.tools.model_loader import load_vposer import torch vposer_ckpt = '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/' def", "rot_vec.reshape(-1) result[k] = pose_body result['global_rvecs'] = loaded[:, -3:] result['global_tvecs'] =", "np.load(part_path + '/dev_trans.npy') rot = poses[:, -3:] trans = poses[:,", "rot_mat = ident + sin * K + (1 -", "cos = torch.unsqueeze(torch.cos(angle), dim=1) sin = torch.unsqueeze(torch.sin(angle), dim=1) # Bx1", "return result def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): ''' Calculates the rotation", "rot_mat rot[i] = cv2.Rodrigues(rot_mat)[0].reshape(-1) trans[i] = (dev_mat @ trans[i].reshape(3, 1)", "pose_eye = poses[:, 35:41] pose_hand = poses[:, 41:-6] else: pose_body", "matrices pose_body_mats = vposer.decode(pose_body_vp).reshape(len(loaded), -1, 3, 3).detach().cpu().numpy() pose_body = np.zeros((pose_body_mats.shape[0],", "for the given axis-angle parameters ''' batch_size = rot_vecs.shape[0] device", "1)).reshape(-1) result = { 'global_rvec': rot, 'global_tvec': trans, 'body_pose': pose_body,", "from vposer to rotation matrices pose_body_mats = vposer.decode(pose_body_vp).reshape(len(loaded), -1, 3,", "pose_body_mats.shape[0]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i]) pose_body[3 * i: 3 *", "np.argsort(req_ids) id_ss_srt = id_sel_set[ss_sort] id_ss_pos = np.arange(0, len(id_sel_set))[ss_sort] req_srt =", "axis-angle vectors Returns ------- R: torch.tensor Nx3x3 The rotation matrices", "= rot_vec.reshape(-1) pose_body_list.append(pose_body) pose_body = np.array(pose_body_list) pose_jaw = poses[:, 32:35]", "= cv2.Rodrigues(rot[i].reshape(3, 1))[0] dev_mat = cv2.Rodrigues(dev_orient.reshape(3, 1))[0] rot_mat = dev_mat", "i += 1 j += 1 elif req_srt[j] < id_ss_srt[i]:", "3, 3), dtype=dtype, device=device) zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device)", "decode the rigid pose of the device) assert len(fid_lst) ==", "betas = np.load(part_path + '/betas.npy') fid_lst = np.load(part_path + '/fid_lst.npy')", "def load_avakhitov_fits(dp, load_betas=True, load_body_poses=True, load_expressions=False, load_fid_lst=True): result = dict() for", "cv2.Rodrigues(dev_orient.reshape(3, 1))[0] rot_mat = dev_mat @ rot_mat rot[i] = cv2.Rodrigues(rot_mat)[0].reshape(-1)", "poses[:, 63:66] pose_eye = poses[:, 66:72] pose_hand = poses[:, 72:-6]", "!= {len(face_expressions)}' n = len(poses) frame_index2fit_index = { fid_lst[i]: i", "= vposer.decode(pose_body_vp).reshape(len(loaded), -1, 3, 3).detach().cpu().numpy() pose_body = np.zeros((pose_body_mats.shape[0], 63)) for", "i < len(id_ss_srt) and j < len(req_srt): if req_srt[j] ==", "= torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) zeros = torch.zeros((batch_size, 1),", "#load the vposer model if loaded.shape[1] == 69: pose_body =", "loaded return result def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): ''' Calculates the", "batch_size = rot_vecs.shape[0] device = rot_vecs.device angle = torch.norm(rot_vecs +", "K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx,", "rot_mat def get_selected_ids(id_sel_set, req_ids): ss_sort = np.argsort(id_sel_set) req_sort = np.argsort(req_ids)", "torch vposer_ckpt = '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/' def load_avakhitov_fits_vposer(vposer, part_path, dev_lbl): poses =", "device (used to decode the rigid pose of the device)", "len(loaded) else: result[k] = loaded return result def batch_rodrigues(rot_vecs, epsilon=1e-8,", "is_male = config['is_male'] # id of a device (used to", "pose of the device) assert len(fid_lst) == len(poses), f'{len(fid_lst)} !=", "= poses[:, 63:66] pose_eye = poses[:, 66:72] pose_hand = poses[:,", "jac = cv2.Rodrigues(pose_body_mats[i,j]) pose_body[i, 3*j : 3*j+3] = rot_vec.reshape(-1) result[k]", "len(fid_lst) == len(face_expressions), f'{len(fid_lst)} != {len(face_expressions)}' n = len(poses) frame_index2fit_index", "'hand_pose': pose_hand, 'jaw_pose': pose_jaw, 'eye_pose': pose_eye, 'face_expression': face_expressions, 'betas': betas,", "return result def load_avakhitov_fits(dp, load_betas=True, load_body_poses=True, load_expressions=False, load_fid_lst=True): result =", "the device pose dev_lst = config['dev_lst'] dev_id = 0 while", "* np.ones(len(req_srt), dtype=int) i = 0 j = 0 while", "pose_body = np.zeros((pose_body_mats.shape[0], 63)) for i in range(0, pose_body_mats.shape[0]): for", "result = dict() for flag, k, fn_no_ext in [ [load_betas,", "for i in range(0, pose_body_mats.shape[0]): for j in range(0, pose_body_mats.shape[1]):", "i = 0 j = 0 while i < len(id_ss_srt)", "'betas', 'betas'], [load_body_poses, 'body_poses', 'poses'], [load_expressions, 'expressions', 'expressions'], [load_fid_lst, 'fid_lst',", "dim=1) K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) zeros =", "66:72] pose_hand = poses[:, 72:-6] if dev_orient is not None:", "flag: load_fp = osp.join(dp, f'{fn_no_ext}.npy') try: loaded = np.load(load_fp) except:", "* torch.bmm(K, K) return rot_mat def get_selected_ids(id_sel_set, req_ids): ss_sort =", "device) assert len(fid_lst) == len(poses), f'{len(fid_lst)} != {len(poses)}' assert len(fid_lst)", "ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\ .view((batch_size,", "= 0 while dev_lst[dev_id] != dev_lbl: dev_id += 1 dev_orient", "0:32] else: vposer, _ = load_vposer(vposer_ckpt, vp_model='snapshot') vposer.eval() pose_body_vp =", "dim=1) \\ .view((batch_size, 3, 3)) ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)", "pose_body = poses[:, 0:63] pose_jaw = poses[:, 63:66] pose_eye =", "1, dim=1) K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) zeros", "jac = cv2.Rodrigues(pose_body_mats[i]) pose_body[3 * i: 3 * i +", "= torch.tensor(loaded[:, 0:32]) #convert from vposer to rotation matrices pose_body_mats", "vectors Parameters ---------- rot_vecs: torch.tensor Nx3 array of N axis-angle", "''' batch_size = rot_vecs.shape[0] device = rot_vecs.device angle = torch.norm(rot_vecs", "# do we use vposer embeddings is_vposer = config['is_vposer'] #", "+= 1 elif id_ss_srt[i] < req_srt[j]: i += 1 req_ids_ans", "'expressions', 'expressions'], [load_fid_lst, 'fid_lst', 'fid_lst'] ]: if flag: load_fp =", "as osp import json from human_body_prior.tools.model_loader import load_vposer import torch", "[] for i in range(n): pose_body_mats = vposer.decode(pose_body_vp[i]).reshape(-1, 3, 3).detach().cpu().numpy()", "'is_male': is_male, 'is_vposer': is_vposer } return result def load_avakhitov_fits(dp, load_betas=True,", "+ '/dev_trans.npy') rot = poses[:, -3:] trans = poses[:, -6:-3]", "/ angle cos = torch.unsqueeze(torch.cos(angle), dim=1) sin = torch.unsqueeze(torch.sin(angle), dim=1)", "in range(n): pose_body_mats = vposer.decode(pose_body_vp[i]).reshape(-1, 3, 3).detach().cpu().numpy() pose_body = np.zeros(63)", "= 0 j = 0 while i < len(id_ss_srt) and", "while dev_lst[dev_id] != dev_lbl: dev_id += 1 dev_orient = None", "for i in range(0, pose_body_mats.shape[0]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i]) pose_body[3", "torch.unsqueeze(torch.sin(angle), dim=1) # Bx1 arrays rx, ry, rz = torch.split(rot_dir,", "in range(0, pose_body_mats.shape[1]): rot_vec, jac = cv2.Rodrigues(pose_body_mats[i,j]) pose_body[i, 3*j :", "try: loaded = np.load(load_fp) except: print(load_fp) raise Exception() if fn_no_ext", "vposer_ckpt = '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/' def load_avakhitov_fits_vposer(vposer, part_path, dev_lbl): poses = np.load(part_path", "rotation matrices for a batch of rotation vectors Parameters ----------", "= poses[:, 32:35] pose_eye = poses[:, 35:41] pose_hand = poses[:,", "dtype=dtype, device=device) K = torch.cat([zeros, -rz, ry, rz, zeros, -rx,", "f'{fn_no_ext}.npy') try: loaded = np.load(load_fp) except: print(load_fp) raise Exception() if", "'is_vposer': is_vposer } return result def load_avakhitov_fits(dp, load_betas=True, load_body_poses=True, load_expressions=False,", "poses[:, 66:72] pose_hand = poses[:, 72:-6] if dev_orient is not", "of rotation vectors Parameters ---------- rot_vecs: torch.tensor Nx3 array of", "rot_dir = rot_vecs / angle cos = torch.unsqueeze(torch.cos(angle), dim=1) sin", "config['is_male'] # id of a device (used to decode the", "req_srt_pos = -1 * np.ones(len(req_srt), dtype=int) i = 0 j", "dev_id = 0 while dev_lst[dev_id] != dev_lbl: dev_id += 1", "'eye_pose': pose_eye, 'face_expression': face_expressions, 'betas': betas, 'n': n, 'frame_index2fit_index': frame_index2fit_index," ]
[ "= get_completion_percentage(line) if percent: progress_bar.update(percent - last_percent) last_percent = percent", "We also need to catch APIError as if the image", "new_tag) os.remove(f\"{path}/Dockerfile\") # We do not want to republish an", "tqdm from typing import Union, Any, Optional def build_image(repo_url: str,", "deleted or has expired. To pull, revive via time machine\"", "we check if the new # pair repo:tag already exists.", "Optional[str] = None, ) -> None: with open(f\"{path}/Dockerfile\", \"w\") as", "(docker.errors.ImageNotFound, docker.errors.APIError) as e: pass print(f\"Pushing to {new_repo_url}:{new_tag}\") client.images.push(new_repo_url, new_tag)", "repo \"\"\" dockerfile_text = render(image_type, [\".\"]) with open(f\"{path}/Dockerfile\", \"w\") as", "not None for value in [username, password, registry]): client.login(username=username, password=password,", "build_and_push_operator creates the Dockerfile for the operator and pushes it", "100 if result > 100.0: return 100.0 return result return", "if percent: progress_bar.update(percent - last_percent) last_percent = percent def retag_image(", "from tqdm import tqdm from typing import Union, Any, Optional", "0.0 for line in client.images.push(tag, stream=True): percent = get_completion_percentage(line) if", "get_completion_percentage(line: Any) -> float: try: line = json.loads(line.strip().decode(\"utf-8\")) except ValueError:", "docker.from_env() print(f\"Pushing image: {tag}\") with tqdm(total=100, ascii=False) as progress_bar: last_percent", "happen?) # we will get this kind of error: #", "\"\"\" client = docker.from_env() print(f\"Building image: {tag}\") client.images.build(tag=tag, path=path) print(\"Successfully", "or has expired. To pull, revive via time machine\" except", "pushes the given tag. It uses the current docker environment", "changed, so we check if the new # pair repo:tag", ") -> None: with open(f\"{path}/Dockerfile\", \"w\") as f: f.write(f\"FROM {old_repo_url}:{old_tag}\")", "\"Layer already exists\") if \"status\" in line: if line[\"status\"] in", "client.images.build(path=f\"{path}\", labels=labels, tag=new_tag) image.tag(new_repo_url, new_tag) os.remove(f\"{path}/Dockerfile\") # We do not", "as progress_bar: last_percent = 0.0 for line in client.images.push(tag, stream=True):", "image = client.images.pull(new_repo_url, new_tag) return # We also need to", "Error # (\"unknown: Tag <tag> was deleted or has expired.", "Server Error # (\"unknown: Tag <tag> was deleted or has", "return # We also need to catch APIError as if", "f.write(f\"FROM {old_repo_url}:{old_tag}\") client = docker.from_env() if all(value is not None", "has expired. To pull, revive via time machine\" except (docker.errors.ImageNotFound,", "docker from dockerfile_generator import render import os import json from", "republish an image that has not changed, so we check", "<tag> was deleted or has expired. To pull, revive via", "dockerfile_text = render(image_type, [\".\"]) with open(f\"{path}/Dockerfile\", \"w\") as f: f.write(dockerfile_text)", "return 0 result = (current / total) * 100 if", "not changed, so we check if the new # pair", "if all(value is not None for value in [username, password,", "with tqdm(total=100, ascii=False) as progress_bar: last_percent = 0.0 for line", "value in [username, password, registry]): client.login(username=username, password=password, registry=registry) image, _", "print(f\"Pushing to {new_repo_url}:{new_tag}\") client.images.push(new_repo_url, new_tag) def get_completion_percentage(line: Any) -> float:", "= render(image_type, [\".\"]) with open(f\"{path}/Dockerfile\", \"w\") as f: f.write(dockerfile_text) build_image(repo_url,", "def retag_image( old_repo_url: str, new_repo_url: str, old_tag: str, new_tag: str,", "recently deleted (uncommon, but might happen?) # we will get", "with open(f\"{path}/Dockerfile\", \"w\") as f: f.write(f\"FROM {old_repo_url}:{old_tag}\") client = docker.from_env()", "\"w\") as f: f.write(f\"FROM {old_repo_url}:{old_tag}\") client = docker.from_env() if all(value", "pair repo:tag already exists. try: image = client.images.pull(new_repo_url, new_tag) return", "been recently deleted (uncommon, but might happen?) # we will", "if line[\"status\"] == \"Pushing\": try: current = float(line[\"progressDetail\"][\"current\"]) total =", "render import os import json from tqdm import tqdm from", "= (current / total) * 100 if result > 100.0:", "already exists. try: image = client.images.pull(new_repo_url, new_tag) return # We", "= (\"Preparing\", \"Waiting\", \"Layer already exists\") if \"status\" in line:", "client.images.pull(new_repo_url, new_tag) return # We also need to catch APIError", "== \"Pushing\": try: current = float(line[\"progressDetail\"][\"current\"]) total = float(line[\"progressDetail\"][\"total\"]) except", "as f: f.write(f\"FROM {old_repo_url}:{old_tag}\") client = docker.from_env() if all(value is", "(\"unknown: Tag <tag> was deleted or has expired. To pull,", "line[\"status\"] == \"Pushing\": try: current = float(line[\"progressDetail\"][\"current\"]) total = float(line[\"progressDetail\"][\"total\"])", "None: \"\"\" push_image pushes the given tag. It uses the", "client.login(username=username, password=password, registry=registry) image, _ = client.images.build(path=f\"{path}\", labels=labels, tag=new_tag) image.tag(new_repo_url,", "to the target repo \"\"\" dockerfile_text = render(image_type, [\".\"]) with", "tag=new_tag) image.tag(new_repo_url, new_tag) os.remove(f\"{path}/Dockerfile\") # We do not want to", "labels: Optional[dict] = None, username: Optional[str] = None, password: Optional[str]", "the operator and pushes it to the target repo \"\"\"", "in to_skip: return 0 if line[\"status\"] == \"Pushing\": try: current", "to republish an image that has not changed, so we", "path=path) print(\"Successfully built image!\") def push_image(tag: str) -> None: \"\"\"", "import docker from dockerfile_generator import render import os import json", "image_type: str) -> None: \"\"\" build_and_push_operator creates the Dockerfile for", "os.remove(f\"{path}/Dockerfile\") # We do not want to republish an image", "current docker environment \"\"\" client = docker.from_env() print(f\"Pushing image: {tag}\")", "get_completion_percentage(line) if percent: progress_bar.update(percent - last_percent) last_percent = percent def", "to_skip = (\"Preparing\", \"Waiting\", \"Layer already exists\") if \"status\" in", "# (\"unknown: Tag <tag> was deleted or has expired. To", "str, labels: Optional[dict] = None, username: Optional[str] = None, password:", "registry=registry) image, _ = client.images.build(path=f\"{path}\", labels=labels, tag=new_tag) image.tag(new_repo_url, new_tag) os.remove(f\"{path}/Dockerfile\")", "current = float(line[\"progressDetail\"][\"current\"]) total = float(line[\"progressDetail\"][\"total\"]) except KeyError: return 0", "Tag <tag> was deleted or has expired. To pull, revive", "str, image_type: str) -> None: \"\"\" build_and_push_operator creates the Dockerfile", "also need to catch APIError as if the image has", "will get this kind of error: # docker.errors.APIError: 500 Server", "str, path: str) -> None: \"\"\" build_image builds the image", "Internal Server Error # (\"unknown: Tag <tag> was deleted or", "\"status\" in line: if line[\"status\"] in to_skip: return 0 if", "{old_repo_url}:{old_tag}\") client = docker.from_env() if all(value is not None for", "KeyError: return 0 result = (current / total) * 100", "Optional[str] = None, password: Optional[str] = None, registry: Optional[str] =", "import Union, Any, Optional def build_image(repo_url: str, tag: str, path:", "if \"status\" in line: if line[\"status\"] in to_skip: return 0", "the given tag \"\"\" client = docker.from_env() print(f\"Building image: {tag}\")", "docker.from_env() print(f\"Building image: {tag}\") client.images.build(tag=tag, path=path) print(\"Successfully built image!\") def", "def build_and_push_image(repo_url: str, tag: str, path: str, image_type: str) ->", "percent: progress_bar.update(percent - last_percent) last_percent = percent def retag_image( old_repo_url:", "= docker.from_env() print(f\"Pushing image: {tag}\") with tqdm(total=100, ascii=False) as progress_bar:", "str) -> None: \"\"\" build_and_push_operator creates the Dockerfile for the", "image: {tag}\") client.images.build(tag=tag, path=path) print(\"Successfully built image!\") def push_image(tag: str)", "typing import Union, Any, Optional def build_image(repo_url: str, tag: str,", "retag_image( old_repo_url: str, new_repo_url: str, old_tag: str, new_tag: str, path:", "client.images.push(new_repo_url, new_tag) def get_completion_percentage(line: Any) -> float: try: line =", "\"\"\" push_image pushes the given tag. It uses the current", "total) * 100 if result > 100.0: return 100.0 return", "in client.images.push(tag, stream=True): percent = get_completion_percentage(line) if percent: progress_bar.update(percent -", "None, registry: Optional[str] = None, ) -> None: with open(f\"{path}/Dockerfile\",", "repo:tag already exists. try: image = client.images.pull(new_repo_url, new_tag) return #", "import json from tqdm import tqdm from typing import Union,", "is not None for value in [username, password, registry]): client.login(username=username,", "print(f\"Building image: {tag}\") client.images.build(tag=tag, path=path) print(\"Successfully built image!\") def push_image(tag:", "labels=labels, tag=new_tag) image.tag(new_repo_url, new_tag) os.remove(f\"{path}/Dockerfile\") # We do not want", "want to republish an image that has not changed, so", "= client.images.pull(new_repo_url, new_tag) return # We also need to catch", "stream=True): percent = get_completion_percentage(line) if percent: progress_bar.update(percent - last_percent) last_percent", "need to catch APIError as if the image has been", "password=password, registry=registry) image, _ = client.images.build(path=f\"{path}\", labels=labels, tag=new_tag) image.tag(new_repo_url, new_tag)", "catch APIError as if the image has been recently deleted", "old_repo_url: str, new_repo_url: str, old_tag: str, new_tag: str, path: str,", "in line: if line[\"status\"] in to_skip: return 0 if line[\"status\"]", "(current / total) * 100 if result > 100.0: return", "revive via time machine\" except (docker.errors.ImageNotFound, docker.errors.APIError) as e: pass", "registry: Optional[str] = None, ) -> None: with open(f\"{path}/Dockerfile\", \"w\")", "tag: str, path: str, image_type: str) -> None: \"\"\" build_and_push_operator", "with open(f\"{path}/Dockerfile\", \"w\") as f: f.write(dockerfile_text) build_image(repo_url, tag, path) os.remove(f\"{path}/Dockerfile\")", "* 100 if result > 100.0: return 100.0 return result", "float(line[\"progressDetail\"][\"total\"]) except KeyError: return 0 result = (current / total)", "the given tag. It uses the current docker environment \"\"\"", "the Dockerfile for the operator and pushes it to the", "print(\"Successfully built image!\") def push_image(tag: str) -> None: \"\"\" push_image", "# docker.errors.APIError: 500 Server Error: Internal Server Error # (\"unknown:", "Optional def build_image(repo_url: str, tag: str, path: str) -> None:", "was deleted or has expired. To pull, revive via time", "if the image has been recently deleted (uncommon, but might", "line = json.loads(line.strip().decode(\"utf-8\")) except ValueError: return 0 to_skip = (\"Preparing\",", "0 result = (current / total) * 100 if result", "str, tag: str, path: str) -> None: \"\"\" build_image builds", "\"\"\" build_and_push_operator creates the Dockerfile for the operator and pushes", "target repo \"\"\" dockerfile_text = render(image_type, [\".\"]) with open(f\"{path}/Dockerfile\", \"w\")", "# pair repo:tag already exists. try: image = client.images.pull(new_repo_url, new_tag)", "image: {tag}\") with tqdm(total=100, ascii=False) as progress_bar: last_percent = 0.0", "for line in client.images.push(tag, stream=True): percent = get_completion_percentage(line) if percent:", "the image has been recently deleted (uncommon, but might happen?)", "{tag}\") with tqdm(total=100, ascii=False) as progress_bar: last_percent = 0.0 for", "client = docker.from_env() print(f\"Building image: {tag}\") client.images.build(tag=tag, path=path) print(\"Successfully built", "new_tag) return # We also need to catch APIError as", "the current docker environment \"\"\" client = docker.from_env() print(f\"Pushing image:", "not want to republish an image that has not changed,", "docker environment \"\"\" client = docker.from_env() print(f\"Pushing image: {tag}\") with", "= float(line[\"progressDetail\"][\"current\"]) total = float(line[\"progressDetail\"][\"total\"]) except KeyError: return 0 result", "str) -> None: \"\"\" push_image pushes the given tag. It", "import os import json from tqdm import tqdm from typing", "json.loads(line.strip().decode(\"utf-8\")) except ValueError: return 0 to_skip = (\"Preparing\", \"Waiting\", \"Layer", "def push_image(tag: str) -> None: \"\"\" push_image pushes the given", "f: f.write(f\"FROM {old_repo_url}:{old_tag}\") client = docker.from_env() if all(value is not", "already exists\") if \"status\" in line: if line[\"status\"] in to_skip:", "the target repo \"\"\" dockerfile_text = render(image_type, [\".\"]) with open(f\"{path}/Dockerfile\",", "build_image builds the image with the given tag \"\"\" client", "new # pair repo:tag already exists. try: image = client.images.pull(new_repo_url,", "of error: # docker.errors.APIError: 500 Server Error: Internal Server Error", "operator and pushes it to the target repo \"\"\" dockerfile_text", "= json.loads(line.strip().decode(\"utf-8\")) except ValueError: return 0 to_skip = (\"Preparing\", \"Waiting\",", "from typing import Union, Any, Optional def build_image(repo_url: str, tag:", "Error: Internal Server Error # (\"unknown: Tag <tag> was deleted", "deleted (uncommon, but might happen?) # we will get this", "for the operator and pushes it to the target repo", "via time machine\" except (docker.errors.ImageNotFound, docker.errors.APIError) as e: pass print(f\"Pushing", "expired. To pull, revive via time machine\" except (docker.errors.ImageNotFound, docker.errors.APIError)", "we will get this kind of error: # docker.errors.APIError: 500", "image!\") def push_image(tag: str) -> None: \"\"\" push_image pushes the", "None: with open(f\"{path}/Dockerfile\", \"w\") as f: f.write(f\"FROM {old_repo_url}:{old_tag}\") client =", "= percent def retag_image( old_repo_url: str, new_repo_url: str, old_tag: str,", "Dockerfile for the operator and pushes it to the target", "docker.errors.APIError) as e: pass print(f\"Pushing to {new_repo_url}:{new_tag}\") client.images.push(new_repo_url, new_tag) def", "client = docker.from_env() print(f\"Pushing image: {tag}\") with tqdm(total=100, ascii=False) as", "get this kind of error: # docker.errors.APIError: 500 Server Error:", "Optional[str] = None, registry: Optional[str] = None, ) -> None:", "-> float: try: line = json.loads(line.strip().decode(\"utf-8\")) except ValueError: return 0", "image.tag(new_repo_url, new_tag) os.remove(f\"{path}/Dockerfile\") # We do not want to republish", "str, new_repo_url: str, old_tag: str, new_tag: str, path: str, labels:", "image with the given tag \"\"\" client = docker.from_env() print(f\"Building", "import render import os import json from tqdm import tqdm", "tag. It uses the current docker environment \"\"\" client =", "given tag. It uses the current docker environment \"\"\" client", "try: current = float(line[\"progressDetail\"][\"current\"]) total = float(line[\"progressDetail\"][\"total\"]) except KeyError: return", "os import json from tqdm import tqdm from typing import", "0 to_skip = (\"Preparing\", \"Waiting\", \"Layer already exists\") if \"status\"", "all(value is not None for value in [username, password, registry]):", "= docker.from_env() print(f\"Building image: {tag}\") client.images.build(tag=tag, path=path) print(\"Successfully built image!\")", "if result > 100.0: return 100.0 return result return 0", "but might happen?) # we will get this kind of", "that has not changed, so we check if the new", "client.images.build(tag=tag, path=path) print(\"Successfully built image!\") def push_image(tag: str) -> None:", "total = float(line[\"progressDetail\"][\"total\"]) except KeyError: return 0 result = (current", "docker.errors.APIError: 500 Server Error: Internal Server Error # (\"unknown: Tag", "str, new_tag: str, path: str, labels: Optional[dict] = None, username:", "\"\"\" build_image builds the image with the given tag \"\"\"", "do not want to republish an image that has not", "kind of error: # docker.errors.APIError: 500 Server Error: Internal Server", "= client.images.build(path=f\"{path}\", labels=labels, tag=new_tag) image.tag(new_repo_url, new_tag) os.remove(f\"{path}/Dockerfile\") # We do", "# We do not want to republish an image that", "{new_repo_url}:{new_tag}\") client.images.push(new_repo_url, new_tag) def get_completion_percentage(line: Any) -> float: try: line", "Any) -> float: try: line = json.loads(line.strip().decode(\"utf-8\")) except ValueError: return", "check if the new # pair repo:tag already exists. try:", "dockerfile_generator import render import os import json from tqdm import", "so we check if the new # pair repo:tag already", "image has been recently deleted (uncommon, but might happen?) #", "has been recently deleted (uncommon, but might happen?) # we", "the image with the given tag \"\"\" client = docker.from_env()", "str) -> None: \"\"\" build_image builds the image with the", "line in client.images.push(tag, stream=True): percent = get_completion_percentage(line) if percent: progress_bar.update(percent", "line: if line[\"status\"] in to_skip: return 0 if line[\"status\"] ==", "as e: pass print(f\"Pushing to {new_repo_url}:{new_tag}\") client.images.push(new_repo_url, new_tag) def get_completion_percentage(line:", "if line[\"status\"] in to_skip: return 0 if line[\"status\"] == \"Pushing\":", "\"\"\" dockerfile_text = render(image_type, [\".\"]) with open(f\"{path}/Dockerfile\", \"w\") as f:", "creates the Dockerfile for the operator and pushes it to", "as if the image has been recently deleted (uncommon, but", "e: pass print(f\"Pushing to {new_repo_url}:{new_tag}\") client.images.push(new_repo_url, new_tag) def get_completion_percentage(line: Any)", "return 0 if line[\"status\"] == \"Pushing\": try: current = float(line[\"progressDetail\"][\"current\"])", "has not changed, so we check if the new #", "None, password: Optional[str] = None, registry: Optional[str] = None, )", "tqdm import tqdm from typing import Union, Any, Optional def", "_ = client.images.build(path=f\"{path}\", labels=labels, tag=new_tag) image.tag(new_repo_url, new_tag) os.remove(f\"{path}/Dockerfile\") # We", "return result return 0 def build_and_push_image(repo_url: str, tag: str, path:", "percent = get_completion_percentage(line) if percent: progress_bar.update(percent - last_percent) last_percent =", "new_tag: str, path: str, labels: Optional[dict] = None, username: Optional[str]", "json from tqdm import tqdm from typing import Union, Any,", "0 def build_and_push_image(repo_url: str, tag: str, path: str, image_type: str)", "open(f\"{path}/Dockerfile\", \"w\") as f: f.write(f\"FROM {old_repo_url}:{old_tag}\") client = docker.from_env() if", "\"Waiting\", \"Layer already exists\") if \"status\" in line: if line[\"status\"]", "str, path: str, labels: Optional[dict] = None, username: Optional[str] =", "None, username: Optional[str] = None, password: Optional[str] = None, registry:", "new_tag) def get_completion_percentage(line: Any) -> float: try: line = json.loads(line.strip().decode(\"utf-8\"))", "path: str) -> None: \"\"\" build_image builds the image with", "It uses the current docker environment \"\"\" client = docker.from_env()", "pull, revive via time machine\" except (docker.errors.ImageNotFound, docker.errors.APIError) as e:", "- last_percent) last_percent = percent def retag_image( old_repo_url: str, new_repo_url:", "except KeyError: return 0 result = (current / total) *", "last_percent = 0.0 for line in client.images.push(tag, stream=True): percent =", "return 0 to_skip = (\"Preparing\", \"Waiting\", \"Layer already exists\") if", "line[\"status\"] in to_skip: return 0 if line[\"status\"] == \"Pushing\": try:", "= 0.0 for line in client.images.push(tag, stream=True): percent = get_completion_percentage(line)", "try: line = json.loads(line.strip().decode(\"utf-8\")) except ValueError: return 0 to_skip =", "float: try: line = json.loads(line.strip().decode(\"utf-8\")) except ValueError: return 0 to_skip", "it to the target repo \"\"\" dockerfile_text = render(image_type, [\".\"])", "to {new_repo_url}:{new_tag}\") client.images.push(new_repo_url, new_tag) def get_completion_percentage(line: Any) -> float: try:", "Optional[dict] = None, username: Optional[str] = None, password: Optional[str] =", "the new # pair repo:tag already exists. try: image =", "100.0: return 100.0 return result return 0 def build_and_push_image(repo_url: str,", "and pushes it to the target repo \"\"\" dockerfile_text =", "def build_image(repo_url: str, tag: str, path: str) -> None: \"\"\"", "push_image(tag: str) -> None: \"\"\" push_image pushes the given tag.", "None: \"\"\" build_image builds the image with the given tag", "last_percent) last_percent = percent def retag_image( old_repo_url: str, new_repo_url: str,", "Union, Any, Optional def build_image(repo_url: str, tag: str, path: str)", "return 100.0 return result return 0 def build_and_push_image(repo_url: str, tag:", "APIError as if the image has been recently deleted (uncommon,", "ascii=False) as progress_bar: last_percent = 0.0 for line in client.images.push(tag,", "path: str, image_type: str) -> None: \"\"\" build_and_push_operator creates the", "an image that has not changed, so we check if", "with the given tag \"\"\" client = docker.from_env() print(f\"Building image:", "0 if line[\"status\"] == \"Pushing\": try: current = float(line[\"progressDetail\"][\"current\"]) total", "client = docker.from_env() if all(value is not None for value", "uses the current docker environment \"\"\" client = docker.from_env() print(f\"Pushing", "500 Server Error: Internal Server Error # (\"unknown: Tag <tag>", "result = (current / total) * 100 if result >", "open(f\"{path}/Dockerfile\", \"w\") as f: f.write(dockerfile_text) build_image(repo_url, tag, path) os.remove(f\"{path}/Dockerfile\") push_image(tag)", "username: Optional[str] = None, password: Optional[str] = None, registry: Optional[str]", "time machine\" except (docker.errors.ImageNotFound, docker.errors.APIError) as e: pass print(f\"Pushing to", "{tag}\") client.images.build(tag=tag, path=path) print(\"Successfully built image!\") def push_image(tag: str) ->", "= None, ) -> None: with open(f\"{path}/Dockerfile\", \"w\") as f:", "progress_bar: last_percent = 0.0 for line in client.images.push(tag, stream=True): percent", "None, ) -> None: with open(f\"{path}/Dockerfile\", \"w\") as f: f.write(f\"FROM", "machine\" except (docker.errors.ImageNotFound, docker.errors.APIError) as e: pass print(f\"Pushing to {new_repo_url}:{new_tag}\")", "str, tag: str, path: str, image_type: str) -> None: \"\"\"", "= docker.from_env() if all(value is not None for value in", "-> None: \"\"\" push_image pushes the given tag. It uses", "/ total) * 100 if result > 100.0: return 100.0", "result return 0 def build_and_push_image(repo_url: str, tag: str, path: str,", "print(f\"Pushing image: {tag}\") with tqdm(total=100, ascii=False) as progress_bar: last_percent =", "pushes it to the target repo \"\"\" dockerfile_text = render(image_type,", "import tqdm from typing import Union, Any, Optional def build_image(repo_url:", "# we will get this kind of error: # docker.errors.APIError:", "progress_bar.update(percent - last_percent) last_percent = percent def retag_image( old_repo_url: str,", "def get_completion_percentage(line: Any) -> float: try: line = json.loads(line.strip().decode(\"utf-8\")) except", "except (docker.errors.ImageNotFound, docker.errors.APIError) as e: pass print(f\"Pushing to {new_repo_url}:{new_tag}\") client.images.push(new_repo_url,", "return 0 def build_and_push_image(repo_url: str, tag: str, path: str, image_type:", "password, registry]): client.login(username=username, password=password, registry=registry) image, _ = client.images.build(path=f\"{path}\", labels=labels,", "registry]): client.login(username=username, password=password, registry=registry) image, _ = client.images.build(path=f\"{path}\", labels=labels, tag=new_tag)", "> 100.0: return 100.0 return result return 0 def build_and_push_image(repo_url:", "# We also need to catch APIError as if the", "ValueError: return 0 to_skip = (\"Preparing\", \"Waiting\", \"Layer already exists\")", "pass print(f\"Pushing to {new_repo_url}:{new_tag}\") client.images.push(new_repo_url, new_tag) def get_completion_percentage(line: Any) ->", "build_image(repo_url: str, tag: str, path: str) -> None: \"\"\" build_image", "percent def retag_image( old_repo_url: str, new_repo_url: str, old_tag: str, new_tag:", "exists. try: image = client.images.pull(new_repo_url, new_tag) return # We also", "None for value in [username, password, registry]): client.login(username=username, password=password, registry=registry)", "this kind of error: # docker.errors.APIError: 500 Server Error: Internal", "environment \"\"\" client = docker.from_env() print(f\"Pushing image: {tag}\") with tqdm(total=100,", "builds the image with the given tag \"\"\" client =", "except ValueError: return 0 to_skip = (\"Preparing\", \"Waiting\", \"Layer already", "[\".\"]) with open(f\"{path}/Dockerfile\", \"w\") as f: f.write(dockerfile_text) build_image(repo_url, tag, path)", "render(image_type, [\".\"]) with open(f\"{path}/Dockerfile\", \"w\") as f: f.write(dockerfile_text) build_image(repo_url, tag,", "password: Optional[str] = None, registry: Optional[str] = None, ) ->", "str, path: str, image_type: str) -> None: \"\"\" build_and_push_operator creates", "= None, registry: Optional[str] = None, ) -> None: with", "-> None: \"\"\" build_image builds the image with the given", "\"Pushing\": try: current = float(line[\"progressDetail\"][\"current\"]) total = float(line[\"progressDetail\"][\"total\"]) except KeyError:", "image that has not changed, so we check if the", "in [username, password, registry]): client.login(username=username, password=password, registry=registry) image, _ =", "path: str, labels: Optional[dict] = None, username: Optional[str] = None,", "(uncommon, but might happen?) # we will get this kind", "new_repo_url: str, old_tag: str, new_tag: str, path: str, labels: Optional[dict]", "To pull, revive via time machine\" except (docker.errors.ImageNotFound, docker.errors.APIError) as", "given tag \"\"\" client = docker.from_env() print(f\"Building image: {tag}\") client.images.build(tag=tag,", "image, _ = client.images.build(path=f\"{path}\", labels=labels, tag=new_tag) image.tag(new_repo_url, new_tag) os.remove(f\"{path}/Dockerfile\") #", "push_image pushes the given tag. It uses the current docker", "docker.from_env() if all(value is not None for value in [username,", "Any, Optional def build_image(repo_url: str, tag: str, path: str) ->", "client.images.push(tag, stream=True): percent = get_completion_percentage(line) if percent: progress_bar.update(percent - last_percent)", "from dockerfile_generator import render import os import json from tqdm", "tag \"\"\" client = docker.from_env() print(f\"Building image: {tag}\") client.images.build(tag=tag, path=path)", "error: # docker.errors.APIError: 500 Server Error: Internal Server Error #", "if the new # pair repo:tag already exists. try: image", "-> None: \"\"\" build_and_push_operator creates the Dockerfile for the operator", "to catch APIError as if the image has been recently", "built image!\") def push_image(tag: str) -> None: \"\"\" push_image pushes", "last_percent = percent def retag_image( old_repo_url: str, new_repo_url: str, old_tag:", "float(line[\"progressDetail\"][\"current\"]) total = float(line[\"progressDetail\"][\"total\"]) except KeyError: return 0 result =", "try: image = client.images.pull(new_repo_url, new_tag) return # We also need", "(\"Preparing\", \"Waiting\", \"Layer already exists\") if \"status\" in line: if", "We do not want to republish an image that has", "build_and_push_image(repo_url: str, tag: str, path: str, image_type: str) -> None:", "None: \"\"\" build_and_push_operator creates the Dockerfile for the operator and", "exists\") if \"status\" in line: if line[\"status\"] in to_skip: return", "Server Error: Internal Server Error # (\"unknown: Tag <tag> was", "result > 100.0: return 100.0 return result return 0 def", "might happen?) # we will get this kind of error:", "for value in [username, password, registry]): client.login(username=username, password=password, registry=registry) image,", "= float(line[\"progressDetail\"][\"total\"]) except KeyError: return 0 result = (current /", "-> None: with open(f\"{path}/Dockerfile\", \"w\") as f: f.write(f\"FROM {old_repo_url}:{old_tag}\") client", "old_tag: str, new_tag: str, path: str, labels: Optional[dict] = None,", "= None, username: Optional[str] = None, password: Optional[str] = None,", "to_skip: return 0 if line[\"status\"] == \"Pushing\": try: current =", "str, old_tag: str, new_tag: str, path: str, labels: Optional[dict] =", "100.0 return result return 0 def build_and_push_image(repo_url: str, tag: str,", "= None, password: Optional[str] = None, registry: Optional[str] = None,", "tqdm(total=100, ascii=False) as progress_bar: last_percent = 0.0 for line in", "[username, password, registry]): client.login(username=username, password=password, registry=registry) image, _ = client.images.build(path=f\"{path}\",", "tag: str, path: str) -> None: \"\"\" build_image builds the", "\"\"\" client = docker.from_env() print(f\"Pushing image: {tag}\") with tqdm(total=100, ascii=False)" ]
[ "filename format is for example lc_bams.gatk.xxxx.vcf.gz, where lc_bams is the", "<gh_stars>1-10 from VcfFilter import VcfFilter import argparse import os #get", "for example lc_bams.gatk.xxxx.vcf.gz, where lc_bams is the analysis group and", "is the analysis group and gatk is the method used'", "gatk is the method used' ) parser.add_argument('--type', type=str, required=False, help='Type", "a certain variant type from a VCF file') #parameters parser.add_argument('--bcftools_folder',", "a VCF file') #parameters parser.add_argument('--bcftools_folder', type=str, required=True, help='Folder containing the", "os #get command line arguments parser = argparse.ArgumentParser(description='Script to select", "from VcfFilter import VcfFilter import argparse import os #get command", "that the filename format is for example lc_bams.gatk.xxxx.vcf.gz, where lc_bams", "to select. i.e. snps/indels etc' ) args = parser.parse_args() if", "= argparse.ArgumentParser(description='Script to select a certain variant type from a", "file') #parameters parser.add_argument('--bcftools_folder', type=str, required=True, help='Folder containing the Bcftools binary'", "required=True, help='Name (without the fullpath) of the VCF file that", "assumes that the filename format is for example lc_bams.gatk.xxxx.vcf.gz, where", "be analysed. It assumes that the filename format is for", "format is for example lc_bams.gatk.xxxx.vcf.gz, where lc_bams is the analysis", "parser = argparse.ArgumentParser(description='Script to select a certain variant type from", "select. i.e. snps/indels etc' ) args = parser.parse_args() if __name__", "required=False, help='Type of variant to select. i.e. snps/indels etc' )", "analysis group and gatk is the method used' ) parser.add_argument('--type',", "the filename format is for example lc_bams.gatk.xxxx.vcf.gz, where lc_bams is", "and gatk is the method used' ) parser.add_argument('--type', type=str, required=False,", "arguments parser = argparse.ArgumentParser(description='Script to select a certain variant type", ") parser.add_argument('--type', type=str, required=False, help='Type of variant to select. i.e.", "import argparse import os #get command line arguments parser =", "that will be analysed. It assumes that the filename format", "certain variant type from a VCF file') #parameters parser.add_argument('--bcftools_folder', type=str,", "type=str, required=True, help='Name (without the fullpath) of the VCF file", "type=str, required=True, help='Folder containing the Bcftools binary' ) parser.add_argument('--filename', type=str,", "etc' ) args = parser.parse_args() if __name__ == '__main__': vcf_f=VcfFilter(vcf=args.filename,bcftools_folder=args.bcftools_folder)", "variant type from a VCF file') #parameters parser.add_argument('--bcftools_folder', type=str, required=True,", "example lc_bams.gatk.xxxx.vcf.gz, where lc_bams is the analysis group and gatk", "containing the Bcftools binary' ) parser.add_argument('--filename', type=str, required=True, help='Name (without", "used' ) parser.add_argument('--type', type=str, required=False, help='Type of variant to select.", "required=True, help='Folder containing the Bcftools binary' ) parser.add_argument('--filename', type=str, required=True,", "VcfFilter import VcfFilter import argparse import os #get command line", "line arguments parser = argparse.ArgumentParser(description='Script to select a certain variant", "method used' ) parser.add_argument('--type', type=str, required=False, help='Type of variant to", "to select a certain variant type from a VCF file')", "lc_bams.gatk.xxxx.vcf.gz, where lc_bams is the analysis group and gatk is", "i.e. snps/indels etc' ) args = parser.parse_args() if __name__ ==", "of variant to select. i.e. snps/indels etc' ) args =", "command line arguments parser = argparse.ArgumentParser(description='Script to select a certain", "the fullpath) of the VCF file that will be analysed.", "Bcftools binary' ) parser.add_argument('--filename', type=str, required=True, help='Name (without the fullpath)", "file that will be analysed. It assumes that the filename", "#parameters parser.add_argument('--bcftools_folder', type=str, required=True, help='Folder containing the Bcftools binary' )", "import os #get command line arguments parser = argparse.ArgumentParser(description='Script to", "of the VCF file that will be analysed. It assumes", "fullpath) of the VCF file that will be analysed. It", "It assumes that the filename format is for example lc_bams.gatk.xxxx.vcf.gz,", "from a VCF file') #parameters parser.add_argument('--bcftools_folder', type=str, required=True, help='Folder containing", "where lc_bams is the analysis group and gatk is the", "the Bcftools binary' ) parser.add_argument('--filename', type=str, required=True, help='Name (without the", "help='Folder containing the Bcftools binary' ) parser.add_argument('--filename', type=str, required=True, help='Name", "the analysis group and gatk is the method used' )", "is the method used' ) parser.add_argument('--type', type=str, required=False, help='Type of", "argparse.ArgumentParser(description='Script to select a certain variant type from a VCF", "is for example lc_bams.gatk.xxxx.vcf.gz, where lc_bams is the analysis group", "parser.add_argument('--filename', type=str, required=True, help='Name (without the fullpath) of the VCF", "(without the fullpath) of the VCF file that will be", "the VCF file that will be analysed. It assumes that", "lc_bams is the analysis group and gatk is the method", "import VcfFilter import argparse import os #get command line arguments", "select a certain variant type from a VCF file') #parameters", "parser.add_argument('--type', type=str, required=False, help='Type of variant to select. i.e. snps/indels", "group and gatk is the method used' ) parser.add_argument('--type', type=str,", ") parser.add_argument('--filename', type=str, required=True, help='Name (without the fullpath) of the", "variant to select. i.e. snps/indels etc' ) args = parser.parse_args()", "the method used' ) parser.add_argument('--type', type=str, required=False, help='Type of variant", "binary' ) parser.add_argument('--filename', type=str, required=True, help='Name (without the fullpath) of", "VCF file') #parameters parser.add_argument('--bcftools_folder', type=str, required=True, help='Folder containing the Bcftools", ") args = parser.parse_args() if __name__ == '__main__': vcf_f=VcfFilter(vcf=args.filename,bcftools_folder=args.bcftools_folder) vcf_f.filter_by_variant_type(type=args.type)", "type=str, required=False, help='Type of variant to select. i.e. snps/indels etc'", "type from a VCF file') #parameters parser.add_argument('--bcftools_folder', type=str, required=True, help='Folder", "VCF file that will be analysed. It assumes that the", "VcfFilter import argparse import os #get command line arguments parser", "help='Name (without the fullpath) of the VCF file that will", "help='Type of variant to select. i.e. snps/indels etc' ) args", "analysed. It assumes that the filename format is for example", "#get command line arguments parser = argparse.ArgumentParser(description='Script to select a", "will be analysed. It assumes that the filename format is", "snps/indels etc' ) args = parser.parse_args() if __name__ == '__main__':", "parser.add_argument('--bcftools_folder', type=str, required=True, help='Folder containing the Bcftools binary' ) parser.add_argument('--filename',", "argparse import os #get command line arguments parser = argparse.ArgumentParser(description='Script" ]
[ "(b'$3d==', b'\\xdd'), (b'[==', b''), (b'YW]3=', b'am'), (b'3{d==', b'\\xdd'), (b'3d}==', b'\\xdd'),", "# Test default alphabet eq(base64.b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode(b'\\x00'), b'AA==') eq(base64.b64encode(b\"a\"), b\"YQ==\")", "True), res) eq(base64.b32decode(data.decode('ascii'), True), res) self.assertRaises(binascii.Error, base64.b32decode, b'me======') self.assertRaises(binascii.Error, base64.b32decode,", "'wb') as fp: fp.write(b'Yf9iCg==') output = self.get_output('-d', support.TESTFN) self.assertEqual(output.rstrip(), b'a\\xffb')", "in tests_urlsafe.items(): eq(base64.urlsafe_b64decode(data), res) eq(base64.urlsafe_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.urlsafe_b64decode(bytearray(b'01a-b_cd')), b'\\xd3V\\xbeo\\xf7\\x1d')", "data_str = data.decode('ascii') map01_str = map01.decode('ascii') eq(base64.b32decode(data, map01=map01), res) eq(base64.b32decode(data_str,", "with self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii')) def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode(b'\\x01\\x02\\xab\\xcd\\xef'), b'0102ABCDEF')", "b'\\xdd'), (b'[==', b''), (b'YW]3=', b'am'), (b'3{d==', b'\\xdd'), (b'3d}==', b'\\xdd'), (b'@@',", "for f in decode_funcs: self.assertRaises(ValueError, f, 'with non-ascii \\xcb') def", "self.assertRaises(binascii.Error, base64.b32decode, 'me======') # Mapping zero and one eq(base64.b32decode(b'MLO23456'), b'b\\xdd\\xad\\xf3\\xbe')", "eq(base64.b64encode(b\"a\"), b\"YQ==\") eq(base64.b64encode(b\"ab\"), b\"YWI=\") eq(base64.b64encode(b\"abc\"), b\"YWJj\") eq(base64.b64encode(b\"\"), b\"\") eq(base64.b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", "with self.assertRaises(binascii.Error): base64.b64decode(bstr, validate=True) with self.assertRaises(binascii.Error): base64.b64decode(bstr.decode('ascii'), validate=True) def test_b32encode(self):", "# Non-bytes eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\\n') self.assertRaises(TypeError, base64.encodebytes, \"\") def test_decodebytes(self): eq", "base64.encode, StringIO('abc'), StringIO()) def test_decode(self): from io import BytesIO, StringIO", "tests_urlsafe = {b'01a-b_cd': b'\\xd3V\\xbeo\\xf7\\x1d', b'': b'', } for data, res", "'rb') as fp: output = self.get_output('-e', stdin=fp) self.assertEqual(output.rstrip(), b'Yf9iCg==') def", "eq(base64.b16decode(b'00'), b'\\x00') eq(base64.b16decode('00'), b'\\x00') # Lower case is not allowed", "tests = {b'': b'', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc',", "b'am'), (b'3{d==', b'\\xdd'), (b'3d}==', b'\\xdd'), (b'@@', b''), (b'!', b''), (b'YWJj\\nYWI=',", "def test_ErrorHeritage(self): self.assertTrue(issubclass(binascii.Error, ValueError)) class TestMain(unittest.TestCase): def tearDown(self): if os.path.exists(support.TESTFN):", "**options): args = (sys.executable, '-m', 'base64') + args return subprocess.check_output(args,", "b'MFRGGZA=') self.assertRaises(TypeError, base64.b32encode, \"\") def test_b32decode(self): eq = self.assertEqual tests", "res) eq(base64.standard_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.standard_b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with", "for data, res in tests.items(): eq(base64.b32decode(data), res) eq(base64.b32decode(data.decode('ascii')), res) #", "for data in [b'abc', b'ABCDEF==', b'==ABCDEF']: with self.assertRaises(binascii.Error): base64.b32decode(data) with", "b'MFRGGZDF': b'abcde', # Lower cases b'me======': b'a', b'mfra====': b'ab', b'mfrgg===':", "b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray(b'abcd')), b'YWJjZA==') #", "data_str = data.decode('ascii') altchars_str = altchars.decode('ascii') eq(base64.b64decode(data, altchars=altchars), res) eq(base64.b64decode(data_str,", "{b\"d3d3LnB5dGhvbi5vcmc=\": b\"www.python.org\", b'AA==': b'\\x00', b\"YQ==\": b\"a\", b\"YWI=\": b\"ab\", b\"YWJj\": b\"abc\",", "b'AA======') eq(base64.b32encode(b'a'), b'ME======') eq(base64.b32encode(b'ab'), b'MFRA====') eq(base64.b32encode(b'abc'), b'MFRGG===') eq(base64.b32encode(b'abcd'), b'MFRGGZA=') eq(base64.b32encode(b'abcde'),", "b'abc', b'mfrggza=': b'abcd', b'mfrggzdf': b'abcde', } for data, res in", "base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), b'www.python.org') # Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'),", "is not allowed without a flag self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef') self.assertRaises(binascii.Error,", "b'\\xd3V\\xbeo\\xf7\\x1d', b'': b'', } for data, res in tests_urlsafe.items(): eq(base64.urlsafe_b64decode(data),", "[]{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray(b'abcd')), b'YWJjZA==') # Check", "\\xcb') def test_ErrorHeritage(self): self.assertTrue(issubclass(binascii.Error, ValueError)) class TestMain(unittest.TestCase): def tearDown(self): if", "support import base64 import binascii import os import sys import", "eq(base64.standard_b64encode(b\"ab\"), b\"YWI=\") eq(base64.standard_b64encode(b\"abc\"), b\"YWJj\") eq(base64.standard_b64encode(b\"\"), b\"\") eq(base64.standard_b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"),", "b\"YWJj\") eq(base64.standard_b64encode(b\"\"), b\"\") eq(base64.standard_b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\")", "eq(base64.b32decode(data_str, map01=map01_str), res) self.assertRaises(binascii.Error, base64.b32decode, data) self.assertRaises(binascii.Error, base64.b32decode, data_str) def", "base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode(b'0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102abcdef', True),", "for data, res in tests_urlsafe.items(): eq(base64.urlsafe_b64decode(data), res) eq(base64.urlsafe_b64decode(data.decode('ascii')), res) #", "StringIO('YWJj\\n'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\\n'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), StringIO())", "b\"abc\") eq(base64.decodebytes(b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodebytes(b''), b'')", "b'\\x01\\x02\\xab\\xcd\\xef') def test_decode_nonascii_str(self): decode_funcs = (base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode, base64.b32decode, base64.b16decode)", "map01=map01_str), res) self.assertRaises(binascii.Error, base64.b32decode, data) self.assertRaises(binascii.Error, base64.b32decode, data_str) def test_b32decode_error(self):", "def test_decodebytes(self): eq = self.assertEqual eq(base64.decodebytes(b\"d3d3LnB5dGhvbi5vcmc=\\n\"), b\"www.python.org\") eq(base64.decodebytes(b\"YQ==\\n\"), b\"a\") eq(base64.decodebytes(b\"YWI=\\n\"),", "alphabet for data, res in tests.items(): eq(base64.standard_b64decode(data), res) eq(base64.standard_b64decode(data.decode('ascii')), res)", "(b'YWJj\\nYWI=', b'abcab')) for bstr, res in tests: self.assertEqual(base64.b64decode(bstr), res) self.assertEqual(base64.b64decode(bstr.decode('ascii')),", "eq(base64.b64decode(data), res) eq(base64.b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test", "eq(base64.decodebytes(b''), b'') # Non-bytes eq(base64.decodebytes(bytearray(b'YWJj\\n')), b'abc') self.assertRaises(TypeError, base64.decodebytes, \"\") def", "import BytesIO, StringIO infp = BytesIO(b'd3d3LnB5dGhvbi5vcmc=') outfp = BytesIO() base64.decode(infp,", "= self.assertEqual # Test default alphabet eq(base64.b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode(b'\\x00'), b'AA==')", "eq(base64.standard_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.standard_b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with 'URL", "# Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\\n'),", "(sys.executable, '-m', 'base64') + args return subprocess.check_output(args, **options) def test_encode_decode(self):", "open(support.TESTFN, 'wb') as fp: fp.write(b'Yf9iCg==') output = self.get_output('-d', support.TESTFN) self.assertEqual(output.rstrip(),", "Test with 'URL safe' alternative characters tests_urlsafe = {b'01a-b_cd': b'\\xd3V\\xbeo\\xf7\\x1d',", "def test_b64decode_invalid_chars(self): # issue 1466065: Test some invalid characters. tests", "b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', } for data, res in", "True), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(b\"0102ABCDEF\")), b'\\x01\\x02\\xab\\xcd\\xef') def", "f, 'with non-ascii \\xcb') def test_ErrorHeritage(self): self.assertTrue(issubclass(binascii.Error, ValueError)) class TestMain(unittest.TestCase):", "b'b\\xdd\\xad\\xf3\\xbe', (b'M1023456', b'I'): b'b\\x1d\\xad\\xf3\\xbe', } for (data, map01), res in", "fp.write(b'Yf9iCg==') output = self.get_output('-d', support.TESTFN) self.assertEqual(output.rstrip(), b'a\\xffb') def test_main(): support.run_unittest(__name__)", "b'L'): b'b\\xdd\\xad\\xf3\\xbe', (b'M1023456', b'I'): b'b\\x1d\\xad\\xf3\\xbe', } for (data, map01), res", "b\"ab\", b\"YWJj\": b\"abc\", b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\": b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\",", "passing a str object raises an error self.assertRaises(TypeError, base64.b64encode, \"\")", "b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary", "eq(base64.encodebytes(b\"ab\"), b\"YWI=\\n\") eq(base64.encodebytes(b\"abc\"), b\"YWJj\\n\") eq(base64.encodebytes(b\"\"), b\"\") eq(base64.encodebytes(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"),", "b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray(b'abcd')), b'YWJjZA==') # Check if", "b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\": b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\", b'': b'', }", "open(support.TESTFN, 'rb') as fp: output = self.get_output('-e', stdin=fp) self.assertEqual(output.rstrip(), b'Yf9iCg==')", "self.get_output('-e', stdin=fp) self.assertEqual(output.rstrip(), b'Yf9iCg==') def test_decode(self): with open(support.TESTFN, 'wb') as", "b'', } for data, res in tests.items(): eq(base64.b64decode(data), res) eq(base64.b64decode(data.decode('ascii')),", "= {b'': b'', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=':", "*args, **options): args = (sys.executable, '-m', 'base64') + args return", "} for (data, map01), res in map_tests.items(): data_str = data.decode('ascii')", "Non-bytes eq(base64.standard_b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with 'URL safe' alternative characters", "with arbitrary alternative characters tests_altchars = {(b'01a*b$cd', b'*$'): b'\\xd3V\\xbeo\\xf7\\x1d', }", "res) self.assertEqual(base64.b64decode(bstr.decode('ascii')), res) with self.assertRaises(binascii.Error): base64.b64decode(bstr, validate=True) with self.assertRaises(binascii.Error): base64.b64decode(bstr.decode('ascii'),", "self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef') self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode(b'0102abcdef',", "base64.b64decode, 'abc') def test_b64decode_invalid_chars(self): # issue 1466065: Test some invalid", "eq(base64.urlsafe_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.urlsafe_b64decode(bytearray(b'01a-b_cd')), b'\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_padding_error(self): self.assertRaises(binascii.Error, base64.b64decode,", "from io import BytesIO, StringIO infp = BytesIO(b'd3d3LnB5dGhvbi5vcmc=') outfp =", "'with non-ascii \\xcb') def test_ErrorHeritage(self): self.assertTrue(issubclass(binascii.Error, ValueError)) class TestMain(unittest.TestCase): def", "Non-bytes eq(base64.b64encode(bytearray(b'abcd')), b'YWJjZA==') eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray(b'*$')), b'01a*b$cd') # Check if passing", "Non-bytes eq(base64.b16decode(bytearray(b\"0102ABCDEF\")), b'\\x01\\x02\\xab\\xcd\\xef') def test_decode_nonascii_str(self): decode_funcs = (base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode,", "for (data, map01), res in map_tests.items(): data_str = data.decode('ascii') map01_str", "in decode_funcs: self.assertRaises(ValueError, f, 'with non-ascii \\xcb') def test_ErrorHeritage(self): self.assertTrue(issubclass(binascii.Error,", "# Test standard alphabet eq(base64.standard_b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(b\"a\"), b\"YQ==\") eq(base64.standard_b64encode(b\"ab\"), b\"YWI=\")", "b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\\n') self.assertRaises(TypeError, base64.encodebytes, \"\") def", "eq = self.assertEqual # Test default alphabet eq(base64.b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode(b'\\x00'),", "b'mfra====': b'ab', b'mfrgg===': b'abc', b'mfrggza=': b'abcd', b'mfrggzdf': b'abcde', } for", "map_tests = {(b'M1023456', b'L'): b'b\\xdd\\xad\\xf3\\xbe', (b'M1023456', b'I'): b'b\\x1d\\xad\\xf3\\xbe', } for", "eq(base64.b32decode(b'MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') map_tests = {(b'M1023456', b'L'): b'b\\xdd\\xad\\xf3\\xbe', (b'M1023456',", "b'00') # Non-bytes eq(base64.b16encode(bytearray(b'\\x01\\x02\\xab\\xcd\\xef')), b'0102ABCDEF') self.assertRaises(TypeError, base64.b16encode, \"\") def test_b16decode(self):", "= {(b'M1023456', b'L'): b'b\\xdd\\xad\\xf3\\xbe', (b'M1023456', b'I'): b'b\\x1d\\xad\\xf3\\xbe', } for (data,", "self.assertRaises(TypeError, base64.decodebytes, \"\") def test_encode(self): eq = self.assertEqual from io", "self.assertEqual eq(base64.b16encode(b'\\x01\\x02\\xab\\xcd\\xef'), b'0102ABCDEF') eq(base64.b16encode(b'\\x00'), b'00') # Non-bytes eq(base64.b16encode(bytearray(b'\\x01\\x02\\xab\\xcd\\xef')), b'0102ABCDEF') self.assertRaises(TypeError,", "import sys import subprocess class LegacyBase64TestCase(unittest.TestCase): def test_encodebytes(self): eq =", "res) # Non-bytes eq(base64.b32decode(bytearray(b'MFRGG===')), b'abc') def test_b32decode_casefold(self): eq = self.assertEqual", "# Test with 'URL safe' alternative characters eq(base64.urlsafe_b64encode(b'\\xd3V\\xbeo\\xf7\\x1d'), b'01a-b_cd') #", "class LegacyBase64TestCase(unittest.TestCase): def test_encodebytes(self): eq = self.assertEqual eq(base64.encodebytes(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodebytes(b\"a\"),", "b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\": b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\", b'': b'', } for data,", "self.assertRaises(binascii.Error, base64.b32decode, data) self.assertRaises(binascii.Error, base64.b32decode, data_str) def test_b32decode_error(self): for data", "def get_output(self, *args, **options): args = (sys.executable, '-m', 'base64') +", "# Non-bytes eq(base64.b32decode(bytearray(b'MFRGG===')), b'abc') def test_b32decode_casefold(self): eq = self.assertEqual tests", "test_b16encode(self): eq = self.assertEqual eq(base64.b16encode(b'\\x01\\x02\\xab\\xcd\\xef'), b'0102ABCDEF') eq(base64.b16encode(b'\\x00'), b'00') # Non-bytes", "infp = BytesIO(b'd3d3LnB5dGhvbi5vcmc=') outfp = BytesIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), b'www.python.org')", "b'Yf9iCg==') with open(support.TESTFN, 'rb') as fp: output = self.get_output('-e', stdin=fp)", "\"\") def test_encode(self): eq = self.assertEqual from io import BytesIO,", "b'', b'AA======': b'\\x00', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=':", "fold eq(base64.b16decode(b'0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(b\"0102ABCDEF\")),", "and one eq(base64.b32decode(b'MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') map_tests = {(b'M1023456', b'L'):", "b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') # Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('abc'), BytesIO()) self.assertRaises(TypeError, base64.encode,", "= ((b'%3d==', b'\\xdd'), (b'$3d==', b'\\xdd'), (b'[==', b''), (b'YW]3=', b'am'), (b'3{d==',", "test_b64decode(self): eq = self.assertEqual tests = {b\"d3d3LnB5dGhvbi5vcmc=\": b\"www.python.org\", b'AA==': b'\\x00',", "Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('abc'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'abc'), StringIO())", "self.assertRaises(binascii.Error): base64.b64decode(bstr.decode('ascii'), validate=True) def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(b''), b'')", "b\"YWI=\") eq(base64.standard_b64encode(b\"abc\"), b\"YWJj\") eq(base64.standard_b64encode(b\"\"), b\"\") eq(base64.standard_b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\"", "altchars_str = altchars.decode('ascii') eq(base64.b64decode(data, altchars=altchars), res) eq(base64.b64decode(data_str, altchars=altchars), res) eq(base64.b64decode(data,", "eq(base64.standard_b64encode(b\"\"), b\"\") eq(base64.standard_b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") #", "base64.b32decode(data.decode('ascii')) def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode(b'\\x01\\x02\\xab\\xcd\\xef'), b'0102ABCDEF') eq(base64.b16encode(b'\\x00'), b'00')", "data.decode('ascii') altchars_str = altchars.decode('ascii') eq(base64.b64decode(data, altchars=altchars), res) eq(base64.b64decode(data_str, altchars=altchars), res)", "b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') # Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('abc'), BytesIO())", "fp.write(b'a\\xffb\\n') output = self.get_output('-e', support.TESTFN) self.assertEqual(output.rstrip(), b'Yf9iCg==') with open(support.TESTFN, 'rb')", "tests_altchars.items(): data_str = data.decode('ascii') altchars_str = altchars.decode('ascii') eq(base64.b64decode(data, altchars=altchars), res)", "base64.b32decode, data_str) def test_b32decode_error(self): for data in [b'abc', b'ABCDEF==', b'==ABCDEF']:", "import base64 import binascii import os import sys import subprocess", "BytesIO(b'YWJj\\n'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), StringIO()) class BaseXYTestCase(unittest.TestCase): def test_b64encode(self):", "safe' alternative characters eq(base64.urlsafe_b64encode(b'\\xd3V\\xbeo\\xf7\\x1d'), b'01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray(b'\\xd3V\\xbeo\\xf7\\x1d')), b'01a-b_cd') #", "self.assertRaises(TypeError, base64.urlsafe_b64encode, \"\") def test_b64decode(self): eq = self.assertEqual tests =", "b'AA======': b'\\x00', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd',", "b\"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodebytes(b\"a\"), b\"YQ==\\n\") eq(base64.encodebytes(b\"ab\"), b\"YWI=\\n\") eq(base64.encodebytes(b\"abc\"), b\"YWJj\\n\") eq(base64.encodebytes(b\"\"), b\"\") eq(base64.encodebytes(b\"abcdefghijklmnopqrstuvwxyz\"", "an error self.assertRaises(TypeError, base64.standard_b64encode, \"\") # Test with 'URL safe'", "Test with arbitrary alternative characters eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=b'*$'), b'01a*b$cd') # Non-bytes", "StringIO('YWJj\\n'), StringIO()) class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual #", "zero and one eq(base64.b32decode(b'MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') map_tests = {(b'M1023456',", "res in tests.items(): eq(base64.b32decode(data), res) eq(base64.b32decode(data.decode('ascii')), res) # Non-bytes eq(base64.b32decode(bytearray(b'MFRGG===')),", "cases b'me======': b'a', b'mfra====': b'ab', b'mfrgg===': b'abc', b'mfrggza=': b'abcd', b'mfrggzdf':", "# Non-bytes eq(base64.urlsafe_b64encode(bytearray(b'\\xd3V\\xbeo\\xf7\\x1d')), b'01a-b_cd') # Check if passing a str", "data_str) def test_b32decode_error(self): for data in [b'abc', b'ABCDEF==', b'==ABCDEF']: with", "non-ascii \\xcb') def test_ErrorHeritage(self): self.assertTrue(issubclass(binascii.Error, ValueError)) class TestMain(unittest.TestCase): def tearDown(self):", "BytesIO() base64.encode(infp, outfp) eq(outfp.getvalue(), b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') # Non-binary files", "self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii')) def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode(b'\\x01\\x02\\xab\\xcd\\xef'), b'0102ABCDEF') eq(base64.b16encode(b'\\x00'),", "eq(base64.standard_b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(b\"a\"), b\"YQ==\") eq(base64.standard_b64encode(b\"ab\"), b\"YWI=\") eq(base64.standard_b64encode(b\"abc\"), b\"YWJj\") eq(base64.standard_b64encode(b\"\"), b\"\")", "b'', } for data, res in tests_urlsafe.items(): eq(base64.urlsafe_b64decode(data), res) eq(base64.urlsafe_b64decode(data.decode('ascii')),", "eq(base64.b64encode(b\"ab\"), b\"YWI=\") eq(base64.b64encode(b\"abc\"), b\"YWJj\") eq(base64.b64encode(b\"\"), b\"\") eq(base64.b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"),", "b\"\") eq(base64.encodebytes(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes", "in tests_altchars.items(): data_str = data.decode('ascii') altchars_str = altchars.decode('ascii') eq(base64.b64decode(data, altchars=altchars),", "= self.get_output('-e', stdin=fp) self.assertEqual(output.rstrip(), b'Yf9iCg==') def test_decode(self): with open(support.TESTFN, 'wb')", "# Check if passing a str object raises an error", "eq(base64.urlsafe_b64encode(bytearray(b'\\xd3V\\xbeo\\xf7\\x1d')), b'01a-b_cd') # Check if passing a str object raises", "alternative characters tests_altchars = {(b'01a*b$cd', b'*$'): b'\\xd3V\\xbeo\\xf7\\x1d', } for (data,", "(b'3{d==', b'\\xdd'), (b'3d}==', b'\\xdd'), (b'@@', b''), (b'!', b''), (b'YWJj\\nYWI=', b'abcab'))", "data, res in tests.items(): eq(base64.b64decode(data), res) eq(base64.b64decode(data.decode('ascii')), res) # Non-bytes", "base64.decodebytes, \"\") def test_encode(self): eq = self.assertEqual from io import", "\"\") def test_decodebytes(self): eq = self.assertEqual eq(base64.decodebytes(b\"d3d3LnB5dGhvbi5vcmc=\\n\"), b\"www.python.org\") eq(base64.decodebytes(b\"YQ==\\n\"), b\"a\")", "Non-bytes eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\\n') self.assertRaises(TypeError, base64.encodebytes, \"\") def test_decodebytes(self): eq =", "arbitrary alternative characters eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=b'*$'), b'01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray(b'abcd')), b'YWJjZA==')", "self.assertRaises(binascii.Error, base64.b32decode, b'me======') self.assertRaises(binascii.Error, base64.b32decode, 'me======') # Mapping zero and", "flag self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef') self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef') # Case fold", "b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\\n')", "res) eq(base64.b64decode(data_str, altchars=altchars_str), res) # Test standard alphabet for data,", "b'\\xd3V\\xbeo\\xf7\\x1d', } for (data, altchars), res in tests_altchars.items(): data_str =", "def test_encodebytes(self): eq = self.assertEqual eq(base64.encodebytes(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodebytes(b\"a\"), b\"YQ==\\n\") eq(base64.encodebytes(b\"ab\"),", "\"\") def test_b64decode(self): eq = self.assertEqual tests = {b\"d3d3LnB5dGhvbi5vcmc=\": b\"www.python.org\",", "StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), StringIO()) class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq", "raises an error self.assertRaises(TypeError, base64.urlsafe_b64encode, \"\") def test_b64decode(self): eq =", "eq = self.assertEqual tests = {b\"d3d3LnB5dGhvbi5vcmc=\": b\"www.python.org\", b'AA==': b'\\x00', b\"YQ==\":", "b'\\x00', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF':", "def test_b32decode_casefold(self): eq = self.assertEqual tests = {b'': b'', b'ME======':", "data.decode('ascii') map01_str = map01.decode('ascii') eq(base64.b32decode(data, map01=map01), res) eq(base64.b32decode(data_str, map01=map01), res)", "base64.urlsafe_b64encode, \"\") def test_b64decode(self): eq = self.assertEqual tests = {b\"d3d3LnB5dGhvbi5vcmc=\":", "res) # Test standard alphabet for data, res in tests.items():", "import support import base64 import binascii import os import sys", "alphabet eq(base64.b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode(b'\\x00'), b'AA==') eq(base64.b64encode(b\"a\"), b\"YQ==\") eq(base64.b64encode(b\"ab\"), b\"YWI=\") eq(base64.b64encode(b\"abc\"),", "fp: fp.write(b'a\\xffb\\n') output = self.get_output('-e', support.TESTFN) self.assertEqual(output.rstrip(), b'Yf9iCg==') with open(support.TESTFN,", "eq(base64.b32decode(data.decode('ascii')), res) # Non-bytes eq(base64.b32decode(bytearray(b'MFRGG===')), b'abc') def test_b32decode_casefold(self): eq =", "b'YWJjZA==') # Check if passing a str object raises an", "test_ErrorHeritage(self): self.assertTrue(issubclass(binascii.Error, ValueError)) class TestMain(unittest.TestCase): def tearDown(self): if os.path.exists(support.TESTFN): os.unlink(support.TESTFN)", "invalid characters. tests = ((b'%3d==', b'\\xdd'), (b'$3d==', b'\\xdd'), (b'[==', b''),", "import subprocess class LegacyBase64TestCase(unittest.TestCase): def test_encodebytes(self): eq = self.assertEqual eq(base64.encodebytes(b\"www.python.org\"),", "b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\", b'': b'', } for data, res in", "self.assertEqual(output.rstrip(), b'Yf9iCg==') with open(support.TESTFN, 'rb') as fp: output = self.get_output('-e',", "'URL safe' alternative characters tests_urlsafe = {b'01a-b_cd': b'\\xd3V\\xbeo\\xf7\\x1d', b'': b'',", "self.assertEqual tests = {b\"d3d3LnB5dGhvbi5vcmc=\": b\"www.python.org\", b'AA==': b'\\x00', b\"YQ==\": b\"a\", b\"YWI=\":", "= self.assertEqual eq(base64.b16encode(b'\\x01\\x02\\xab\\xcd\\xef'), b'0102ABCDEF') eq(base64.b16encode(b'\\x00'), b'00') # Non-bytes eq(base64.b16encode(bytearray(b'\\x01\\x02\\xab\\xcd\\xef')), b'0102ABCDEF')", "import BytesIO, StringIO infp = BytesIO(b'abcdefghijklmnopqrstuvwxyz' b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' b'0123456789!@#0^&*();:<>,. []{}') outfp", "for bstr, res in tests: self.assertEqual(base64.b64decode(bstr), res) self.assertEqual(base64.b64decode(bstr.decode('ascii')), res) with", "not allowed without a flag self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef') self.assertRaises(binascii.Error, base64.b16decode,", "self.assertEqual(base64.b64decode(bstr), res) self.assertEqual(base64.b64decode(bstr.decode('ascii')), res) with self.assertRaises(binascii.Error): base64.b64decode(bstr, validate=True) with self.assertRaises(binascii.Error):", "eq = self.assertEqual eq(base64.b16decode(b'0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode(b'00'), b'\\x00') eq(base64.b16decode('00'),", "base64.b32decode, b'me======') self.assertRaises(binascii.Error, base64.b32decode, 'me======') # Mapping zero and one", "b\"YWI=\": b\"ab\", b\"YWJj\": b\"abc\", b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\": b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,.", "self.assertEqual(outfp.getvalue(), b'www.python.org') # Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), BytesIO()) self.assertRaises(TypeError,", "eq(base64.b64encode(b\"abc\"), b\"YWJj\") eq(base64.b64encode(b\"\"), b\"\") eq(base64.b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\"", "data, res in tests.items(): eq(base64.standard_b64decode(data), res) eq(base64.standard_b64decode(data.decode('ascii')), res) # Non-bytes", "self.assertRaises(binascii.Error): base64.b64decode(bstr, validate=True) with self.assertRaises(binascii.Error): base64.b64decode(bstr.decode('ascii'), validate=True) def test_b32encode(self): eq", "= data.decode('ascii') map01_str = map01.decode('ascii') eq(base64.b32decode(data, map01=map01), res) eq(base64.b32decode(data_str, map01=map01),", "BytesIO, StringIO infp = BytesIO(b'abcdefghijklmnopqrstuvwxyz' b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' b'0123456789!@#0^&*();:<>,. []{}') outfp =", "b'YWJj\\n') self.assertRaises(TypeError, base64.encodebytes, \"\") def test_decodebytes(self): eq = self.assertEqual eq(base64.decodebytes(b\"d3d3LnB5dGhvbi5vcmc=\\n\"),", "# Non-bytes eq(base64.urlsafe_b64decode(bytearray(b'01a-b_cd')), b'\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_padding_error(self): self.assertRaises(binascii.Error, base64.b64decode, b'abc') self.assertRaises(binascii.Error,", "self.assertRaises(binascii.Error, base64.b64decode, 'abc') def test_b64decode_invalid_chars(self): # issue 1466065: Test some", "eq(base64.standard_b64encode(bytearray(b'abcd')), b'YWJjZA==') # Check if passing a str object raises", "b''), (b'!', b''), (b'YWJj\\nYWI=', b'abcab')) for bstr, res in tests:", "self.assertRaises(TypeError, base64.encode, StringIO('abc'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'abc'), StringIO()) self.assertRaises(TypeError, base64.encode,", "b'abc') self.assertRaises(binascii.Error, base64.b64decode, 'abc') def test_b64decode_invalid_chars(self): # issue 1466065: Test", "str object raises an error self.assertRaises(TypeError, base64.b64encode, \"\") self.assertRaises(TypeError, base64.b64encode,", "# Case fold eq(base64.b16decode(b'0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') #", "<filename>site/tests/unittests/test/test_base64.py import unittest from test import support import base64 import", "eq = self.assertEqual eq(base64.encodebytes(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodebytes(b\"a\"), b\"YQ==\\n\") eq(base64.encodebytes(b\"ab\"), b\"YWI=\\n\") eq(base64.encodebytes(b\"abc\"),", "= BytesIO() base64.encode(infp, outfp) eq(outfp.getvalue(), b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') # Non-binary", "b'abcde', # Lower cases b'me======': b'a', b'mfra====': b'ab', b'mfrgg===': b'abc',", "b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', # Lower cases b'me======': b'a', b'mfra====':", "sys import subprocess class LegacyBase64TestCase(unittest.TestCase): def test_encodebytes(self): eq = self.assertEqual", "base64.b64decode, b'abc') self.assertRaises(binascii.Error, base64.b64decode, 'abc') def test_b64decode_invalid_chars(self): # issue 1466065:", "self.assertEqual eq(base64.decodebytes(b\"d3d3LnB5dGhvbi5vcmc=\\n\"), b\"www.python.org\") eq(base64.decodebytes(b\"YQ==\\n\"), b\"a\") eq(base64.decodebytes(b\"YWI=\\n\"), b\"ab\") eq(base64.decodebytes(b\"YWJj\\n\"), b\"abc\") eq(base64.decodebytes(b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\"", "b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\": b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\", b'': b'', } for", "b\"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodebytes(b''), b'') # Non-bytes eq(base64.decodebytes(bytearray(b'YWJj\\n')), b'abc') self.assertRaises(TypeError, base64.decodebytes,", "eq(base64.b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with", "b'abc') self.assertRaises(TypeError, base64.decodebytes, \"\") def test_encode(self): eq = self.assertEqual from", "(b'@@', b''), (b'!', b''), (b'YWJj\\nYWI=', b'abcab')) for bstr, res in", "b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', }", "decode_funcs = (base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode, base64.b32decode, base64.b16decode) for f in", "b'\\xdd'), (b'3d}==', b'\\xdd'), (b'@@', b''), (b'!', b''), (b'YWJj\\nYWI=', b'abcab')) for", "passing a str object raises an error self.assertRaises(TypeError, base64.urlsafe_b64encode, \"\")", "b\"www.python.org\") eq(base64.decodebytes(b\"YQ==\\n\"), b\"a\") eq(base64.decodebytes(b\"YWI=\\n\"), b\"ab\") eq(base64.decodebytes(b\"YWJj\\n\"), b\"abc\") eq(base64.decodebytes(b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"),", "[]{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\\n') self.assertRaises(TypeError, base64.encodebytes,", "b'MFRGGZDF': b'abcde', } for data, res in tests.items(): eq(base64.b32decode(data), res)", "test_encode_decode(self): output = self.get_output('-t') self.assertSequenceEqual(output.splitlines(), ( b\"b'Aladdin:open sesame'\", br\"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\n'\", b\"b'Aladdin:open", "base64.b64encode, b\"\", altchars=\"\") # Test standard alphabet eq(base64.standard_b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(b\"a\"),", "outfp) self.assertEqual(outfp.getvalue(), b'www.python.org') # Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), BytesIO())", "for data, res in tests.items(): eq(base64.b64decode(data), res) eq(base64.b64decode(data.decode('ascii')), res) #", "b''), (b'YWJj\\nYWI=', b'abcab')) for bstr, res in tests: self.assertEqual(base64.b64decode(bstr), res)", "eq(base64.b16decode('0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(b\"0102ABCDEF\")), b'\\x01\\x02\\xab\\xcd\\xef') def test_decode_nonascii_str(self): decode_funcs", "import os import sys import subprocess class LegacyBase64TestCase(unittest.TestCase): def test_encodebytes(self):", "error self.assertRaises(TypeError, base64.b64encode, \"\") self.assertRaises(TypeError, base64.b64encode, b\"\", altchars=\"\") # Test", "b'I'): b'b\\x1d\\xad\\xf3\\xbe', } for (data, map01), res in map_tests.items(): data_str", "map01.decode('ascii') eq(base64.b32decode(data, map01=map01), res) eq(base64.b32decode(data_str, map01=map01), res) eq(base64.b32decode(data, map01=map01_str), res)", "} for (data, altchars), res in tests_altchars.items(): data_str = data.decode('ascii')", "fp: output = self.get_output('-e', stdin=fp) self.assertEqual(output.rstrip(), b'Yf9iCg==') def test_decode(self): with", "eq(base64.b16encode(b'\\x00'), b'00') # Non-bytes eq(base64.b16encode(bytearray(b'\\x01\\x02\\xab\\xcd\\xef')), b'0102ABCDEF') self.assertRaises(TypeError, base64.b16encode, \"\") def", "eq(base64.encodebytes(b\"abc\"), b\"YWJj\\n\") eq(base64.encodebytes(b\"\"), b\"\") eq(base64.encodebytes(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\"", "Check if passing a str object raises an error self.assertRaises(TypeError,", "self.assertEqual tests = {b'': b'', b'AA======': b'\\x00', b'ME======': b'a', b'MFRA====':", "b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', # Lower cases b'me======': b'a',", "b'mfrgg===': b'abc', b'mfrggza=': b'abcd', b'mfrggzdf': b'abcde', } for data, res", "eq(base64.standard_b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with 'URL safe' alternative characters tests_urlsafe", "b'me======') self.assertRaises(binascii.Error, base64.b32decode, 'me======') # Mapping zero and one eq(base64.b32decode(b'MLO23456'),", "object raises an error self.assertRaises(TypeError, base64.standard_b64encode, \"\") # Test with", "characters eq(base64.urlsafe_b64encode(b'\\xd3V\\xbeo\\xf7\\x1d'), b'01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray(b'\\xd3V\\xbeo\\xf7\\x1d')), b'01a-b_cd') # Check if", "tests: self.assertEqual(base64.b64decode(bstr), res) self.assertEqual(base64.b64decode(bstr.decode('ascii')), res) with self.assertRaises(binascii.Error): base64.b64decode(bstr, validate=True) with", "} for data, res in tests.items(): eq(base64.b64decode(data), res) eq(base64.b64decode(data.decode('ascii')), res)", "res in tests_urlsafe.items(): eq(base64.urlsafe_b64decode(data), res) eq(base64.urlsafe_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.urlsafe_b64decode(bytearray(b'01a-b_cd')),", "altchars=altchars_str), res) eq(base64.b64decode(data_str, altchars=altchars_str), res) # Test standard alphabet for", "eq(base64.standard_b64encode(b\"abc\"), b\"YWJj\") eq(base64.standard_b64encode(b\"\"), b\"\") eq(base64.standard_b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\"", "altchars=altchars_str), res) # Test standard alphabet for data, res in", "self.assertEqual eq(base64.b16decode(b'0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode(b'00'), b'\\x00') eq(base64.b16decode('00'), b'\\x00') #", "self.assertRaises(TypeError, base64.encodebytes, \"\") def test_decodebytes(self): eq = self.assertEqual eq(base64.decodebytes(b\"d3d3LnB5dGhvbi5vcmc=\\n\"), b\"www.python.org\")", "with 'URL safe' alternative characters eq(base64.urlsafe_b64encode(b'\\xd3V\\xbeo\\xf7\\x1d'), b'01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray(b'\\xd3V\\xbeo\\xf7\\x1d')),", "eq = self.assertEqual eq(base64.b16encode(b'\\x01\\x02\\xab\\xcd\\xef'), b'0102ABCDEF') eq(base64.b16encode(b'\\x00'), b'00') # Non-bytes eq(base64.b16encode(bytearray(b'\\x01\\x02\\xab\\xcd\\xef')),", "= (sys.executable, '-m', 'base64') + args return subprocess.check_output(args, **options) def", "b'Yf9iCg==') def test_decode(self): with open(support.TESTFN, 'wb') as fp: fp.write(b'Yf9iCg==') output", "self.assertRaises(ValueError, f, 'with non-ascii \\xcb') def test_ErrorHeritage(self): self.assertTrue(issubclass(binascii.Error, ValueError)) class", "characters eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=b'*$'), b'01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray(b'abcd')), b'YWJjZA==') eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray(b'*$')),", "= {b\"d3d3LnB5dGhvbi5vcmc=\": b\"www.python.org\", b'AA==': b'\\x00', b\"YQ==\": b\"a\", b\"YWI=\": b\"ab\", b\"YWJj\":", "standard alphabet for data, res in tests.items(): eq(base64.standard_b64decode(data), res) eq(base64.standard_b64decode(data.decode('ascii')),", "map01=map01), res) eq(base64.b32decode(data, map01=map01_str), res) eq(base64.b32decode(data_str, map01=map01_str), res) self.assertRaises(binascii.Error, base64.b32decode,", "test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(b''), b'') eq(base64.b32encode(b'\\x00'), b'AA======') eq(base64.b32encode(b'a'), b'ME======')", "b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', } for", "self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), StringIO()) class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq =", "base64.b32decode, data) self.assertRaises(binascii.Error, base64.b32decode, data_str) def test_b32decode_error(self): for data in", "eq(base64.b16decode('0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode(b'00'), b'\\x00') eq(base64.b16decode('00'), b'\\x00') # Lower case is", "b'b\\x1d\\xad\\xf3\\xbe', } for (data, map01), res in map_tests.items(): data_str =", "object raises an error self.assertRaises(TypeError, base64.b64encode, \"\") self.assertRaises(TypeError, base64.b64encode, b\"\",", "a flag self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef') self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef') # Case", "= self.assertEqual from io import BytesIO, StringIO infp = BytesIO(b'abcdefghijklmnopqrstuvwxyz'", "tests.items(): eq(base64.standard_b64decode(data), res) eq(base64.standard_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.standard_b64decode(bytearray(b\"YWJj\")), b\"abc\") #", "b\"\", altchars=\"\") # Test standard alphabet eq(base64.standard_b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(b\"a\"), b\"YQ==\")", "some invalid characters. tests = ((b'%3d==', b'\\xdd'), (b'$3d==', b'\\xdd'), (b'[==',", "b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\\n') self.assertRaises(TypeError, base64.encodebytes, \"\") def test_decodebytes(self):", "def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode(b'0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode(b'00'),", "eq(base64.b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with arbitrary alternative characters tests_altchars =", "eq(base64.encodebytes(b\"a\"), b\"YQ==\\n\") eq(base64.encodebytes(b\"ab\"), b\"YWI=\\n\") eq(base64.encodebytes(b\"abc\"), b\"YWJj\\n\") eq(base64.encodebytes(b\"\"), b\"\") eq(base64.encodebytes(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", "test_decodebytes(self): eq = self.assertEqual eq(base64.decodebytes(b\"d3d3LnB5dGhvbi5vcmc=\\n\"), b\"www.python.org\") eq(base64.decodebytes(b\"YQ==\\n\"), b\"a\") eq(base64.decodebytes(b\"YWI=\\n\"), b\"ab\")", "allowed without a flag self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef') self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef')", "get_output(self, *args, **options): args = (sys.executable, '-m', 'base64') + args", "tests_urlsafe.items(): eq(base64.urlsafe_b64decode(data), res) eq(base64.urlsafe_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.urlsafe_b64decode(bytearray(b'01a-b_cd')), b'\\xd3V\\xbeo\\xf7\\x1d') def", "self.assertEqual tests = {b'': b'', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===':", "test_b32decode_casefold(self): eq = self.assertEqual tests = {b'': b'', b'ME======': b'a',", "b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(b\"a\"), b\"YQ==\") eq(base64.standard_b64encode(b\"ab\"), b\"YWI=\") eq(base64.standard_b64encode(b\"abc\"), b\"YWJj\") eq(base64.standard_b64encode(b\"\"), b\"\") eq(base64.standard_b64encode(b\"abcdefghijklmnopqrstuvwxyz\"", "eq(base64.b64encode(b\"\"), b\"\") eq(base64.b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") #", "eq(base64.b32decode(data, map01=map01_str), res) eq(base64.b32decode(data_str, map01=map01_str), res) self.assertRaises(binascii.Error, base64.b32decode, data) self.assertRaises(binascii.Error,", "'0102abcdef') # Case fold eq(base64.b16decode(b'0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef')", "Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\\n'), StringIO())", "b'\\xdd'), (b'@@', b''), (b'!', b''), (b'YWJj\\nYWI=', b'abcab')) for bstr, res", "str object raises an error self.assertRaises(TypeError, base64.standard_b64encode, \"\") # Test", "StringIO infp = BytesIO(b'abcdefghijklmnopqrstuvwxyz' b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' b'0123456789!@#0^&*();:<>,. []{}') outfp = BytesIO()", "map_tests.items(): data_str = data.decode('ascii') map01_str = map01.decode('ascii') eq(base64.b32decode(data, map01=map01), res)", "data in [b'abc', b'ABCDEF==', b'==ABCDEF']: with self.assertRaises(binascii.Error): base64.b32decode(data) with self.assertRaises(binascii.Error):", "res) self.assertRaises(binascii.Error, base64.b32decode, data) self.assertRaises(binascii.Error, base64.b32decode, data_str) def test_b32decode_error(self): for", "b'': b'', } for data, res in tests.items(): eq(base64.b64decode(data), res)", "with arbitrary alternative characters eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=b'*$'), b'01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray(b'abcd')),", "} for data, res in tests.items(): eq(base64.b32decode(data, True), res) eq(base64.b32decode(data.decode('ascii'),", "BytesIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), b'www.python.org') # Non-binary files self.assertRaises(TypeError, base64.encode,", "self.assertEqual(base64.b64decode(bstr.decode('ascii')), res) with self.assertRaises(binascii.Error): base64.b64decode(bstr, validate=True) with self.assertRaises(binascii.Error): base64.b64decode(bstr.decode('ascii'), validate=True)", "eq(base64.b32encode(b'abcd'), b'MFRGGZA=') eq(base64.b32encode(b'abcde'), b'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray(b'abcd')), b'MFRGGZA=') self.assertRaises(TypeError, base64.b32encode,", "eq(base64.standard_b64encode(b\"a\"), b\"YQ==\") eq(base64.standard_b64encode(b\"ab\"), b\"YWI=\") eq(base64.standard_b64encode(b\"abc\"), b\"YWJj\") eq(base64.standard_b64encode(b\"\"), b\"\") eq(base64.standard_b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", "b\"ab\") eq(base64.decodebytes(b\"YWJj\\n\"), b\"abc\") eq(base64.decodebytes(b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\")", "os.unlink(support.TESTFN) def get_output(self, *args, **options): args = (sys.executable, '-m', 'base64')", "map01=map01_str), res) eq(base64.b32decode(data_str, map01=map01_str), res) self.assertRaises(binascii.Error, base64.b32decode, data) self.assertRaises(binascii.Error, base64.b32decode,", "self.assertRaises(TypeError, base64.encode, StringIO('abc'), StringIO()) def test_decode(self): from io import BytesIO,", "eq(base64.b16decode('00'), b'\\x00') # Lower case is not allowed without a", "res) eq(base64.b32decode(data.decode('ascii')), res) # Non-bytes eq(base64.b32decode(bytearray(b'MFRGG===')), b'abc') def test_b32decode_casefold(self): eq", "eq = self.assertEqual tests = {b'': b'', b'AA======': b'\\x00', b'ME======':", "b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode(b'\\x00'), b'AA==') eq(base64.b64encode(b\"a\"), b\"YQ==\") eq(base64.b64encode(b\"ab\"), b\"YWI=\") eq(base64.b64encode(b\"abc\"), b\"YWJj\") eq(base64.b64encode(b\"\"),", "[]{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary alternative characters", "b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', } for data, res in tests.items():", "args = (sys.executable, '-m', 'base64') + args return subprocess.check_output(args, **options)", "test_b64encode(self): eq = self.assertEqual # Test default alphabet eq(base64.b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\")", "eq(base64.b32decode(data_str, map01=map01), res) eq(base64.b32decode(data, map01=map01_str), res) eq(base64.b32decode(data_str, map01=map01_str), res) self.assertRaises(binascii.Error,", "Test standard alphabet for data, res in tests.items(): eq(base64.standard_b64decode(data), res)", "b\"abc\") # Test with 'URL safe' alternative characters tests_urlsafe =", "(b'!', b''), (b'YWJj\\nYWI=', b'abcab')) for bstr, res in tests: self.assertEqual(base64.b64decode(bstr),", "data, res in tests_urlsafe.items(): eq(base64.urlsafe_b64decode(data), res) eq(base64.urlsafe_b64decode(data.decode('ascii')), res) # Non-bytes", "self.assertRaises(binascii.Error, base64.b64decode, b'abc') self.assertRaises(binascii.Error, base64.b64decode, 'abc') def test_b64decode_invalid_chars(self): # issue", "b'abcd', b'mfrggzdf': b'abcde', } for data, res in tests.items(): eq(base64.b32decode(data,", "eq(base64.b32encode(b'abc'), b'MFRGG===') eq(base64.b32encode(b'abcd'), b'MFRGGZA=') eq(base64.b32encode(b'abcde'), b'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray(b'abcd')), b'MFRGGZA=')", "eq(base64.b16decode(b'0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(b\"0102ABCDEF\")), b'\\x01\\x02\\xab\\xcd\\xef')", "= self.assertEqual tests = {b'': b'', b'ME======': b'a', b'MFRA====': b'ab',", "eq(base64.decodebytes(b\"YWJj\\n\"), b\"abc\") eq(base64.decodebytes(b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodebytes(b''),", "b'\\x00', b\"YQ==\": b\"a\", b\"YWI=\": b\"ab\", b\"YWJj\": b\"abc\", b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\":", "= altchars.decode('ascii') eq(base64.b64decode(data, altchars=altchars), res) eq(base64.b64decode(data_str, altchars=altchars), res) eq(base64.b64decode(data, altchars=altchars_str),", "b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary alternative characters eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=b'*$'),", "unittest from test import support import base64 import binascii import", "eq(base64.urlsafe_b64encode(b'\\xd3V\\xbeo\\xf7\\x1d'), b'01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray(b'\\xd3V\\xbeo\\xf7\\x1d')), b'01a-b_cd') # Check if passing", "b'': b'', } for data, res in tests_urlsafe.items(): eq(base64.urlsafe_b64decode(data), res)", "eq(base64.b64encode(bytearray(b'abcd')), b'YWJjZA==') eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray(b'*$')), b'01a*b$cd') # Check if passing a", "b\"a\") eq(base64.decodebytes(b\"YWI=\\n\"), b\"ab\") eq(base64.decodebytes(b\"YWJj\\n\"), b\"abc\") eq(base64.decodebytes(b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", "output = self.get_output('-t') self.assertSequenceEqual(output.splitlines(), ( b\"b'Aladdin:open sesame'\", br\"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\n'\", b\"b'Aladdin:open sesame'\",", "= BytesIO(b'd3d3LnB5dGhvbi5vcmc=') outfp = BytesIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), b'www.python.org') #", "alternative characters tests_urlsafe = {b'01a-b_cd': b'\\xd3V\\xbeo\\xf7\\x1d', b'': b'', } for", "{(b'01a*b$cd', b'*$'): b'\\xd3V\\xbeo\\xf7\\x1d', } for (data, altchars), res in tests_altchars.items():", "b'AA==') eq(base64.b64encode(b\"a\"), b\"YQ==\") eq(base64.b64encode(b\"ab\"), b\"YWI=\") eq(base64.b64encode(b\"abc\"), b\"YWJj\") eq(base64.b64encode(b\"\"), b\"\") eq(base64.b64encode(b\"abcdefghijklmnopqrstuvwxyz\"", "base64.b64encode, \"\") self.assertRaises(TypeError, base64.b64encode, b\"\", altchars=\"\") # Test standard alphabet", "Non-bytes eq(base64.urlsafe_b64encode(bytearray(b'\\xd3V\\xbeo\\xf7\\x1d')), b'01a-b_cd') # Check if passing a str object", "b'abcd', b'MFRGGZDF': b'abcde', } for data, res in tests.items(): eq(base64.b32decode(data),", "(b'[==', b''), (b'YW]3=', b'am'), (b'3{d==', b'\\xdd'), (b'3d}==', b'\\xdd'), (b'@@', b''),", "tests = {b'': b'', b'AA======': b'\\x00', b'ME======': b'a', b'MFRA====': b'ab',", "test_decode_nonascii_str(self): decode_funcs = (base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode, base64.b32decode, base64.b16decode) for f", "# Non-bytes eq(base64.decodebytes(bytearray(b'YWJj\\n')), b'abc') self.assertRaises(TypeError, base64.decodebytes, \"\") def test_encode(self): eq", "issue 1466065: Test some invalid characters. tests = ((b'%3d==', b'\\xdd'),", "= self.get_output('-e', support.TESTFN) self.assertEqual(output.rstrip(), b'Yf9iCg==') with open(support.TESTFN, 'rb') as fp:", "with open(support.TESTFN, 'rb') as fp: output = self.get_output('-e', stdin=fp) self.assertEqual(output.rstrip(),", "b\"b'Aladdin:open sesame'\", br\"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\n'\", b\"b'Aladdin:open sesame'\", )) def test_encode_file(self): with open(support.TESTFN,", "# Test with 'URL safe' alternative characters tests_urlsafe = {b'01a-b_cd':", "res) self.assertRaises(binascii.Error, base64.b32decode, b'me======') self.assertRaises(binascii.Error, base64.b32decode, 'me======') # Mapping zero", "b\"abc\") # Test with arbitrary alternative characters tests_altchars = {(b'01a*b$cd',", "object raises an error self.assertRaises(TypeError, base64.urlsafe_b64encode, \"\") def test_b64decode(self): eq", "b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', # Lower cases", "ValueError)) class TestMain(unittest.TestCase): def tearDown(self): if os.path.exists(support.TESTFN): os.unlink(support.TESTFN) def get_output(self,", "open(support.TESTFN, 'wb') as fp: fp.write(b'a\\xffb\\n') output = self.get_output('-e', support.TESTFN) self.assertEqual(output.rstrip(),", "b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(b\"0102ABCDEF\")), b'\\x01\\x02\\xab\\xcd\\xef') def test_decode_nonascii_str(self):", "eq = self.assertEqual eq(base64.b32encode(b''), b'') eq(base64.b32encode(b'\\x00'), b'AA======') eq(base64.b32encode(b'a'), b'ME======') eq(base64.b32encode(b'ab'),", "self.assertRaises(binascii.Error): base64.b32decode(data) with self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii')) def test_b16encode(self): eq = self.assertEqual", "Test some invalid characters. tests = ((b'%3d==', b'\\xdd'), (b'$3d==', b'\\xdd'),", "eq(base64.standard_b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray(b'abcd')),", "self.assertRaises(binascii.Error, base64.b32decode, data_str) def test_b32decode_error(self): for data in [b'abc', b'ABCDEF==',", "eq(base64.b64decode(data, altchars=altchars_str), res) eq(base64.b64decode(data_str, altchars=altchars_str), res) # Test standard alphabet", "= self.get_output('-d', support.TESTFN) self.assertEqual(output.rstrip(), b'a\\xffb') def test_main(): support.run_unittest(__name__) if __name__", "{b'': b'', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd',", "eq(base64.encodebytes(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodebytes(bytearray(b'abc')),", "eq(base64.b64decode(data, altchars=altchars), res) eq(base64.b64decode(data_str, altchars=altchars), res) eq(base64.b64decode(data, altchars=altchars_str), res) eq(base64.b64decode(data_str,", "b'YWJjZA==') eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray(b'*$')), b'01a*b$cd') # Check if passing a str", "b\"0123456789!@#0^&*();:<>,. []{}\", b'': b'', } for data, res in tests.items():", "def tearDown(self): if os.path.exists(support.TESTFN): os.unlink(support.TESTFN) def get_output(self, *args, **options): args", "b'MFRGGZA=') eq(base64.b32encode(b'abcde'), b'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray(b'abcd')), b'MFRGGZA=') self.assertRaises(TypeError, base64.b32encode, \"\")", "eq(base64.decodebytes(b\"YQ==\\n\"), b\"a\") eq(base64.decodebytes(b\"YWI=\\n\"), b\"ab\") eq(base64.decodebytes(b\"YWJj\\n\"), b\"abc\") eq(base64.decodebytes(b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), b\"abcdefghijklmnopqrstuvwxyz\"", "eq(base64.b32encode(b'a'), b'ME======') eq(base64.b32encode(b'ab'), b'MFRA====') eq(base64.b32encode(b'abc'), b'MFRGG===') eq(base64.b32encode(b'abcd'), b'MFRGGZA=') eq(base64.b32encode(b'abcde'), b'MFRGGZDF')", "from io import BytesIO, StringIO infp = BytesIO(b'abcdefghijklmnopqrstuvwxyz' b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' b'0123456789!@#0^&*();:<>,.", "b'') # Non-bytes eq(base64.decodebytes(bytearray(b'YWJj\\n')), b'abc') self.assertRaises(TypeError, base64.decodebytes, \"\") def test_encode(self):", "def test_encode(self): eq = self.assertEqual from io import BytesIO, StringIO", "test_b64decode_padding_error(self): self.assertRaises(binascii.Error, base64.b64decode, b'abc') self.assertRaises(binascii.Error, base64.b64decode, 'abc') def test_b64decode_invalid_chars(self): #", "b'mfrggza=': b'abcd', b'mfrggzdf': b'abcde', } for data, res in tests.items():", "base64.encode, BytesIO(b'YWJj\\n'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), StringIO()) class BaseXYTestCase(unittest.TestCase): def", "return subprocess.check_output(args, **options) def test_encode_decode(self): output = self.get_output('-t') self.assertSequenceEqual(output.splitlines(), (", "res) eq(base64.b64decode(data_str, altchars=altchars), res) eq(base64.b64decode(data, altchars=altchars_str), res) eq(base64.b64decode(data_str, altchars=altchars_str), res)", "res in tests.items(): eq(base64.standard_b64decode(data), res) eq(base64.standard_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.standard_b64decode(bytearray(b\"YWJj\")),", "b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') # Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('abc'), BytesIO()) self.assertRaises(TypeError,", "b'01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray(b'\\xd3V\\xbeo\\xf7\\x1d')), b'01a-b_cd') # Check if passing a", "b'*$'): b'\\xd3V\\xbeo\\xf7\\x1d', } for (data, altchars), res in tests_altchars.items(): data_str", "res in tests: self.assertEqual(base64.b64decode(bstr), res) self.assertEqual(base64.b64decode(bstr.decode('ascii')), res) with self.assertRaises(binascii.Error): base64.b64decode(bstr,", "( b\"b'Aladdin:open sesame'\", br\"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\n'\", b\"b'Aladdin:open sesame'\", )) def test_encode_file(self): with", "an error self.assertRaises(TypeError, base64.b64encode, \"\") self.assertRaises(TypeError, base64.b64encode, b\"\", altchars=\"\") #", "standard alphabet eq(base64.standard_b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(b\"a\"), b\"YQ==\") eq(base64.standard_b64encode(b\"ab\"), b\"YWI=\") eq(base64.standard_b64encode(b\"abc\"), b\"YWJj\")", "b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\\n') self.assertRaises(TypeError, base64.encodebytes, \"\")", "Non-bytes eq(base64.standard_b64encode(bytearray(b'abcd')), b'YWJjZA==') # Check if passing a str object", "base64.encode, BytesIO(b'abc'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('abc'), StringIO()) def test_decode(self): from", "} for data, res in tests_urlsafe.items(): eq(base64.urlsafe_b64decode(data), res) eq(base64.urlsafe_b64decode(data.decode('ascii')), res)", "b'ab', b'mfrgg===': b'abc', b'mfrggza=': b'abcd', b'mfrggzdf': b'abcde', } for data,", "b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' b'0123456789!@#0^&*();:<>,. []{}') outfp = BytesIO() base64.encode(infp, outfp) eq(outfp.getvalue(), b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE'", "True), res) self.assertRaises(binascii.Error, base64.b32decode, b'me======') self.assertRaises(binascii.Error, base64.b32decode, 'me======') # Mapping", "altchars=\"\") # Test standard alphabet eq(base64.standard_b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(b\"a\"), b\"YQ==\") eq(base64.standard_b64encode(b\"ab\"),", "validate=True) def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(b''), b'') eq(base64.b32encode(b'\\x00'), b'AA======')", "= BytesIO(b'abcdefghijklmnopqrstuvwxyz' b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' b'0123456789!@#0^&*();:<>,. []{}') outfp = BytesIO() base64.encode(infp, outfp)", "b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray(b'abcd')), b'YWJjZA==')", "eq(base64.standard_b64decode(data), res) eq(base64.standard_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.standard_b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test", "b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary alternative characters eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=b'*$'), b'01a*b$cd')", "data, res in tests.items(): eq(base64.b32decode(data), res) eq(base64.b32decode(data.decode('ascii')), res) # Non-bytes", "b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode(b'00'), b'\\x00') eq(base64.b16decode('00'), b'\\x00') # Lower case", "io import BytesIO, StringIO infp = BytesIO(b'abcdefghijklmnopqrstuvwxyz' b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' b'0123456789!@#0^&*();:<>,. []{}')", "characters tests_urlsafe = {b'01a-b_cd': b'\\xd3V\\xbeo\\xf7\\x1d', b'': b'', } for data,", "base64.standard_b64decode, base64.urlsafe_b64decode, base64.b32decode, base64.b16decode) for f in decode_funcs: self.assertRaises(ValueError, f,", "def test_b64decode_padding_error(self): self.assertRaises(binascii.Error, base64.b64decode, b'abc') self.assertRaises(binascii.Error, base64.b64decode, 'abc') def test_b64decode_invalid_chars(self):", "# Test standard alphabet for data, res in tests.items(): eq(base64.standard_b64decode(data),", "b'MFRGG===') eq(base64.b32encode(b'abcd'), b'MFRGGZA=') eq(base64.b32encode(b'abcde'), b'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray(b'abcd')), b'MFRGGZA=') self.assertRaises(TypeError,", "characters tests_altchars = {(b'01a*b$cd', b'*$'): b'\\xd3V\\xbeo\\xf7\\x1d', } for (data, altchars),", "b'ME======') eq(base64.b32encode(b'ab'), b'MFRA====') eq(base64.b32encode(b'abc'), b'MFRGG===') eq(base64.b32encode(b'abcd'), b'MFRGGZA=') eq(base64.b32encode(b'abcde'), b'MFRGGZDF') #", "b\"www.python.org\", b'AA==': b'\\x00', b\"YQ==\": b\"a\", b\"YWI=\": b\"ab\", b\"YWJj\": b\"abc\", b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\"", "eq(base64.b16encode(bytearray(b'\\x01\\x02\\xab\\xcd\\xef')), b'0102ABCDEF') self.assertRaises(TypeError, base64.b16encode, \"\") def test_b16decode(self): eq = self.assertEqual", "tests_altchars = {(b'01a*b$cd', b'*$'): b'\\xd3V\\xbeo\\xf7\\x1d', } for (data, altchars), res", "as fp: output = self.get_output('-e', stdin=fp) self.assertEqual(output.rstrip(), b'Yf9iCg==') def test_decode(self):", "b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', # Lower cases b'me======':", "alphabet eq(base64.standard_b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(b\"a\"), b\"YQ==\") eq(base64.standard_b64encode(b\"ab\"), b\"YWI=\") eq(base64.standard_b64encode(b\"abc\"), b\"YWJj\") eq(base64.standard_b64encode(b\"\"),", "res) eq(base64.urlsafe_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.urlsafe_b64decode(bytearray(b'01a-b_cd')), b'\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_padding_error(self): self.assertRaises(binascii.Error,", "StringIO('abc'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'abc'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('abc'), StringIO())", "eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\\n') self.assertRaises(TypeError, base64.encodebytes, \"\") def test_decodebytes(self): eq = self.assertEqual", "'-m', 'base64') + args return subprocess.check_output(args, **options) def test_encode_decode(self): output", "f in decode_funcs: self.assertRaises(ValueError, f, 'with non-ascii \\xcb') def test_ErrorHeritage(self):", "eq = self.assertEqual tests = {b'': b'', b'ME======': b'a', b'MFRA====':", "test_encode(self): eq = self.assertEqual from io import BytesIO, StringIO infp", "self.assertRaises(TypeError, base64.b64encode, b\"\", altchars=\"\") # Test standard alphabet eq(base64.standard_b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\")", "eq(base64.b32decode(bytearray(b'MFRGG===')), b'abc') def test_b32decode_casefold(self): eq = self.assertEqual tests = {b'':", "class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual # Test default", "br\"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\n'\", b\"b'Aladdin:open sesame'\", )) def test_encode_file(self): with open(support.TESTFN, 'wb') as", "b'ABCDEF==', b'==ABCDEF']: with self.assertRaises(binascii.Error): base64.b32decode(data) with self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii')) def test_b16encode(self):", "b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") # Non-bytes eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\\n') self.assertRaises(TypeError,", "b\"YWJj\": b\"abc\", b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\": b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\", b'':", "# Non-bytes eq(base64.b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with arbitrary alternative characters", "for data, res in tests.items(): eq(base64.b32decode(data, True), res) eq(base64.b32decode(data.decode('ascii'), True),", "b\"abc\", b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\": b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\", b'': b'',", "with self.assertRaises(binascii.Error): base64.b32decode(data) with self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii')) def test_b16encode(self): eq =", "= BytesIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), b'www.python.org') # Non-binary files self.assertRaises(TypeError,", "characters. tests = ((b'%3d==', b'\\xdd'), (b'$3d==', b'\\xdd'), (b'[==', b''), (b'YW]3=',", "base64.b64decode(bstr.decode('ascii'), validate=True) def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(b''), b'') eq(base64.b32encode(b'\\x00'),", "a str object raises an error self.assertRaises(TypeError, base64.urlsafe_b64encode, \"\") def", "altchars=b'*$'), b'01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray(b'abcd')), b'YWJjZA==') eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray(b'*$')), b'01a*b$cd') #", "self.assertRaises(TypeError, base64.standard_b64encode, \"\") # Test with 'URL safe' alternative characters", "self.assertRaises(TypeError, base64.b16encode, \"\") def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode(b'0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef')", "res in tests.items(): eq(base64.b32decode(data, True), res) eq(base64.b32decode(data.decode('ascii'), True), res) self.assertRaises(binascii.Error,", "b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodebytes(b''), b'') # Non-bytes eq(base64.decodebytes(bytearray(b'YWJj\\n')), b'abc')", "with open(support.TESTFN, 'wb') as fp: fp.write(b'Yf9iCg==') output = self.get_output('-d', support.TESTFN)", "b\"YQ==\\n\") eq(base64.encodebytes(b\"ab\"), b\"YWI=\\n\") eq(base64.encodebytes(b\"abc\"), b\"YWJj\\n\") eq(base64.encodebytes(b\"\"), b\"\") eq(base64.encodebytes(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,.", "raises an error self.assertRaises(TypeError, base64.standard_b64encode, \"\") # Test with 'URL", "# Test with arbitrary alternative characters eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=b'*$'), b'01a*b$cd') #", "'wb') as fp: fp.write(b'a\\xffb\\n') output = self.get_output('-e', support.TESTFN) self.assertEqual(output.rstrip(), b'Yf9iCg==')", "eq(base64.b32encode(b'\\x00'), b'AA======') eq(base64.b32encode(b'a'), b'ME======') eq(base64.b32encode(b'ab'), b'MFRA====') eq(base64.b32encode(b'abc'), b'MFRGG===') eq(base64.b32encode(b'abcd'), b'MFRGGZA=')", "self.assertSequenceEqual(output.splitlines(), ( b\"b'Aladdin:open sesame'\", br\"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\n'\", b\"b'Aladdin:open sesame'\", )) def test_encode_file(self):", "b\"YQ==\": b\"a\", b\"YWI=\": b\"ab\", b\"YWJj\": b\"abc\", b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\": b\"abcdefghijklmnopqrstuvwxyz\"", "'URL safe' alternative characters eq(base64.urlsafe_b64encode(b'\\xd3V\\xbeo\\xf7\\x1d'), b'01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray(b'\\xd3V\\xbeo\\xf7\\x1d')), b'01a-b_cd')", "base64.b32decode(data) with self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii')) def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode(b'\\x01\\x02\\xab\\xcd\\xef'),", "b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\", b'': b'', } for data, res", "eq(base64.b32decode(data, map01=map01), res) eq(base64.b32decode(data_str, map01=map01), res) eq(base64.b32decode(data, map01=map01_str), res) eq(base64.b32decode(data_str,", "[]{}\") eq(base64.decodebytes(b''), b'') # Non-bytes eq(base64.decodebytes(bytearray(b'YWJj\\n')), b'abc') self.assertRaises(TypeError, base64.decodebytes, \"\")", "Test default alphabet eq(base64.b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode(b'\\x00'), b'AA==') eq(base64.b64encode(b\"a\"), b\"YQ==\") eq(base64.b64encode(b\"ab\"),", "in map_tests.items(): data_str = data.decode('ascii') map01_str = map01.decode('ascii') eq(base64.b32decode(data, map01=map01),", "# Lower cases b'me======': b'a', b'mfra====': b'ab', b'mfrgg===': b'abc', b'mfrggza=':", "eq(base64.urlsafe_b64decode(data), res) eq(base64.urlsafe_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.urlsafe_b64decode(bytearray(b'01a-b_cd')), b'\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_padding_error(self):", "# Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('abc'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'abc'),", "'me======') # Mapping zero and one eq(base64.b32decode(b'MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('MLO23456'), b'b\\xdd\\xad\\xf3\\xbe')", "eq(base64.b32encode(bytearray(b'abcd')), b'MFRGGZA=') self.assertRaises(TypeError, base64.b32encode, \"\") def test_b32decode(self): eq = self.assertEqual", "b\"b'Aladdin:open sesame'\", )) def test_encode_file(self): with open(support.TESTFN, 'wb') as fp:", "case is not allowed without a flag self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef')", "an error self.assertRaises(TypeError, base64.urlsafe_b64encode, \"\") def test_b64decode(self): eq = self.assertEqual", "= self.assertEqual eq(base64.b16decode(b'0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode(b'00'), b'\\x00') eq(base64.b16decode('00'), b'\\x00')", "eq(base64.b32decode(data, True), res) eq(base64.b32decode(data.decode('ascii'), True), res) self.assertRaises(binascii.Error, base64.b32decode, b'me======') self.assertRaises(binascii.Error,", "def test_b64decode(self): eq = self.assertEqual tests = {b\"d3d3LnB5dGhvbi5vcmc=\": b\"www.python.org\", b'AA==':", "\"\") def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode(b'0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef')", "test import support import base64 import binascii import os import", "altchars), res in tests_altchars.items(): data_str = data.decode('ascii') altchars_str = altchars.decode('ascii')", "one eq(base64.b32decode(b'MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') map_tests = {(b'M1023456', b'L'): b'b\\xdd\\xad\\xf3\\xbe',", "from test import support import base64 import binascii import os", "test_decode(self): from io import BytesIO, StringIO infp = BytesIO(b'd3d3LnB5dGhvbi5vcmc=') outfp", "eq(base64.b64decode(data_str, altchars=altchars_str), res) # Test standard alphabet for data, res", "without a flag self.assertRaises(binascii.Error, base64.b16decode, b'0102abcdef') self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef') #", "output = self.get_output('-e', stdin=fp) self.assertEqual(output.rstrip(), b'Yf9iCg==') def test_decode(self): with open(support.TESTFN,", "b'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') map_tests = {(b'M1023456', b'L'): b'b\\xdd\\xad\\xf3\\xbe', (b'M1023456', b'I'):", "b\"\") eq(base64.standard_b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes", "# Non-bytes eq(base64.standard_b64encode(bytearray(b'abcd')), b'YWJjZA==') # Check if passing a str", "self.get_output('-t') self.assertSequenceEqual(output.splitlines(), ( b\"b'Aladdin:open sesame'\", br\"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\n'\", b\"b'Aladdin:open sesame'\", )) def", "self.assertTrue(issubclass(binascii.Error, ValueError)) class TestMain(unittest.TestCase): def tearDown(self): if os.path.exists(support.TESTFN): os.unlink(support.TESTFN) def", "self.assertEqual eq(base64.encodebytes(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodebytes(b\"a\"), b\"YQ==\\n\") eq(base64.encodebytes(b\"ab\"), b\"YWI=\\n\") eq(base64.encodebytes(b\"abc\"), b\"YWJj\\n\") eq(base64.encodebytes(b\"\"),", "True), b'\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(b\"0102ABCDEF\")), b'\\x01\\x02\\xab\\xcd\\xef') def test_decode_nonascii_str(self): decode_funcs =", "support.TESTFN) self.assertEqual(output.rstrip(), b'a\\xffb') def test_main(): support.run_unittest(__name__) if __name__ == '__main__':", "res) # Non-bytes eq(base64.standard_b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with 'URL safe'", "BytesIO, StringIO infp = BytesIO(b'd3d3LnB5dGhvbi5vcmc=') outfp = BytesIO() base64.decode(infp, outfp)", "altchars=altchars), res) eq(base64.b64decode(data_str, altchars=altchars), res) eq(base64.b64decode(data, altchars=altchars_str), res) eq(base64.b64decode(data_str, altchars=altchars_str),", "StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('abc'), StringIO()) def test_decode(self): from io import", "eq(base64.decodebytes(b\"d3d3LnB5dGhvbi5vcmc=\\n\"), b\"www.python.org\") eq(base64.decodebytes(b\"YQ==\\n\"), b\"a\") eq(base64.decodebytes(b\"YWI=\\n\"), b\"ab\") eq(base64.decodebytes(b\"YWJj\\n\"), b\"abc\") eq(base64.decodebytes(b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\"", "files self.assertRaises(TypeError, base64.encode, StringIO('abc'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'abc'), StringIO()) self.assertRaises(TypeError,", "self.assertEqual(output.rstrip(), b'Yf9iCg==') def test_decode(self): with open(support.TESTFN, 'wb') as fp: fp.write(b'Yf9iCg==')", "b'01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray(b'abcd')), b'YWJjZA==') eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray(b'*$')), b'01a*b$cd') # Check", "test_b16decode(self): eq = self.assertEqual eq(base64.b16decode(b'0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode(b'00'), b'\\x00')", "b'\\x00') # Lower case is not allowed without a flag", "tests = ((b'%3d==', b'\\xdd'), (b'$3d==', b'\\xdd'), (b'[==', b''), (b'YW]3=', b'am'),", "base64.standard_b64encode, \"\") # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64encode(b'\\xd3V\\xbeo\\xf7\\x1d'),", "eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=b'*$'), b'01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray(b'abcd')), b'YWJjZA==') eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray(b'*$')), b'01a*b$cd')", "b'\\xdd'), (b'$3d==', b'\\xdd'), (b'[==', b''), (b'YW]3=', b'am'), (b'3{d==', b'\\xdd'), (b'3d}==',", "# Mapping zero and one eq(base64.b32decode(b'MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') map_tests", "base64 import binascii import os import sys import subprocess class", "base64.b16encode, \"\") def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode(b'0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102ABCDEF'),", "res) with self.assertRaises(binascii.Error): base64.b64decode(bstr, validate=True) with self.assertRaises(binascii.Error): base64.b64decode(bstr.decode('ascii'), validate=True) def", "b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary alternative characters eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d',", "b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', } for data, res", "if passing a str object raises an error self.assertRaises(TypeError, base64.urlsafe_b64encode,", "# Test with arbitrary alternative characters tests_altchars = {(b'01a*b$cd', b'*$'):", "b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray(b'abcd')), b'YWJjZA==') # Check if passing a", "StringIO()) class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual # Test", "b'abcde', } for data, res in tests.items(): eq(base64.b32decode(data, True), res)", "b'==ABCDEF']: with self.assertRaises(binascii.Error): base64.b32decode(data) with self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii')) def test_b16encode(self): eq", "# Non-bytes eq(base64.b32encode(bytearray(b'abcd')), b'MFRGGZA=') self.assertRaises(TypeError, base64.b32encode, \"\") def test_b32decode(self): eq", "b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', } for data,", "for (data, altchars), res in tests_altchars.items(): data_str = data.decode('ascii') altchars_str", "LegacyBase64TestCase(unittest.TestCase): def test_encodebytes(self): eq = self.assertEqual eq(base64.encodebytes(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodebytes(b\"a\"), b\"YQ==\\n\")", "res in tests_altchars.items(): data_str = data.decode('ascii') altchars_str = altchars.decode('ascii') eq(base64.b64decode(data,", "with 'URL safe' alternative characters tests_urlsafe = {b'01a-b_cd': b'\\xd3V\\xbeo\\xf7\\x1d', b'':", "eq(base64.b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with arbitrary", "res) # Non-bytes eq(base64.urlsafe_b64decode(bytearray(b'01a-b_cd')), b'\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_padding_error(self): self.assertRaises(binascii.Error, base64.b64decode, b'abc')", "eq(base64.urlsafe_b64decode(bytearray(b'01a-b_cd')), b'\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_padding_error(self): self.assertRaises(binascii.Error, base64.b64decode, b'abc') self.assertRaises(binascii.Error, base64.b64decode, 'abc')", "{b'': b'', b'AA======': b'\\x00', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc',", "eq(base64.b32decode(data), res) eq(base64.b32decode(data.decode('ascii')), res) # Non-bytes eq(base64.b32decode(bytearray(b'MFRGG===')), b'abc') def test_b32decode_casefold(self):", "b'0102ABCDEF') eq(base64.b16encode(b'\\x00'), b'00') # Non-bytes eq(base64.b16encode(bytearray(b'\\x01\\x02\\xab\\xcd\\xef')), b'0102ABCDEF') self.assertRaises(TypeError, base64.b16encode, \"\")", "b'', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF':", "Lower case is not allowed without a flag self.assertRaises(binascii.Error, base64.b16decode,", "def test_decode_nonascii_str(self): decode_funcs = (base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode, base64.b32decode, base64.b16decode) for", "a str object raises an error self.assertRaises(TypeError, base64.b64encode, \"\") self.assertRaises(TypeError,", "tests.items(): eq(base64.b32decode(data, True), res) eq(base64.b32decode(data.decode('ascii'), True), res) self.assertRaises(binascii.Error, base64.b32decode, b'me======')", "res in tests.items(): eq(base64.b64decode(data), res) eq(base64.b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.b64decode(bytearray(b\"YWJj\")),", "sesame'\", br\"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\n'\", b\"b'Aladdin:open sesame'\", )) def test_encode_file(self): with open(support.TESTFN, 'wb')", "test_b32decode(self): eq = self.assertEqual tests = {b'': b'', b'AA======': b'\\x00',", "+ args return subprocess.check_output(args, **options) def test_encode_decode(self): output = self.get_output('-t')", "BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'abc'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('abc'), StringIO()) def", "Non-bytes eq(base64.urlsafe_b64decode(bytearray(b'01a-b_cd')), b'\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_padding_error(self): self.assertRaises(binascii.Error, base64.b64decode, b'abc') self.assertRaises(binascii.Error, base64.b64decode,", "passing a str object raises an error self.assertRaises(TypeError, base64.standard_b64encode, \"\")", "BytesIO(b'abcdefghijklmnopqrstuvwxyz' b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' b'0123456789!@#0^&*();:<>,. []{}') outfp = BytesIO() base64.encode(infp, outfp) eq(outfp.getvalue(),", "as fp: fp.write(b'Yf9iCg==') output = self.get_output('-d', support.TESTFN) self.assertEqual(output.rstrip(), b'a\\xffb') def", "str object raises an error self.assertRaises(TypeError, base64.urlsafe_b64encode, \"\") def test_b64decode(self):", "b'b\\xdd\\xad\\xf3\\xbe') map_tests = {(b'M1023456', b'L'): b'b\\xdd\\xad\\xf3\\xbe', (b'M1023456', b'I'): b'b\\x1d\\xad\\xf3\\xbe', }", "\"\") self.assertRaises(TypeError, base64.b64encode, b\"\", altchars=\"\") # Test standard alphabet eq(base64.standard_b64encode(b\"www.python.org\"),", "b'a', b'mfra====': b'ab', b'mfrgg===': b'abc', b'mfrggza=': b'abcd', b'mfrggzdf': b'abcde', }", "Non-bytes eq(base64.b32encode(bytearray(b'abcd')), b'MFRGGZA=') self.assertRaises(TypeError, base64.b32encode, \"\") def test_b32decode(self): eq =", "= self.assertEqual tests = {b\"d3d3LnB5dGhvbi5vcmc=\": b\"www.python.org\", b'AA==': b'\\x00', b\"YQ==\": b\"a\",", "error self.assertRaises(TypeError, base64.standard_b64encode, \"\") # Test with 'URL safe' alternative", "res) eq(base64.b32decode(data.decode('ascii'), True), res) self.assertRaises(binascii.Error, base64.b32decode, b'me======') self.assertRaises(binascii.Error, base64.b32decode, 'me======')", "in [b'abc', b'ABCDEF==', b'==ABCDEF']: with self.assertRaises(binascii.Error): base64.b32decode(data) with self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii'))", "\"\") # Test with 'URL safe' alternative characters eq(base64.urlsafe_b64encode(b'\\xd3V\\xbeo\\xf7\\x1d'), b'01a-b_cd')", "eq(base64.b16decode(bytearray(b\"0102ABCDEF\")), b'\\x01\\x02\\xab\\xcd\\xef') def test_decode_nonascii_str(self): decode_funcs = (base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode, base64.b32decode,", "{(b'M1023456', b'L'): b'b\\xdd\\xad\\xf3\\xbe', (b'M1023456', b'I'): b'b\\x1d\\xad\\xf3\\xbe', } for (data, map01),", "subprocess class LegacyBase64TestCase(unittest.TestCase): def test_encodebytes(self): eq = self.assertEqual eq(base64.encodebytes(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\\n\")", "b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test with arbitrary alternative", "subprocess.check_output(args, **options) def test_encode_decode(self): output = self.get_output('-t') self.assertSequenceEqual(output.splitlines(), ( b\"b'Aladdin:open", "Non-bytes eq(base64.b16encode(bytearray(b'\\x01\\x02\\xab\\xcd\\xef')), b'0102ABCDEF') self.assertRaises(TypeError, base64.b16encode, \"\") def test_b16decode(self): eq =", "= self.assertEqual eq(base64.decodebytes(b\"d3d3LnB5dGhvbi5vcmc=\\n\"), b\"www.python.org\") eq(base64.decodebytes(b\"YQ==\\n\"), b\"a\") eq(base64.decodebytes(b\"YWI=\\n\"), b\"ab\") eq(base64.decodebytes(b\"YWJj\\n\"), b\"abc\")", "(data, altchars), res in tests_altchars.items(): data_str = data.decode('ascii') altchars_str =", "eq = self.assertEqual from io import BytesIO, StringIO infp =", "eq(base64.encodebytes(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodebytes(b\"a\"), b\"YQ==\\n\") eq(base64.encodebytes(b\"ab\"), b\"YWI=\\n\") eq(base64.encodebytes(b\"abc\"), b\"YWJj\\n\") eq(base64.encodebytes(b\"\"), b\"\")", "a str object raises an error self.assertRaises(TypeError, base64.standard_b64encode, \"\") #", "error self.assertRaises(TypeError, base64.urlsafe_b64encode, \"\") def test_b64decode(self): eq = self.assertEqual tests", "Mapping zero and one eq(base64.b32decode(b'MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') map_tests =", "def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode(b'\\x01\\x02\\xab\\xcd\\xef'), b'0102ABCDEF') eq(base64.b16encode(b'\\x00'), b'00') #", "StringIO()) def test_decode(self): from io import BytesIO, StringIO infp =", "def test_encode_file(self): with open(support.TESTFN, 'wb') as fp: fp.write(b'a\\xffb\\n') output =", "b'01a-b_cd') # Check if passing a str object raises an", "default alphabet eq(base64.b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode(b'\\x00'), b'AA==') eq(base64.b64encode(b\"a\"), b\"YQ==\") eq(base64.b64encode(b\"ab\"), b\"YWI=\")", "map01_str = map01.decode('ascii') eq(base64.b32decode(data, map01=map01), res) eq(base64.b32decode(data_str, map01=map01), res) eq(base64.b32decode(data,", "(b'YW]3=', b'am'), (b'3{d==', b'\\xdd'), (b'3d}==', b'\\xdd'), (b'@@', b''), (b'!', b''),", "eq(base64.b64decode(data_str, altchars=altchars), res) eq(base64.b64decode(data, altchars=altchars_str), res) eq(base64.b64decode(data_str, altchars=altchars_str), res) #", "as fp: fp.write(b'a\\xffb\\n') output = self.get_output('-e', support.TESTFN) self.assertEqual(output.rstrip(), b'Yf9iCg==') with", "b'www.python.org') # Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), BytesIO()) self.assertRaises(TypeError, base64.encode,", "map01), res in map_tests.items(): data_str = data.decode('ascii') map01_str = map01.decode('ascii')", "base64.b32decode, base64.b16decode) for f in decode_funcs: self.assertRaises(ValueError, f, 'with non-ascii", "alternative characters eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=b'*$'), b'01a*b$cd') # Non-bytes eq(base64.b64encode(bytearray(b'abcd')), b'YWJjZA==') eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d',", "Non-bytes eq(base64.b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with arbitrary alternative characters tests_altchars", "} for data, res in tests.items(): eq(base64.b32decode(data), res) eq(base64.b32decode(data.decode('ascii')), res)", "Lower cases b'me======': b'a', b'mfra====': b'ab', b'mfrgg===': b'abc', b'mfrggza=': b'abcd',", "[]{}\", b'': b'', } for data, res in tests.items(): eq(base64.b64decode(data),", "res) eq(base64.b64decode(data, altchars=altchars_str), res) eq(base64.b64decode(data_str, altchars=altchars_str), res) # Test standard", "eq(base64.decodebytes(bytearray(b'YWJj\\n')), b'abc') self.assertRaises(TypeError, base64.decodebytes, \"\") def test_encode(self): eq = self.assertEqual", "(b'3d}==', b'\\xdd'), (b'@@', b''), (b'!', b''), (b'YWJj\\nYWI=', b'abcab')) for bstr,", "= (base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode, base64.b32decode, base64.b16decode) for f in decode_funcs:", "'base64') + args return subprocess.check_output(args, **options) def test_encode_decode(self): output =", "b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde',", "def test_decode(self): from io import BytesIO, StringIO infp = BytesIO(b'd3d3LnB5dGhvbi5vcmc=')", "tearDown(self): if os.path.exists(support.TESTFN): os.unlink(support.TESTFN) def get_output(self, *args, **options): args =", "for data, res in tests.items(): eq(base64.standard_b64decode(data), res) eq(base64.standard_b64decode(data.decode('ascii')), res) #", "base64.b16decode, b'0102abcdef') self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode(b'0102abcdef', True),", "'abc') def test_b64decode_invalid_chars(self): # issue 1466065: Test some invalid characters.", "arbitrary alternative characters tests_altchars = {(b'01a*b$cd', b'*$'): b'\\xd3V\\xbeo\\xf7\\x1d', } for", "base64.urlsafe_b64decode, base64.b32decode, base64.b16decode) for f in decode_funcs: self.assertRaises(ValueError, f, 'with", "base64.b16decode) for f in decode_funcs: self.assertRaises(ValueError, f, 'with non-ascii \\xcb')", "self.assertEqual(output.rstrip(), b'a\\xffb') def test_main(): support.run_unittest(__name__) if __name__ == '__main__': test_main()", "def test_b32decode(self): eq = self.assertEqual tests = {b'': b'', b'AA======':", "BytesIO(b'd3d3LnB5dGhvbi5vcmc=') outfp = BytesIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), b'www.python.org') # Non-binary", "if passing a str object raises an error self.assertRaises(TypeError, base64.standard_b64encode,", "outfp = BytesIO() base64.encode(infp, outfp) eq(outfp.getvalue(), b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') #", "b'0102abcdef') self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode(b'0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef')", "map01=map01), res) eq(base64.b32decode(data_str, map01=map01), res) eq(base64.b32decode(data, map01=map01_str), res) eq(base64.b32decode(data_str, map01=map01_str),", "(data, map01), res in map_tests.items(): data_str = data.decode('ascii') map01_str =", "output = self.get_output('-d', support.TESTFN) self.assertEqual(output.rstrip(), b'a\\xffb') def test_main(): support.run_unittest(__name__) if", "output = self.get_output('-e', support.TESTFN) self.assertEqual(output.rstrip(), b'Yf9iCg==') with open(support.TESTFN, 'rb') as", "b'me======': b'a', b'mfra====': b'ab', b'mfrgg===': b'abc', b'mfrggza=': b'abcd', b'mfrggzdf': b'abcde',", "b'01a*b$cd') # Check if passing a str object raises an", "in tests.items(): eq(base64.b32decode(data, True), res) eq(base64.b32decode(data.decode('ascii'), True), res) self.assertRaises(binascii.Error, base64.b32decode,", "base64.b32decode, 'me======') # Mapping zero and one eq(base64.b32decode(b'MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') eq(base64.b32decode('MLO23456'),", "in tests.items(): eq(base64.b64decode(data), res) eq(base64.b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.b64decode(bytearray(b\"YWJj\")), b\"abc\")", "os.path.exists(support.TESTFN): os.unlink(support.TESTFN) def get_output(self, *args, **options): args = (sys.executable, '-m',", "test_encodebytes(self): eq = self.assertEqual eq(base64.encodebytes(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodebytes(b\"a\"), b\"YQ==\\n\") eq(base64.encodebytes(b\"ab\"), b\"YWI=\\n\")", "eq(base64.b32decode('MLO23456'), b'b\\xdd\\xad\\xf3\\xbe') map_tests = {(b'M1023456', b'L'): b'b\\xdd\\xad\\xf3\\xbe', (b'M1023456', b'I'): b'b\\x1d\\xad\\xf3\\xbe',", "validate=True) with self.assertRaises(binascii.Error): base64.b64decode(bstr.decode('ascii'), validate=True) def test_b32encode(self): eq = self.assertEqual", "b\"YQ==\") eq(base64.standard_b64encode(b\"ab\"), b\"YWI=\") eq(base64.standard_b64encode(b\"abc\"), b\"YWJj\") eq(base64.standard_b64encode(b\"\"), b\"\") eq(base64.standard_b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,.", "self.assertEqual # Test default alphabet eq(base64.b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode(b'\\x00'), b'AA==') eq(base64.b64encode(b\"a\"),", "self.assertRaises(TypeError, base64.b64encode, \"\") self.assertRaises(TypeError, base64.b64encode, b\"\", altchars=\"\") # Test standard", "tests.items(): eq(base64.b64decode(data), res) eq(base64.b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.b64decode(bytearray(b\"YWJj\")), b\"abc\") #", "\"\") def test_b32decode(self): eq = self.assertEqual tests = {b'': b'',", "def test_b32decode_error(self): for data in [b'abc', b'ABCDEF==', b'==ABCDEF']: with self.assertRaises(binascii.Error):", "base64.encode, StringIO('YWJj\\n'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\\n'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'),", "StringIO('abc'), StringIO()) def test_decode(self): from io import BytesIO, StringIO infp", "b'abcd', b'MFRGGZDF': b'abcde', # Lower cases b'me======': b'a', b'mfra====': b'ab',", "os import sys import subprocess class LegacyBase64TestCase(unittest.TestCase): def test_encodebytes(self): eq", "outfp) eq(outfp.getvalue(), b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') # Non-binary files self.assertRaises(TypeError, base64.encode,", "BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\\n'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), StringIO()) class", "= self.assertEqual eq(base64.b32encode(b''), b'') eq(base64.b32encode(b'\\x00'), b'AA======') eq(base64.b32encode(b'a'), b'ME======') eq(base64.b32encode(b'ab'), b'MFRA====')", "= {b'': b'', b'AA======': b'\\x00', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===':", "b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodebytes(b''), b'') # Non-bytes", "altchars.decode('ascii') eq(base64.b64decode(data, altchars=altchars), res) eq(base64.b64decode(data_str, altchars=altchars), res) eq(base64.b64decode(data, altchars=altchars_str), res)", "= map01.decode('ascii') eq(base64.b32decode(data, map01=map01), res) eq(base64.b32decode(data_str, map01=map01), res) eq(base64.b32decode(data, map01=map01_str),", "self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\\n'), StringIO()) self.assertRaises(TypeError, base64.encode,", "if os.path.exists(support.TESTFN): os.unlink(support.TESTFN) def get_output(self, *args, **options): args = (sys.executable,", "base64.b64decode(bstr, validate=True) with self.assertRaises(binascii.Error): base64.b64decode(bstr.decode('ascii'), validate=True) def test_b32encode(self): eq =", "self.assertRaises(binascii.Error, base64.b16decode, '0102abcdef') # Case fold eq(base64.b16decode(b'0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102abcdef',", "import binascii import os import sys import subprocess class LegacyBase64TestCase(unittest.TestCase):", "support.TESTFN) self.assertEqual(output.rstrip(), b'Yf9iCg==') with open(support.TESTFN, 'rb') as fp: output =", "res) eq(base64.b32decode(data, map01=map01_str), res) eq(base64.b32decode(data_str, map01=map01_str), res) self.assertRaises(binascii.Error, base64.b32decode, data)", "base64.encode, StringIO('YWJj\\n'), StringIO()) class BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual", "self.assertRaises(TypeError, base64.b32encode, \"\") def test_b32decode(self): eq = self.assertEqual tests =", "b'0123456789!@#0^&*();:<>,. []{}') outfp = BytesIO() base64.encode(infp, outfp) eq(outfp.getvalue(), b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT'", "eq(base64.b32encode(b''), b'') eq(base64.b32encode(b'\\x00'), b'AA======') eq(base64.b32encode(b'a'), b'ME======') eq(base64.b32encode(b'ab'), b'MFRA====') eq(base64.b32encode(b'abc'), b'MFRGG===')", "eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray(b'*$')), b'01a*b$cd') # Check if passing a str object", "altchars=altchars), res) eq(base64.b64decode(data, altchars=altchars_str), res) eq(base64.b64decode(data_str, altchars=altchars_str), res) # Test", "[b'abc', b'ABCDEF==', b'==ABCDEF']: with self.assertRaises(binascii.Error): base64.b32decode(data) with self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii')) def", "# Lower case is not allowed without a flag self.assertRaises(binascii.Error,", "Case fold eq(base64.b16decode(b'0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102abcdef', True), b'\\x01\\x02\\xab\\xcd\\xef') # Non-bytes", "b\"a\", b\"YWI=\": b\"ab\", b\"YWJj\": b\"abc\", b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\": b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", "safe' alternative characters tests_urlsafe = {b'01a-b_cd': b'\\xd3V\\xbeo\\xf7\\x1d', b'': b'', }", "b\"YWJj\") eq(base64.b64encode(b\"\"), b\"\") eq(base64.b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\")", "eq(base64.encodebytes(b\"\"), b\"\") eq(base64.encodebytes(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\") #", "# Non-bytes eq(base64.standard_b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with 'URL safe' alternative", "stdin=fp) self.assertEqual(output.rstrip(), b'Yf9iCg==') def test_decode(self): with open(support.TESTFN, 'wb') as fp:", "test_b64decode_invalid_chars(self): # issue 1466065: Test some invalid characters. tests =", "Non-bytes eq(base64.b32decode(bytearray(b'MFRGG===')), b'abc') def test_b32decode_casefold(self): eq = self.assertEqual tests =", "data, res in tests.items(): eq(base64.b32decode(data, True), res) eq(base64.b32decode(data.decode('ascii'), True), res)", "res) # Non-bytes eq(base64.b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with arbitrary alternative", "def test_decode(self): with open(support.TESTFN, 'wb') as fp: fp.write(b'Yf9iCg==') output =", "= {b'01a-b_cd': b'\\xd3V\\xbeo\\xf7\\x1d', b'': b'', } for data, res in", "raises an error self.assertRaises(TypeError, base64.b64encode, \"\") self.assertRaises(TypeError, base64.b64encode, b\"\", altchars=\"\")", "b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', #", "b'mfrggzdf': b'abcde', } for data, res in tests.items(): eq(base64.b32decode(data, True),", "1466065: Test some invalid characters. tests = ((b'%3d==', b'\\xdd'), (b'$3d==',", "b\"\") eq(base64.b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Test", "base64.encode, StringIO('abc'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'abc'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('abc'),", "base64.b32encode, \"\") def test_b32decode(self): eq = self.assertEqual tests = {b'':", "tests.items(): eq(base64.b32decode(data), res) eq(base64.b32decode(data.decode('ascii')), res) # Non-bytes eq(base64.b32decode(bytearray(b'MFRGG===')), b'abc') def", "eq(base64.b16encode(b'\\x01\\x02\\xab\\xcd\\xef'), b'0102ABCDEF') eq(base64.b16encode(b'\\x00'), b'00') # Non-bytes eq(base64.b16encode(bytearray(b'\\x01\\x02\\xab\\xcd\\xef')), b'0102ABCDEF') self.assertRaises(TypeError, base64.b16encode,", "TestMain(unittest.TestCase): def tearDown(self): if os.path.exists(support.TESTFN): os.unlink(support.TESTFN) def get_output(self, *args, **options):", "io import BytesIO, StringIO infp = BytesIO(b'd3d3LnB5dGhvbi5vcmc=') outfp = BytesIO()", "= {(b'01a*b$cd', b'*$'): b'\\xd3V\\xbeo\\xf7\\x1d', } for (data, altchars), res in", "b\"YWJj\\n\") eq(base64.encodebytes(b\"\"), b\"\") eq(base64.encodebytes(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\")", "eq = self.assertEqual eq(base64.decodebytes(b\"d3d3LnB5dGhvbi5vcmc=\\n\"), b\"www.python.org\") eq(base64.decodebytes(b\"YQ==\\n\"), b\"a\") eq(base64.decodebytes(b\"YWI=\\n\"), b\"ab\") eq(base64.decodebytes(b\"YWJj\\n\"),", "Non-bytes eq(base64.decodebytes(bytearray(b'YWJj\\n')), b'abc') self.assertRaises(TypeError, base64.decodebytes, \"\") def test_encode(self): eq =", "infp = BytesIO(b'abcdefghijklmnopqrstuvwxyz' b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' b'0123456789!@#0^&*();:<>,. []{}') outfp = BytesIO() base64.encode(infp,", "test_b32decode_error(self): for data in [b'abc', b'ABCDEF==', b'==ABCDEF']: with self.assertRaises(binascii.Error): base64.b32decode(data)", "b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\") # Non-bytes eq(base64.standard_b64encode(bytearray(b'abcd')), b'YWJjZA==') # Check if passing", "# Non-bytes eq(base64.b64encode(bytearray(b'abcd')), b'YWJjZA==') eq(base64.b64encode(b'\\xd3V\\xbeo\\xf7\\x1d', altchars=bytearray(b'*$')), b'01a*b$cd') # Check if", "files self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), BytesIO()) self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\\n'), StringIO()) self.assertRaises(TypeError,", "**options) def test_encode_decode(self): output = self.get_output('-t') self.assertSequenceEqual(output.splitlines(), ( b\"b'Aladdin:open sesame'\",", "self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\\n'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('YWJj\\n'), StringIO()) class BaseXYTestCase(unittest.TestCase):", "eq(base64.b32encode(b'ab'), b'MFRA====') eq(base64.b32encode(b'abc'), b'MFRGG===') eq(base64.b32encode(b'abcd'), b'MFRGGZA=') eq(base64.b32encode(b'abcde'), b'MFRGGZDF') # Non-bytes", "b'0102ABCDEF') self.assertRaises(TypeError, base64.b16encode, \"\") def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode(b'0102ABCDEF'),", "Test with arbitrary alternative characters tests_altchars = {(b'01a*b$cd', b'*$'): b'\\xd3V\\xbeo\\xf7\\x1d',", "# Non-bytes eq(base64.b16encode(bytearray(b'\\x01\\x02\\xab\\xcd\\xef')), b'0102ABCDEF') self.assertRaises(TypeError, base64.b16encode, \"\") def test_b16decode(self): eq", "= self.assertEqual eq(base64.encodebytes(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\\n\") eq(base64.encodebytes(b\"a\"), b\"YQ==\\n\") eq(base64.encodebytes(b\"ab\"), b\"YWI=\\n\") eq(base64.encodebytes(b\"abc\"), b\"YWJj\\n\")", "if passing a str object raises an error self.assertRaises(TypeError, base64.b64encode,", "Test with 'URL safe' alternative characters eq(base64.urlsafe_b64encode(b'\\xd3V\\xbeo\\xf7\\x1d'), b'01a-b_cd') # Non-bytes", "b\"YWI=\\n\") eq(base64.encodebytes(b\"abc\"), b\"YWJj\\n\") eq(base64.encodebytes(b\"\"), b\"\") eq(base64.encodebytes(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\"", "b'') eq(base64.b32encode(b'\\x00'), b'AA======') eq(base64.b32encode(b'a'), b'ME======') eq(base64.b32encode(b'ab'), b'MFRA====') eq(base64.b32encode(b'abc'), b'MFRGG===') eq(base64.b32encode(b'abcd'),", "self.assertRaises(TypeError, base64.encode, BytesIO(b'abc'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('abc'), StringIO()) def test_decode(self):", "sesame'\", )) def test_encode_file(self): with open(support.TESTFN, 'wb') as fp: fp.write(b'a\\xffb\\n')", "= self.get_output('-t') self.assertSequenceEqual(output.splitlines(), ( b\"b'Aladdin:open sesame'\", br\"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\n'\", b\"b'Aladdin:open sesame'\", ))", "eq(base64.b32encode(b'abcde'), b'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray(b'abcd')), b'MFRGGZA=') self.assertRaises(TypeError, base64.b32encode, \"\") def", "b'\\x01\\x02\\xab\\xcd\\xef') # Non-bytes eq(base64.b16decode(bytearray(b\"0102ABCDEF\")), b'\\x01\\x02\\xab\\xcd\\xef') def test_decode_nonascii_str(self): decode_funcs = (base64.b64decode,", "= self.assertEqual tests = {b'': b'', b'AA======': b'\\x00', b'ME======': b'a',", "base64.encode(infp, outfp) eq(outfp.getvalue(), b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') # Non-binary files self.assertRaises(TypeError,", "self.get_output('-d', support.TESTFN) self.assertEqual(output.rstrip(), b'a\\xffb') def test_main(): support.run_unittest(__name__) if __name__ ==", "in tests.items(): eq(base64.standard_b64decode(data), res) eq(base64.standard_b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.standard_b64decode(bytearray(b\"YWJj\")), b\"abc\")", "b'abcab')) for bstr, res in tests: self.assertEqual(base64.b64decode(bstr), res) self.assertEqual(base64.b64decode(bstr.decode('ascii')), res)", "binascii import os import sys import subprocess class LegacyBase64TestCase(unittest.TestCase): def", "in tests: self.assertEqual(base64.b64decode(bstr), res) self.assertEqual(base64.b64decode(bstr.decode('ascii')), res) with self.assertRaises(binascii.Error): base64.b64decode(bstr, validate=True)", "with open(support.TESTFN, 'wb') as fp: fp.write(b'a\\xffb\\n') output = self.get_output('-e', support.TESTFN)", "data) self.assertRaises(binascii.Error, base64.b32decode, data_str) def test_b32decode_error(self): for data in [b'abc',", "BaseXYTestCase(unittest.TestCase): def test_b64encode(self): eq = self.assertEqual # Test default alphabet", "eq(base64.b16decode(b'0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode('0102ABCDEF'), b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode(b'00'), b'\\x00') eq(base64.b16decode('00'), b'\\x00') # Lower", "eq(base64.b64encode(b'\\x00'), b'AA==') eq(base64.b64encode(b\"a\"), b\"YQ==\") eq(base64.b64encode(b\"ab\"), b\"YWI=\") eq(base64.b64encode(b\"abc\"), b\"YWJj\") eq(base64.b64encode(b\"\"), b\"\")", "b\"YWI=\") eq(base64.b64encode(b\"abc\"), b\"YWJj\") eq(base64.b64encode(b\"\"), b\"\") eq(base64.b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\"), b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\"", "eq(base64.decodebytes(b\"YWI=\\n\"), b\"ab\") eq(base64.decodebytes(b\"YWJj\\n\"), b\"abc\") eq(base64.decodebytes(b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,.", "def test_b64encode(self): eq = self.assertEqual # Test default alphabet eq(base64.b64encode(b\"www.python.org\"),", "b''), (b'YW]3=', b'am'), (b'3{d==', b'\\xdd'), (b'3d}==', b'\\xdd'), (b'@@', b''), (b'!',", "b'abc') def test_b32decode_casefold(self): eq = self.assertEqual tests = {b'': b'',", "args return subprocess.check_output(args, **options) def test_encode_decode(self): output = self.get_output('-t') self.assertSequenceEqual(output.splitlines(),", "def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(b''), b'') eq(base64.b32encode(b'\\x00'), b'AA======') eq(base64.b32encode(b'a'),", "b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodebytes(b''), b'') # Non-bytes eq(base64.decodebytes(bytearray(b'YWJj\\n')),", "b'\\x00') eq(base64.b16decode('00'), b'\\x00') # Lower case is not allowed without", "eq(outfp.getvalue(), b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n') # Non-binary files self.assertRaises(TypeError, base64.encode, StringIO('abc'),", "altchars=bytearray(b'*$')), b'01a*b$cd') # Check if passing a str object raises", "base64.encodebytes, \"\") def test_decodebytes(self): eq = self.assertEqual eq(base64.decodebytes(b\"d3d3LnB5dGhvbi5vcmc=\\n\"), b\"www.python.org\") eq(base64.decodebytes(b\"YQ==\\n\"),", "class TestMain(unittest.TestCase): def tearDown(self): if os.path.exists(support.TESTFN): os.unlink(support.TESTFN) def get_output(self, *args,", "self.assertEqual from io import BytesIO, StringIO infp = BytesIO(b'abcdefghijklmnopqrstuvwxyz' b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'", "def test_encode_decode(self): output = self.get_output('-t') self.assertSequenceEqual(output.splitlines(), ( b\"b'Aladdin:open sesame'\", br\"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\n'\",", "self.get_output('-e', support.TESTFN) self.assertEqual(output.rstrip(), b'Yf9iCg==') with open(support.TESTFN, 'rb') as fp: output", "b'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray(b'abcd')), b'MFRGGZA=') self.assertRaises(TypeError, base64.b32encode, \"\") def test_b32decode(self):", "(b'M1023456', b'I'): b'b\\x1d\\xad\\xf3\\xbe', } for (data, map01), res in map_tests.items():", "# issue 1466065: Test some invalid characters. tests = ((b'%3d==',", "fp: fp.write(b'Yf9iCg==') output = self.get_output('-d', support.TESTFN) self.assertEqual(output.rstrip(), b'a\\xffb') def test_main():", "b\"YQ==\") eq(base64.b64encode(b\"ab\"), b\"YWI=\") eq(base64.b64encode(b\"abc\"), b\"YWJj\") eq(base64.b64encode(b\"\"), b\"\") eq(base64.b64encode(b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,.", "decode_funcs: self.assertRaises(ValueError, f, 'with non-ascii \\xcb') def test_ErrorHeritage(self): self.assertTrue(issubclass(binascii.Error, ValueError))", "res in map_tests.items(): data_str = data.decode('ascii') map01_str = map01.decode('ascii') eq(base64.b32decode(data,", "test_decode(self): with open(support.TESTFN, 'wb') as fp: fp.write(b'Yf9iCg==') output = self.get_output('-d',", "b'\\x01\\x02\\xab\\xcd\\xef') eq(base64.b16decode(b'00'), b'\\x00') eq(base64.b16decode('00'), b'\\x00') # Lower case is not", "# Non-bytes eq(base64.b16decode(bytearray(b\"0102ABCDEF\")), b'\\x01\\x02\\xab\\xcd\\xef') def test_decode_nonascii_str(self): decode_funcs = (base64.b64decode, base64.standard_b64decode,", "b'AA==': b'\\x00', b\"YQ==\": b\"a\", b\"YWI=\": b\"ab\", b\"YWJj\": b\"abc\", b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\"", "[]{}') outfp = BytesIO() base64.encode(infp, outfp) eq(outfp.getvalue(), b'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' b'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT' b'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n')", ")) def test_encode_file(self): with open(support.TESTFN, 'wb') as fp: fp.write(b'a\\xffb\\n') output", "test_encode_file(self): with open(support.TESTFN, 'wb') as fp: fp.write(b'a\\xffb\\n') output = self.get_output('-e',", "b'abcde', } for data, res in tests.items(): eq(base64.b32decode(data), res) eq(base64.b32decode(data.decode('ascii')),", "eq(base64.decodebytes(b\"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE\" b\"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\\nNT\" b\"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\\n\"), b\"abcdefghijklmnopqrstuvwxyz\" b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodebytes(b''), b'') #", "= data.decode('ascii') altchars_str = altchars.decode('ascii') eq(base64.b64decode(data, altchars=altchars), res) eq(base64.b64decode(data_str, altchars=altchars),", "StringIO infp = BytesIO(b'd3d3LnB5dGhvbi5vcmc=') outfp = BytesIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(),", "self.assertEqual eq(base64.b32encode(b''), b'') eq(base64.b32encode(b'\\x00'), b'AA======') eq(base64.b32encode(b'a'), b'ME======') eq(base64.b32encode(b'ab'), b'MFRA====') eq(base64.b32encode(b'abc'),", "Test standard alphabet eq(base64.standard_b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.standard_b64encode(b\"a\"), b\"YQ==\") eq(base64.standard_b64encode(b\"ab\"), b\"YWI=\") eq(base64.standard_b64encode(b\"abc\"),", "b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" b\"0123456789!@#0^&*();:<>,. []{}\") eq(base64.decodebytes(b''), b'') # Non-bytes eq(base64.decodebytes(bytearray(b'YWJj\\n')), b'abc') self.assertRaises(TypeError,", "alternative characters eq(base64.urlsafe_b64encode(b'\\xd3V\\xbeo\\xf7\\x1d'), b'01a-b_cd') # Non-bytes eq(base64.urlsafe_b64encode(bytearray(b'\\xd3V\\xbeo\\xf7\\x1d')), b'01a-b_cd') # Check", "eq(base64.b32decode(data.decode('ascii'), True), res) self.assertRaises(binascii.Error, base64.b32decode, b'me======') self.assertRaises(binascii.Error, base64.b32decode, 'me======') #", "outfp = BytesIO() base64.decode(infp, outfp) self.assertEqual(outfp.getvalue(), b'www.python.org') # Non-binary files", "BytesIO(b'abc'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('abc'), StringIO()) def test_decode(self): from io", "res) eq(base64.b32decode(data_str, map01=map01), res) eq(base64.b32decode(data, map01=map01_str), res) eq(base64.b32decode(data_str, map01=map01_str), res)", "import unittest from test import support import base64 import binascii", "b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', # Lower", "bstr, res in tests: self.assertEqual(base64.b64decode(bstr), res) self.assertEqual(base64.b64decode(bstr.decode('ascii')), res) with self.assertRaises(binascii.Error):", "tests = {b\"d3d3LnB5dGhvbi5vcmc=\": b\"www.python.org\", b'AA==': b'\\x00', b\"YQ==\": b\"a\", b\"YWI=\": b\"ab\",", "{b'01a-b_cd': b'\\xd3V\\xbeo\\xf7\\x1d', b'': b'', } for data, res in tests_urlsafe.items():", "b'\\xd3V\\xbeo\\xf7\\x1d') def test_b64decode_padding_error(self): self.assertRaises(binascii.Error, base64.b64decode, b'abc') self.assertRaises(binascii.Error, base64.b64decode, 'abc') def", "b'MFRA====') eq(base64.b32encode(b'abc'), b'MFRGG===') eq(base64.b32encode(b'abcd'), b'MFRGGZA=') eq(base64.b32encode(b'abcde'), b'MFRGGZDF') # Non-bytes eq(base64.b32encode(bytearray(b'abcd')),", "(base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode, base64.b32decode, base64.b16decode) for f in decode_funcs: self.assertRaises(ValueError,", "with self.assertRaises(binascii.Error): base64.b64decode(bstr.decode('ascii'), validate=True) def test_b32encode(self): eq = self.assertEqual eq(base64.b32encode(b''),", "res) eq(base64.b64decode(data.decode('ascii')), res) # Non-bytes eq(base64.b64decode(bytearray(b\"YWJj\")), b\"abc\") # Test with", "eq(base64.b64encode(b\"www.python.org\"), b\"d3d3LnB5dGhvbi5vcmc=\") eq(base64.b64encode(b'\\x00'), b'AA==') eq(base64.b64encode(b\"a\"), b\"YQ==\") eq(base64.b64encode(b\"ab\"), b\"YWI=\") eq(base64.b64encode(b\"abc\"), b\"YWJj\")", "((b'%3d==', b'\\xdd'), (b'$3d==', b'\\xdd'), (b'[==', b''), (b'YW]3=', b'am'), (b'3{d==', b'\\xdd'),", "res) eq(base64.b32decode(data_str, map01=map01_str), res) self.assertRaises(binascii.Error, base64.b32decode, data) self.assertRaises(binascii.Error, base64.b32decode, data_str)", "in tests.items(): eq(base64.b32decode(data), res) eq(base64.b32decode(data.decode('ascii')), res) # Non-bytes eq(base64.b32decode(bytearray(b'MFRGG===')), b'abc')" ]
[ "import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): \"\"\"Updates", "[ ('appliance_catalog', '0014_auto_20180625_1104'), ] operations = [ migrations.AlterField( model_name='appliance', name='appliance_icon',", "-*- coding: utf-8 -*- # Generated by Django 1.11.29 on", "20:32 from __future__ import unicode_literals from django.db import migrations, models", "<filename>appliance_catalog/migrations/0015_appliance_icon_py3.py # -*- coding: utf-8 -*- # Generated by Django", "on 2021-02-25 20:32 from __future__ import unicode_literals from django.db import", "-*- # Generated by Django 1.11.29 on 2021-02-25 20:32 from", "import migrations, models class Migration(migrations.Migration): \"\"\"Updates ImageField syntax for later", "utf-8 -*- # Generated by Django 1.11.29 on 2021-02-25 20:32", "1.11.29 on 2021-02-25 20:32 from __future__ import unicode_literals from django.db", "('appliance_catalog', '0014_auto_20180625_1104'), ] operations = [ migrations.AlterField( model_name='appliance', name='appliance_icon', field=models.ImageField(blank=True,", "ImageField syntax for later version. \"\"\" dependencies = [ ('appliance_catalog',", "# Generated by Django 1.11.29 on 2021-02-25 20:32 from __future__", "= [ ('appliance_catalog', '0014_auto_20180625_1104'), ] operations = [ migrations.AlterField( model_name='appliance',", "Django 1.11.29 on 2021-02-25 20:32 from __future__ import unicode_literals from", "unicode_literals from django.db import migrations, models class Migration(migrations.Migration): \"\"\"Updates ImageField", "syntax for later version. \"\"\" dependencies = [ ('appliance_catalog', '0014_auto_20180625_1104'),", "'0014_auto_20180625_1104'), ] operations = [ migrations.AlterField( model_name='appliance', name='appliance_icon', field=models.ImageField(blank=True, upload_to='appliance_catalog/icons/'),", "] operations = [ migrations.AlterField( model_name='appliance', name='appliance_icon', field=models.ImageField(blank=True, upload_to='appliance_catalog/icons/'), ),", "# -*- coding: utf-8 -*- # Generated by Django 1.11.29", "dependencies = [ ('appliance_catalog', '0014_auto_20180625_1104'), ] operations = [ migrations.AlterField(", "by Django 1.11.29 on 2021-02-25 20:32 from __future__ import unicode_literals", "for later version. \"\"\" dependencies = [ ('appliance_catalog', '0014_auto_20180625_1104'), ]", "django.db import migrations, models class Migration(migrations.Migration): \"\"\"Updates ImageField syntax for", "\"\"\" dependencies = [ ('appliance_catalog', '0014_auto_20180625_1104'), ] operations = [", "Generated by Django 1.11.29 on 2021-02-25 20:32 from __future__ import", "models class Migration(migrations.Migration): \"\"\"Updates ImageField syntax for later version. \"\"\"", "2021-02-25 20:32 from __future__ import unicode_literals from django.db import migrations,", "migrations, models class Migration(migrations.Migration): \"\"\"Updates ImageField syntax for later version.", "class Migration(migrations.Migration): \"\"\"Updates ImageField syntax for later version. \"\"\" dependencies", "Migration(migrations.Migration): \"\"\"Updates ImageField syntax for later version. \"\"\" dependencies =", "coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-02-25", "__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):", "from __future__ import unicode_literals from django.db import migrations, models class", "from django.db import migrations, models class Migration(migrations.Migration): \"\"\"Updates ImageField syntax", "version. \"\"\" dependencies = [ ('appliance_catalog', '0014_auto_20180625_1104'), ] operations =", "operations = [ migrations.AlterField( model_name='appliance', name='appliance_icon', field=models.ImageField(blank=True, upload_to='appliance_catalog/icons/'), ), ]", "later version. \"\"\" dependencies = [ ('appliance_catalog', '0014_auto_20180625_1104'), ] operations", "\"\"\"Updates ImageField syntax for later version. \"\"\" dependencies = [" ]
[ "in tweets: tweet_vector = vectorize_tweet(tweet[\"full_text\"]) tweet_id = tweet[\"id\"] db_tweet =", "import spacy from .models import DB, Tweet, User nlp =", "or Tweet( id=tweet[\"id\"], text=tweet[\"full_text\"], vect=tweet_vector) db_user.tweets.append(db_tweet) DB.session.add(db_tweet) except Exception as", "respectively grabs or creates a user for our db db_user", "user_id = user[\"twitter_handle\"][\"id\"] # print(user) # This is either respectively", "our database \"\"\" #TODO: Figure out try: r = requests.get(", "user[\"twitter_handle\"][\"id\"] # print(user) # This is either respectively grabs or", "a user for our db db_user = (User.query.get(user_id)) or User(id=user_id,", "def vectorize_tweet(tweet_text): return nlp(tweet_text).vector # Add and updates tweets def", "or User(id=user_id, name=username) # This adds the db_user to our", "e: print(\"Error processing {}: {}\".format(username, e)) raise e else: DB.session.commit()", "r.json() user_id = user[\"twitter_handle\"][\"id\"] # print(user) # This is either", "or creates a user for our db db_user = (User.query.get(user_id))", "from the DS API\"\"\" import requests import spacy from .models", "= tweet[\"id\"] db_tweet = (Tweet.query.get(tweet_id)) or Tweet( id=tweet[\"id\"], text=tweet[\"full_text\"], vect=tweet_vector)", "= (User.query.get(user_id)) or User(id=user_id, name=username) # This adds the db_user", "= requests.get( f\"https://lambda-ds-twit-assist.herokuapp.com/user/{username}\") user = r.json() user_id = user[\"twitter_handle\"][\"id\"] #", "import requests import spacy from .models import DB, Tweet, User", "name=username) # This adds the db_user to our database DB.session.add(db_user)", "DB, Tweet, User nlp = spacy.load(\"my_model\") def vectorize_tweet(tweet_text): return nlp(tweet_text).vector", "db_user = (User.query.get(user_id)) or User(id=user_id, name=username) # This adds the", "= (Tweet.query.get(tweet_id)) or Tweet( id=tweet[\"id\"], text=tweet[\"full_text\"], vect=tweet_vector) db_user.tweets.append(db_tweet) DB.session.add(db_tweet) except", "from .models import DB, Tweet, User nlp = spacy.load(\"my_model\") def", "DB.session.add(db_user) tweets = user[\"tweets\"] # if tweets: # db_user.newest_tweet_id =", "for tweet in tweets: tweet_vector = vectorize_tweet(tweet[\"full_text\"]) tweet_id = tweet[\"id\"]", "This adds the db_user to our database DB.session.add(db_user) tweets =", "our db db_user = (User.query.get(user_id)) or User(id=user_id, name=username) # This", "and request tweets from the DS API\"\"\" import requests import", "\"\"\" #TODO: Figure out try: r = requests.get( f\"https://lambda-ds-twit-assist.herokuapp.com/user/{username}\") user", "Tweet, User nlp = spacy.load(\"my_model\") def vectorize_tweet(tweet_text): return nlp(tweet_text).vector #", "tweets def add_or_update_user(username): \"\"\"Adds and updates the user with twiter", "DB.session.add(db_tweet) except Exception as e: print(\"Error processing {}: {}\".format(username, e))", "tweet[\"id\"] db_tweet = (Tweet.query.get(tweet_id)) or Tweet( id=tweet[\"id\"], text=tweet[\"full_text\"], vect=tweet_vector) db_user.tweets.append(db_tweet)", "either respectively grabs or creates a user for our db", "as e: print(\"Error processing {}: {}\".format(username, e)) raise e else:", "except Exception as e: print(\"Error processing {}: {}\".format(username, e)) raise", "API\"\"\" import requests import spacy from .models import DB, Tweet,", "f\"https://lambda-ds-twit-assist.herokuapp.com/user/{username}\") user = r.json() user_id = user[\"twitter_handle\"][\"id\"] # print(user) #", "User(id=user_id, name=username) # This adds the db_user to our database", "vectorize_tweet(tweet[\"full_text\"]) tweet_id = tweet[\"id\"] db_tweet = (Tweet.query.get(tweet_id)) or Tweet( id=tweet[\"id\"],", "the db_user to our database DB.session.add(db_user) tweets = user[\"tweets\"] #", "vect=tweet_vector) db_user.tweets.append(db_tweet) DB.session.add(db_tweet) except Exception as e: print(\"Error processing {}:", "\"\"\"Retrieve and request tweets from the DS API\"\"\" import requests", "'username' to our database \"\"\" #TODO: Figure out try: r", "db_user.newest_tweet_id = tweets[0].id for tweet in tweets: tweet_vector = vectorize_tweet(tweet[\"full_text\"])", "to our database DB.session.add(db_user) tweets = user[\"tweets\"] # if tweets:", "# This is either respectively grabs or creates a user", "the DS API\"\"\" import requests import spacy from .models import", "user[\"tweets\"] # if tweets: # db_user.newest_tweet_id = tweets[0].id for tweet", "db_user.tweets.append(db_tweet) DB.session.add(db_tweet) except Exception as e: print(\"Error processing {}: {}\".format(username,", "# db_user.newest_tweet_id = tweets[0].id for tweet in tweets: tweet_vector =", "db_user to our database DB.session.add(db_user) tweets = user[\"tweets\"] # if", "add_or_update_user(username): \"\"\"Adds and updates the user with twiter handle 'username'", "= user[\"tweets\"] # if tweets: # db_user.newest_tweet_id = tweets[0].id for", "Tweet( id=tweet[\"id\"], text=tweet[\"full_text\"], vect=tweet_vector) db_user.tweets.append(db_tweet) DB.session.add(db_tweet) except Exception as e:", "updates tweets def add_or_update_user(username): \"\"\"Adds and updates the user with", "user with twiter handle 'username' to our database \"\"\" #TODO:", "tweets = user[\"tweets\"] # if tweets: # db_user.newest_tweet_id = tweets[0].id", "tweets: tweet_vector = vectorize_tweet(tweet[\"full_text\"]) tweet_id = tweet[\"id\"] db_tweet = (Tweet.query.get(tweet_id))", "spacy.load(\"my_model\") def vectorize_tweet(tweet_text): return nlp(tweet_text).vector # Add and updates tweets", "if tweets: # db_user.newest_tweet_id = tweets[0].id for tweet in tweets:", "nlp(tweet_text).vector # Add and updates tweets def add_or_update_user(username): \"\"\"Adds and", "tweets: # db_user.newest_tweet_id = tweets[0].id for tweet in tweets: tweet_vector", "tweets from the DS API\"\"\" import requests import spacy from", "to our database \"\"\" #TODO: Figure out try: r =", "tweets[0].id for tweet in tweets: tweet_vector = vectorize_tweet(tweet[\"full_text\"]) tweet_id =", "= r.json() user_id = user[\"twitter_handle\"][\"id\"] # print(user) # This is", ".models import DB, Tweet, User nlp = spacy.load(\"my_model\") def vectorize_tweet(tweet_text):", "database \"\"\" #TODO: Figure out try: r = requests.get( f\"https://lambda-ds-twit-assist.herokuapp.com/user/{username}\")", "# Add and updates tweets def add_or_update_user(username): \"\"\"Adds and updates", "spacy from .models import DB, Tweet, User nlp = spacy.load(\"my_model\")", "out try: r = requests.get( f\"https://lambda-ds-twit-assist.herokuapp.com/user/{username}\") user = r.json() user_id", "db_tweet = (Tweet.query.get(tweet_id)) or Tweet( id=tweet[\"id\"], text=tweet[\"full_text\"], vect=tweet_vector) db_user.tweets.append(db_tweet) DB.session.add(db_tweet)", "tweet in tweets: tweet_vector = vectorize_tweet(tweet[\"full_text\"]) tweet_id = tweet[\"id\"] db_tweet", "= spacy.load(\"my_model\") def vectorize_tweet(tweet_text): return nlp(tweet_text).vector # Add and updates", "for our db db_user = (User.query.get(user_id)) or User(id=user_id, name=username) #", "tweet_vector = vectorize_tweet(tweet[\"full_text\"]) tweet_id = tweet[\"id\"] db_tweet = (Tweet.query.get(tweet_id)) or", "id=tweet[\"id\"], text=tweet[\"full_text\"], vect=tweet_vector) db_user.tweets.append(db_tweet) DB.session.add(db_tweet) except Exception as e: print(\"Error", "r = requests.get( f\"https://lambda-ds-twit-assist.herokuapp.com/user/{username}\") user = r.json() user_id = user[\"twitter_handle\"][\"id\"]", "print(user) # This is either respectively grabs or creates a", "# This adds the db_user to our database DB.session.add(db_user) tweets", "updates the user with twiter handle 'username' to our database", "and updates tweets def add_or_update_user(username): \"\"\"Adds and updates the user", "User nlp = spacy.load(\"my_model\") def vectorize_tweet(tweet_text): return nlp(tweet_text).vector # Add", "db db_user = (User.query.get(user_id)) or User(id=user_id, name=username) # This adds", "nlp = spacy.load(\"my_model\") def vectorize_tweet(tweet_text): return nlp(tweet_text).vector # Add and", "<reponame>ChristopherKchilton/twitoff-ChristopherKchilton \"\"\"Retrieve and request tweets from the DS API\"\"\" import", "(Tweet.query.get(tweet_id)) or Tweet( id=tweet[\"id\"], text=tweet[\"full_text\"], vect=tweet_vector) db_user.tweets.append(db_tweet) DB.session.add(db_tweet) except Exception", "Add and updates tweets def add_or_update_user(username): \"\"\"Adds and updates the", "= tweets[0].id for tweet in tweets: tweet_vector = vectorize_tweet(tweet[\"full_text\"]) tweet_id", "user for our db db_user = (User.query.get(user_id)) or User(id=user_id, name=username)", "text=tweet[\"full_text\"], vect=tweet_vector) db_user.tweets.append(db_tweet) DB.session.add(db_tweet) except Exception as e: print(\"Error processing", "database DB.session.add(db_user) tweets = user[\"tweets\"] # if tweets: # db_user.newest_tweet_id", "requests.get( f\"https://lambda-ds-twit-assist.herokuapp.com/user/{username}\") user = r.json() user_id = user[\"twitter_handle\"][\"id\"] # print(user)", "is either respectively grabs or creates a user for our", "#TODO: Figure out try: r = requests.get( f\"https://lambda-ds-twit-assist.herokuapp.com/user/{username}\") user =", "vectorize_tweet(tweet_text): return nlp(tweet_text).vector # Add and updates tweets def add_or_update_user(username):", "creates a user for our db db_user = (User.query.get(user_id)) or", "This is either respectively grabs or creates a user for", "user = r.json() user_id = user[\"twitter_handle\"][\"id\"] # print(user) # This", "import DB, Tweet, User nlp = spacy.load(\"my_model\") def vectorize_tweet(tweet_text): return", "twiter handle 'username' to our database \"\"\" #TODO: Figure out", "handle 'username' to our database \"\"\" #TODO: Figure out try:", "with twiter handle 'username' to our database \"\"\" #TODO: Figure", "adds the db_user to our database DB.session.add(db_user) tweets = user[\"tweets\"]", "Figure out try: r = requests.get( f\"https://lambda-ds-twit-assist.herokuapp.com/user/{username}\") user = r.json()", "grabs or creates a user for our db db_user =", "the user with twiter handle 'username' to our database \"\"\"", "= vectorize_tweet(tweet[\"full_text\"]) tweet_id = tweet[\"id\"] db_tweet = (Tweet.query.get(tweet_id)) or Tweet(", "# print(user) # This is either respectively grabs or creates", "DS API\"\"\" import requests import spacy from .models import DB,", "\"\"\"Adds and updates the user with twiter handle 'username' to", "return nlp(tweet_text).vector # Add and updates tweets def add_or_update_user(username): \"\"\"Adds", "(User.query.get(user_id)) or User(id=user_id, name=username) # This adds the db_user to", "Exception as e: print(\"Error processing {}: {}\".format(username, e)) raise e", "request tweets from the DS API\"\"\" import requests import spacy", "and updates the user with twiter handle 'username' to our", "our database DB.session.add(db_user) tweets = user[\"tweets\"] # if tweets: #", "tweet_id = tweet[\"id\"] db_tweet = (Tweet.query.get(tweet_id)) or Tweet( id=tweet[\"id\"], text=tweet[\"full_text\"],", "try: r = requests.get( f\"https://lambda-ds-twit-assist.herokuapp.com/user/{username}\") user = r.json() user_id =", "requests import spacy from .models import DB, Tweet, User nlp", "= user[\"twitter_handle\"][\"id\"] # print(user) # This is either respectively grabs", "def add_or_update_user(username): \"\"\"Adds and updates the user with twiter handle", "# if tweets: # db_user.newest_tweet_id = tweets[0].id for tweet in" ]
[ "1 y = y // 2 x = x //", "x in range(len(l)): grid[(y,x)] = l[x] y += 1 y", "for iter in range(10000000): if (y,x) not in grid or", "io.open(\"day22.in\").read().splitlines(): for x in range(len(l)): grid[(y,x)] = l[x] y +=", "'F': (dy, dx) = (-dy, -dx) grid[(y,x)] = '.' y", "'#' r += 1 elif grid[(y,x)] == '#': (dy, dx)", "0 dy = -1 r = 0 for iter in", "== 'F': (dy, dx) = (-dy, -dx) grid[(y,x)] = '.'", "iter in range(10000000): if (y,x) not in grid or grid[(y,x)]", "dx) = (dx, -dy) grid[(y,x)] = 'F' elif grid[(y,x)] ==", "(-dy, -dx) grid[(y,x)] = '.' y += dy x +=", "if (y,x) not in grid or grid[(y,x)] == '.': (dy,", "{} y = 0 x = 0 for l in", "in range(len(l)): grid[(y,x)] = l[x] y += 1 y =", "// 2 x = x // 2 dx = 0", "1 elif grid[(y,x)] == '#': (dy, dx) = (dx, -dy)", "(-dx, dy) grid[(y,x)] = 'W' elif grid[(y,x)] == 'W': grid[(y,x)]", "grid[(y,x)] = 'W' elif grid[(y,x)] == 'W': grid[(y,x)] = '#'", "dy = -1 r = 0 for iter in range(10000000):", "= x // 2 dx = 0 dy = -1", "grid[(y,x)] = '#' r += 1 elif grid[(y,x)] == '#':", "range(len(l)): grid[(y,x)] = l[x] y += 1 y = y", "x = 0 for l in io.open(\"day22.in\").read().splitlines(): for x in", "(y,x) not in grid or grid[(y,x)] == '.': (dy, dx)", "grid[(y,x)] = l[x] y += 1 y = y //", "'F' elif grid[(y,x)] == 'F': (dy, dx) = (-dy, -dx)", "y = 0 x = 0 for l in io.open(\"day22.in\").read().splitlines():", "not in grid or grid[(y,x)] == '.': (dy, dx) =", "= 'W' elif grid[(y,x)] == 'W': grid[(y,x)] = '#' r", "dx = 0 dy = -1 r = 0 for", "-dx) grid[(y,x)] = '.' y += dy x += dx", "= (-dx, dy) grid[(y,x)] = 'W' elif grid[(y,x)] == 'W':", "(dy, dx) = (-dy, -dx) grid[(y,x)] = '.' y +=", "elif grid[(y,x)] == '#': (dy, dx) = (dx, -dy) grid[(y,x)]", "-1 r = 0 for iter in range(10000000): if (y,x)", "grid[(y,x)] = 'F' elif grid[(y,x)] == 'F': (dy, dx) =", "y // 2 x = x // 2 dx =", "r = 0 for iter in range(10000000): if (y,x) not", "= (dx, -dy) grid[(y,x)] = 'F' elif grid[(y,x)] == 'F':", "0 for l in io.open(\"day22.in\").read().splitlines(): for x in range(len(l)): grid[(y,x)]", "l in io.open(\"day22.in\").read().splitlines(): for x in range(len(l)): grid[(y,x)] = l[x]", "// 2 dx = 0 dy = -1 r =", "'W': grid[(y,x)] = '#' r += 1 elif grid[(y,x)] ==", "-dy) grid[(y,x)] = 'F' elif grid[(y,x)] == 'F': (dy, dx)", "== 'W': grid[(y,x)] = '#' r += 1 elif grid[(y,x)]", "2 dx = 0 dy = -1 r = 0", "import io grid = {} y = 0 x =", "'W' elif grid[(y,x)] == 'W': grid[(y,x)] = '#' r +=", "grid[(y,x)] == 'W': grid[(y,x)] = '#' r += 1 elif", "= 0 x = 0 for l in io.open(\"day22.in\").read().splitlines(): for", "y += 1 y = y // 2 x =", "= 0 dy = -1 r = 0 for iter", "= 'F' elif grid[(y,x)] == 'F': (dy, dx) = (-dy,", "(dy, dx) = (dx, -dy) grid[(y,x)] = 'F' elif grid[(y,x)]", "= 0 for l in io.open(\"day22.in\").read().splitlines(): for x in range(len(l)):", "(dx, -dy) grid[(y,x)] = 'F' elif grid[(y,x)] == 'F': (dy,", "+= 1 y = y // 2 x = x", "dx) = (-dy, -dx) grid[(y,x)] = '.' y += dy", "= -1 r = 0 for iter in range(10000000): if", "= 0 for iter in range(10000000): if (y,x) not in", "grid[(y,x)] = '.' y += dy x += dx print(r)", "= '#' r += 1 elif grid[(y,x)] == '#': (dy,", "grid[(y,x)] == 'F': (dy, dx) = (-dy, -dx) grid[(y,x)] =", "= l[x] y += 1 y = y // 2", "grid = {} y = 0 x = 0 for", "0 x = 0 for l in io.open(\"day22.in\").read().splitlines(): for x", "dy) grid[(y,x)] = 'W' elif grid[(y,x)] == 'W': grid[(y,x)] =", "l[x] y += 1 y = y // 2 x", "dx) = (-dx, dy) grid[(y,x)] = 'W' elif grid[(y,x)] ==", "elif grid[(y,x)] == 'W': grid[(y,x)] = '#' r += 1", "for l in io.open(\"day22.in\").read().splitlines(): for x in range(len(l)): grid[(y,x)] =", "'#': (dy, dx) = (dx, -dy) grid[(y,x)] = 'F' elif", "elif grid[(y,x)] == 'F': (dy, dx) = (-dy, -dx) grid[(y,x)]", "(dy, dx) = (-dx, dy) grid[(y,x)] = 'W' elif grid[(y,x)]", "r += 1 elif grid[(y,x)] == '#': (dy, dx) =", "x // 2 dx = 0 dy = -1 r", "grid or grid[(y,x)] == '.': (dy, dx) = (-dx, dy)", "2 x = x // 2 dx = 0 dy", "0 for iter in range(10000000): if (y,x) not in grid", "for x in range(len(l)): grid[(y,x)] = l[x] y += 1", "== '.': (dy, dx) = (-dx, dy) grid[(y,x)] = 'W'", "io grid = {} y = 0 x = 0", "= {} y = 0 x = 0 for l", "== '#': (dy, dx) = (dx, -dy) grid[(y,x)] = 'F'", "in range(10000000): if (y,x) not in grid or grid[(y,x)] ==", "in io.open(\"day22.in\").read().splitlines(): for x in range(len(l)): grid[(y,x)] = l[x] y", "grid[(y,x)] == '.': (dy, dx) = (-dx, dy) grid[(y,x)] =", "x = x // 2 dx = 0 dy =", "y = y // 2 x = x // 2", "in grid or grid[(y,x)] == '.': (dy, dx) = (-dx,", "= y // 2 x = x // 2 dx", "+= 1 elif grid[(y,x)] == '#': (dy, dx) = (dx,", "grid[(y,x)] == '#': (dy, dx) = (dx, -dy) grid[(y,x)] =", "= (-dy, -dx) grid[(y,x)] = '.' y += dy x", "range(10000000): if (y,x) not in grid or grid[(y,x)] == '.':", "or grid[(y,x)] == '.': (dy, dx) = (-dx, dy) grid[(y,x)]", "'.': (dy, dx) = (-dx, dy) grid[(y,x)] = 'W' elif" ]
[ "defined sweeping phase before plotting. \"\"\" _FIELD_CONTAINER_PLOTTING_MSG = \"\"\"\" This", "msg=None): if msg is None: msg = \"Feature not supported.", "msg = ( \"A \" + data_type + \" must", "type.\"\"\" def __init__(self, data_type, parameter_name): msg = ( \"A \"", "an object.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self, msg) class InvalidPortError(OSError): \"\"\"Error", "@wraps(func) def wrapper(*args, **kwargs): \"\"\"Capture gRPC exceptions.\"\"\" # Capture gRPC", "a field with complex data.\"\"\" def __init__(self, msg=_COMPLEX_PLOTTING_ERROR_MSG): ValueError.__init__(self, msg)", "\" must be used for the following parameter: \" +", "def __init__(self, data_type, parameter_name): msg = ( \"A \" +", "details = error.details() if \"object is null in the dataBase\"", "as error: details = error.details() if \"object is null in", "python features are not supported by the DPF gRPC server", "invalid port when starting DPF.\"\"\" def __init__(self, msg=\"\"): OSError.__init__(self, msg)", "__init__(self, msg=\"\"): Exception.__init__(self, msg) class InvalidPortError(OSError): \"\"\"Error raised when used", "\"\"\"Error raised when a parameter has the wrong type.\"\"\" def", "an invalid location.\"\"\" def __init__(self, msg=\"Invalid location\"): ValueError.__init__(self, msg) class", "def __init__(self, msg=_FIELD_CONTAINER_PLOTTING_MSG): ValueError.__init__(self, msg) class InvalidANSYSVersionError(RuntimeError): \"\"\"Error raised when", ") ValueError.__init__(self, msg) class LocationError(ValueError): \"\"\"Error raised when using an", "verion is invalid.\"\"\" def __init__(self, msg=\"\"): RuntimeError.__init__(self, msg) class DPFServerException(Exception):", "DPFServerNullObject(Exception): \"\"\"Error raised when the DPF server cannot find an", "defined.\"\"\" def __init__( self, msg=\"A value that has been set", "InvalidPortError(OSError): \"\"\"Error raised when used an invalid port when starting", "be plotted. Use operators to get the amplitude or the", "**kwargs): \"\"\"Capture gRPC exceptions.\"\"\" # Capture gRPC exceptions try: out", "when a specific DPF error value must be defined.\"\"\" def", "Upgrade the server to \" msg += str(version) msg +=", "in details: raise DPFServerNullObject(details) from None raise DPFServerException(details) from None", "the dataBase\" in details: raise DPFServerNullObject(details) from None raise DPFServerException(details)", "\"\"\"Error raised when the DPF server cannot find an object.\"\"\"", "): ValueError.__init__(self, msg) class InvalidTypeError(ValueError): \"\"\"Error raised when a parameter", "class DpfValueError(ValueError): \"\"\"Error raised when a specific DPF error value", "_COMPLEX_PLOTTING_ERROR_MSG = \"\"\" Complex fields cannot be plotted. Use operators", "to plot a fields_container containing multiple fields.\"\"\" def __init__(self, msg=_FIELD_CONTAINER_PLOTTING_MSG):", "operators to get the amplitude or the result at a", "__init__(self, msg=_COMPLEX_PLOTTING_ERROR_MSG): ValueError.__init__(self, msg) class FieldContainerPlottingError(ValueError): \"\"\"Error raised when attempting", "raised when attempting to plot a field with complex data.\"\"\"", "ComplexPlottingError(ValueError): \"\"\"Error raised when attempting to plot a field with", "class InvalidANSYSVersionError(RuntimeError): \"\"\"Error raised when the Ansys verion is invalid.\"\"\"", "out = func(*args, **kwargs) except (_InactiveRpcError, _MultiThreadedRendezvous) as error: details", "def __init__(self, msg=\"\"): Exception.__init__(self, msg) class DPFServerNullObject(Exception): \"\"\"Error raised when", "port when starting DPF.\"\"\" def __init__(self, msg=\"\"): OSError.__init__(self, msg) def", "msg) class InvalidTypeError(ValueError): \"\"\"Error raised when a parameter has the", "encountered an error.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self, msg) class DPFServerNullObject(Exception):", "gRPC exceptions and return a more succinct error message.\"\"\" @wraps(func)", "plotting. \"\"\" _FIELD_CONTAINER_PLOTTING_MSG = \"\"\"\" This fields_container contains multiple fields.", "exceptions.\"\"\" # Capture gRPC exceptions try: out = func(*args, **kwargs)", "if \"object is null in the dataBase\" in details: raise", "msg) class DPFServerNullObject(Exception): \"\"\"Error raised when the DPF server cannot", "parameter: \" + parameter_name + \".\" ) ValueError.__init__(self, msg) class", "msg) def protect_grpc(func): \"\"\"Capture gRPC exceptions and return a more", "+= str(version) msg += \" version (or above).\" RuntimeError.__init__(self, msg)", "wraps _COMPLEX_PLOTTING_ERROR_MSG = \"\"\" Complex fields cannot be plotted. Use", "at a time. Extract a field with ``fields_container[index]``. \"\"\" class", "when the Ansys verion is invalid.\"\"\" def __init__(self, msg=\"\"): RuntimeError.__init__(self,", "and return a more succinct error message.\"\"\" @wraps(func) def wrapper(*args,", "has the wrong type.\"\"\" def __init__(self, data_type, parameter_name): msg =", "in the dataBase\" in details: raise DPFServerNullObject(details) from None raise", "a defined sweeping phase before plotting. \"\"\" _FIELD_CONTAINER_PLOTTING_MSG = \"\"\"\"", "find an object.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self, msg) class InvalidPortError(OSError):", "msg=\"\"): RuntimeError.__init__(self, msg) class DPFServerException(Exception): \"\"\"Error raised when the DPF", "data.\"\"\" def __init__(self, msg=_COMPLEX_PLOTTING_ERROR_MSG): ValueError.__init__(self, msg) class FieldContainerPlottingError(ValueError): \"\"\"Error raised", "from None raise DPFServerException(details) from None return out return wrapper", "if msg is None: msg = \"Feature not supported. Upgrade", "features are not supported by the DPF gRPC server version.\"\"\"", "DPF error value must be defined.\"\"\" def __init__( self, msg=\"A", "def protect_grpc(func): \"\"\"Capture gRPC exceptions and return a more succinct", "time-step result can be plotted at a time. Extract a", "parameter has the wrong type.\"\"\" def __init__(self, data_type, parameter_name): msg", "This fields_container contains multiple fields. Only one time-step result can", "\"\"\"Error raised when the Ansys verion is invalid.\"\"\" def __init__(self,", "wrapper(*args, **kwargs): \"\"\"Capture gRPC exceptions.\"\"\" # Capture gRPC exceptions try:", "a more succinct error message.\"\"\" @wraps(func) def wrapper(*args, **kwargs): \"\"\"Capture", "specific DPF error value must be defined.\"\"\" def __init__( self,", "null in the dataBase\" in details: raise DPFServerNullObject(details) from None", "multiple fields. Only one time-step result can be plotted at", "+ \".\" ) ValueError.__init__(self, msg) class LocationError(ValueError): \"\"\"Error raised when", "def __init__(self, msg=\"\"): Exception.__init__(self, msg) class InvalidPortError(OSError): \"\"\"Error raised when", "the DPF server has encountered an error.\"\"\" def __init__(self, msg=\"\"):", "_InactiveRpcError, _MultiThreadedRendezvous from functools import wraps _COMPLEX_PLOTTING_ERROR_MSG = \"\"\" Complex", "__init__(self, data_type, parameter_name): msg = ( \"A \" + data_type", "class InvalidTypeError(ValueError): \"\"\"Error raised when a parameter has the wrong", "__init__(self, msg=_FIELD_CONTAINER_PLOTTING_MSG): ValueError.__init__(self, msg) class InvalidANSYSVersionError(RuntimeError): \"\"\"Error raised when the", "= \"\"\"\" This fields_container contains multiple fields. Only one time-step", "when the DPF server has encountered an error.\"\"\" def __init__(self,", "is null in the dataBase\" in details: raise DPFServerNullObject(details) from", "\" version (or above).\" RuntimeError.__init__(self, msg) class DpfValueError(ValueError): \"\"\"Error raised", "server has encountered an error.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self, msg)", "class InvalidPortError(OSError): \"\"\"Error raised when used an invalid port when", "plotted. Use operators to get the amplitude or the result", "used for the following parameter: \" + parameter_name + \".\"", "when a parameter has the wrong type.\"\"\" def __init__(self, data_type,", "attempting to plot a field with complex data.\"\"\" def __init__(self,", "the dpf-core/grpc-dpf python features are not supported by the DPF", "must be used for the following parameter: \" + parameter_name", "be used for the following parameter: \" + parameter_name +", "starting DPF.\"\"\" def __init__(self, msg=\"\"): OSError.__init__(self, msg) def protect_grpc(func): \"\"\"Capture", "gRPC exceptions.\"\"\" # Capture gRPC exceptions try: out = func(*args,", "raised when the DPF server has encountered an error.\"\"\" def", "the Ansys verion is invalid.\"\"\" def __init__(self, msg=\"\"): RuntimeError.__init__(self, msg)", "msg += \" version (or above).\" RuntimeError.__init__(self, msg) class DpfValueError(ValueError):", "msg=_FIELD_CONTAINER_PLOTTING_MSG): ValueError.__init__(self, msg) class InvalidANSYSVersionError(RuntimeError): \"\"\"Error raised when the Ansys", "more succinct error message.\"\"\" @wraps(func) def wrapper(*args, **kwargs): \"\"\"Capture gRPC", "\" msg += str(version) msg += \" version (or above).\"", "parameter_name + \".\" ) ValueError.__init__(self, msg) class LocationError(ValueError): \"\"\"Error raised", "to plot a field with complex data.\"\"\" def __init__(self, msg=_COMPLEX_PLOTTING_ERROR_MSG):", "\"\"\"Error raised when a specific DPF error value must be", "# Capture gRPC exceptions try: out = func(*args, **kwargs) except", "\"\"\"Error raised when attempting to plot a fields_container containing multiple", "functools import wraps _COMPLEX_PLOTTING_ERROR_MSG = \"\"\" Complex fields cannot be", "version (or above).\" RuntimeError.__init__(self, msg) class DpfValueError(ValueError): \"\"\"Error raised when", "Extract a field with ``fields_container[index]``. \"\"\" class DpfVersionNotSupported(RuntimeError): \"\"\"Error raised", "amplitude or the result at a defined sweeping phase before", "when attempting to plot a field with complex data.\"\"\" def", "DPF behavior.\" ): ValueError.__init__(self, msg) class InvalidTypeError(ValueError): \"\"\"Error raised when", "field with complex data.\"\"\" def __init__(self, msg=_COMPLEX_PLOTTING_ERROR_MSG): ValueError.__init__(self, msg) class", "phase before plotting. \"\"\" _FIELD_CONTAINER_PLOTTING_MSG = \"\"\"\" This fields_container contains", "error value must be defined.\"\"\" def __init__( self, msg=\"A value", "__init__(self, msg=\"Invalid location\"): ValueError.__init__(self, msg) class ComplexPlottingError(ValueError): \"\"\"Error raised when", "server cannot find an object.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self, msg)", "parameter_name): msg = ( \"A \" + data_type + \"", "return a more succinct error message.\"\"\" @wraps(func) def wrapper(*args, **kwargs):", "before plotting. \"\"\" _FIELD_CONTAINER_PLOTTING_MSG = \"\"\"\" This fields_container contains multiple", "\" + parameter_name + \".\" ) ValueError.__init__(self, msg) class LocationError(ValueError):", "to incorrect DPF behavior.\" ): ValueError.__init__(self, msg) class InvalidTypeError(ValueError): \"\"\"Error", "error.details() if \"object is null in the dataBase\" in details:", "when starting DPF.\"\"\" def __init__(self, msg=\"\"): OSError.__init__(self, msg) def protect_grpc(func):", "class DPFServerNullObject(Exception): \"\"\"Error raised when the DPF server cannot find", "DPF server has encountered an error.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self,", "gRPC exceptions try: out = func(*args, **kwargs) except (_InactiveRpcError, _MultiThreadedRendezvous)", "InvalidTypeError(ValueError): \"\"\"Error raised when a parameter has the wrong type.\"\"\"", "msg=\"Invalid location\"): ValueError.__init__(self, msg) class ComplexPlottingError(ValueError): \"\"\"Error raised when attempting", "None: msg = \"Feature not supported. Upgrade the server to", "data_type + \" must be used for the following parameter:", "msg) class LocationError(ValueError): \"\"\"Error raised when using an invalid location.\"\"\"", "a fields_container containing multiple fields.\"\"\" def __init__(self, msg=_FIELD_CONTAINER_PLOTTING_MSG): ValueError.__init__(self, msg)", "except (_InactiveRpcError, _MultiThreadedRendezvous) as error: details = error.details() if \"object", "exceptions try: out = func(*args, **kwargs) except (_InactiveRpcError, _MultiThreadedRendezvous) as", "object.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self, msg) class InvalidPortError(OSError): \"\"\"Error raised", "+ \" must be used for the following parameter: \"", "Exception.__init__(self, msg) class InvalidPortError(OSError): \"\"\"Error raised when used an invalid", "plot a field with complex data.\"\"\" def __init__(self, msg=_COMPLEX_PLOTTING_ERROR_MSG): ValueError.__init__(self,", "fields_container contains multiple fields. Only one time-step result can be", "( \"A \" + data_type + \" must be used", "has encountered an error.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self, msg) class", "fields_container containing multiple fields.\"\"\" def __init__(self, msg=_FIELD_CONTAINER_PLOTTING_MSG): ValueError.__init__(self, msg) class", "fields.\"\"\" def __init__(self, msg=_FIELD_CONTAINER_PLOTTING_MSG): ValueError.__init__(self, msg) class InvalidANSYSVersionError(RuntimeError): \"\"\"Error raised", "msg=\"\"): Exception.__init__(self, msg) class DPFServerNullObject(Exception): \"\"\"Error raised when the DPF", "**kwargs) except (_InactiveRpcError, _MultiThreadedRendezvous) as error: details = error.details() if", "msg=\"A value that has been set leads to incorrect DPF", "cannot find an object.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self, msg) class", "from functools import wraps _COMPLEX_PLOTTING_ERROR_MSG = \"\"\" Complex fields cannot", "plotted at a time. Extract a field with ``fields_container[index]``. \"\"\"", "behavior.\" ): ValueError.__init__(self, msg) class InvalidTypeError(ValueError): \"\"\"Error raised when a", "def __init__(self, msg=\"Invalid location\"): ValueError.__init__(self, msg) class ComplexPlottingError(ValueError): \"\"\"Error raised", "server version.\"\"\" def __init__(self, version, msg=None): if msg is None:", "ValueError.__init__(self, msg) class InvalidANSYSVersionError(RuntimeError): \"\"\"Error raised when the Ansys verion", "import wraps _COMPLEX_PLOTTING_ERROR_MSG = \"\"\" Complex fields cannot be plotted.", "be plotted at a time. Extract a field with ``fields_container[index]``.", "attempting to plot a fields_container containing multiple fields.\"\"\" def __init__(self,", "str(version) msg += \" version (or above).\" RuntimeError.__init__(self, msg) class", "the result at a defined sweeping phase before plotting. \"\"\"", "is invalid.\"\"\" def __init__(self, msg=\"\"): RuntimeError.__init__(self, msg) class DPFServerException(Exception): \"\"\"Error", "an error.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self, msg) class DPFServerNullObject(Exception): \"\"\"Error", "ValueError.__init__(self, msg) class InvalidTypeError(ValueError): \"\"\"Error raised when a parameter has", "__init__(self, msg=\"\"): Exception.__init__(self, msg) class DPFServerNullObject(Exception): \"\"\"Error raised when the", "class DpfVersionNotSupported(RuntimeError): \"\"\"Error raised when the dpf-core/grpc-dpf python features are", "a specific DPF error value must be defined.\"\"\" def __init__(", "multiple fields.\"\"\" def __init__(self, msg=_FIELD_CONTAINER_PLOTTING_MSG): ValueError.__init__(self, msg) class InvalidANSYSVersionError(RuntimeError): \"\"\"Error", "one time-step result can be plotted at a time. Extract", "fields. Only one time-step result can be plotted at a", "the DPF server cannot find an object.\"\"\" def __init__(self, msg=\"\"):", "grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous from functools import wraps _COMPLEX_PLOTTING_ERROR_MSG =", "\"\"\"Error raised when the DPF server has encountered an error.\"\"\"", "msg) class FieldContainerPlottingError(ValueError): \"\"\"Error raised when attempting to plot a", "raised when the DPF server cannot find an object.\"\"\" def", "= ( \"A \" + data_type + \" must be", "a parameter has the wrong type.\"\"\" def __init__(self, data_type, parameter_name):", "containing multiple fields.\"\"\" def __init__(self, msg=_FIELD_CONTAINER_PLOTTING_MSG): ValueError.__init__(self, msg) class InvalidANSYSVersionError(RuntimeError):", "class DPFServerException(Exception): \"\"\"Error raised when the DPF server has encountered", "with ``fields_container[index]``. \"\"\" class DpfVersionNotSupported(RuntimeError): \"\"\"Error raised when the dpf-core/grpc-dpf", "\".\" ) ValueError.__init__(self, msg) class LocationError(ValueError): \"\"\"Error raised when using", "an invalid port when starting DPF.\"\"\" def __init__(self, msg=\"\"): OSError.__init__(self,", "to \" msg += str(version) msg += \" version (or", "DpfVersionNotSupported(RuntimeError): \"\"\"Error raised when the dpf-core/grpc-dpf python features are not", "dataBase\" in details: raise DPFServerNullObject(details) from None raise DPFServerException(details) from", "invalid.\"\"\" def __init__(self, msg=\"\"): RuntimeError.__init__(self, msg) class DPFServerException(Exception): \"\"\"Error raised", "incorrect DPF behavior.\" ): ValueError.__init__(self, msg) class InvalidTypeError(ValueError): \"\"\"Error raised", "InvalidANSYSVersionError(RuntimeError): \"\"\"Error raised when the Ansys verion is invalid.\"\"\" def", "with complex data.\"\"\" def __init__(self, msg=_COMPLEX_PLOTTING_ERROR_MSG): ValueError.__init__(self, msg) class FieldContainerPlottingError(ValueError):", "+ data_type + \" must be used for the following", "DPFServerNullObject(details) from None raise DPFServerException(details) from None return out return", "\"\"\" Complex fields cannot be plotted. Use operators to get", "raised when the dpf-core/grpc-dpf python features are not supported by", "the wrong type.\"\"\" def __init__(self, data_type, parameter_name): msg = (", "gRPC server version.\"\"\" def __init__(self, version, msg=None): if msg is", "msg += str(version) msg += \" version (or above).\" RuntimeError.__init__(self,", "DPFServerException(Exception): \"\"\"Error raised when the DPF server has encountered an", "\" + data_type + \" must be used for the", "\"\"\"Capture gRPC exceptions and return a more succinct error message.\"\"\"", "\"\"\"Capture gRPC exceptions.\"\"\" # Capture gRPC exceptions try: out =", "used an invalid port when starting DPF.\"\"\" def __init__(self, msg=\"\"):", "= \"Feature not supported. Upgrade the server to \" msg", "self, msg=\"A value that has been set leads to incorrect", "__init__(self, msg=\"\"): OSError.__init__(self, msg) def protect_grpc(func): \"\"\"Capture gRPC exceptions and", "error: details = error.details() if \"object is null in the", "Exception.__init__(self, msg) class DPFServerNullObject(Exception): \"\"\"Error raised when the DPF server", "def __init__(self, msg=\"\"): OSError.__init__(self, msg) def protect_grpc(func): \"\"\"Capture gRPC exceptions", "\"\"\"Error raised when attempting to plot a field with complex", "raised when a parameter has the wrong type.\"\"\" def __init__(self,", "msg=_COMPLEX_PLOTTING_ERROR_MSG): ValueError.__init__(self, msg) class FieldContainerPlottingError(ValueError): \"\"\"Error raised when attempting to", "func(*args, **kwargs) except (_InactiveRpcError, _MultiThreadedRendezvous) as error: details = error.details()", "(or above).\" RuntimeError.__init__(self, msg) class DpfValueError(ValueError): \"\"\"Error raised when a", "ValueError.__init__(self, msg) class ComplexPlottingError(ValueError): \"\"\"Error raised when attempting to plot", "exceptions and return a more succinct error message.\"\"\" @wraps(func) def", "protect_grpc(func): \"\"\"Capture gRPC exceptions and return a more succinct error", "to get the amplitude or the result at a defined", "for the following parameter: \" + parameter_name + \".\" )", "by the DPF gRPC server version.\"\"\" def __init__(self, version, msg=None):", "= error.details() if \"object is null in the dataBase\" in", "import _InactiveRpcError, _MultiThreadedRendezvous from functools import wraps _COMPLEX_PLOTTING_ERROR_MSG = \"\"\"", "when the DPF server cannot find an object.\"\"\" def __init__(self,", "at a defined sweeping phase before plotting. \"\"\" _FIELD_CONTAINER_PLOTTING_MSG =", "value must be defined.\"\"\" def __init__( self, msg=\"A value that", "class FieldContainerPlottingError(ValueError): \"\"\"Error raised when attempting to plot a fields_container", "succinct error message.\"\"\" @wraps(func) def wrapper(*args, **kwargs): \"\"\"Capture gRPC exceptions.\"\"\"", "\"\"\"Error raised when the dpf-core/grpc-dpf python features are not supported", "class ComplexPlottingError(ValueError): \"\"\"Error raised when attempting to plot a field", "Use operators to get the amplitude or the result at", "fields cannot be plotted. Use operators to get the amplitude", "ValueError.__init__(self, msg) class FieldContainerPlottingError(ValueError): \"\"\"Error raised when attempting to plot", "is None: msg = \"Feature not supported. Upgrade the server", "when used an invalid port when starting DPF.\"\"\" def __init__(self,", "raised when attempting to plot a fields_container containing multiple fields.\"\"\"", "the server to \" msg += str(version) msg += \"", "the DPF gRPC server version.\"\"\" def __init__(self, version, msg=None): if", "\"\"\"\" This fields_container contains multiple fields. Only one time-step result", "dpf-core/grpc-dpf python features are not supported by the DPF gRPC", "Capture gRPC exceptions try: out = func(*args, **kwargs) except (_InactiveRpcError,", "invalid location.\"\"\" def __init__(self, msg=\"Invalid location\"): ValueError.__init__(self, msg) class ComplexPlottingError(ValueError):", "result at a defined sweeping phase before plotting. \"\"\" _FIELD_CONTAINER_PLOTTING_MSG", "__init__( self, msg=\"A value that has been set leads to", "msg=\"\"): OSError.__init__(self, msg) def protect_grpc(func): \"\"\"Capture gRPC exceptions and return", "\"\"\" class DpfVersionNotSupported(RuntimeError): \"\"\"Error raised when the dpf-core/grpc-dpf python features", "version, msg=None): if msg is None: msg = \"Feature not", "msg=\"\"): Exception.__init__(self, msg) class InvalidPortError(OSError): \"\"\"Error raised when used an", "\"\"\"Error raised when using an invalid location.\"\"\" def __init__(self, msg=\"Invalid", "has been set leads to incorrect DPF behavior.\" ): ValueError.__init__(self,", "__init__(self, version, msg=None): if msg is None: msg = \"Feature", "_FIELD_CONTAINER_PLOTTING_MSG = \"\"\"\" This fields_container contains multiple fields. Only one", "\"\"\"Error raised when used an invalid port when starting DPF.\"\"\"", "raised when used an invalid port when starting DPF.\"\"\" def", "are not supported by the DPF gRPC server version.\"\"\" def", "value that has been set leads to incorrect DPF behavior.\"", "been set leads to incorrect DPF behavior.\" ): ValueError.__init__(self, msg)", "be defined.\"\"\" def __init__( self, msg=\"A value that has been", "can be plotted at a time. Extract a field with", "server to \" msg += str(version) msg += \" version", "error message.\"\"\" @wraps(func) def wrapper(*args, **kwargs): \"\"\"Capture gRPC exceptions.\"\"\" #", "Only one time-step result can be plotted at a time.", "supported by the DPF gRPC server version.\"\"\" def __init__(self, version,", "using an invalid location.\"\"\" def __init__(self, msg=\"Invalid location\"): ValueError.__init__(self, msg)", "RuntimeError.__init__(self, msg) class DpfValueError(ValueError): \"\"\"Error raised when a specific DPF", "Complex fields cannot be plotted. Use operators to get the", "that has been set leads to incorrect DPF behavior.\" ):", "msg) class InvalidPortError(OSError): \"\"\"Error raised when used an invalid port", "msg) class DpfValueError(ValueError): \"\"\"Error raised when a specific DPF error", "from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous from functools import wraps _COMPLEX_PLOTTING_ERROR_MSG", "msg) class ComplexPlottingError(ValueError): \"\"\"Error raised when attempting to plot a", "DPF server cannot find an object.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self,", "location.\"\"\" def __init__(self, msg=\"Invalid location\"): ValueError.__init__(self, msg) class ComplexPlottingError(ValueError): \"\"\"Error", "LocationError(ValueError): \"\"\"Error raised when using an invalid location.\"\"\" def __init__(self,", "message.\"\"\" @wraps(func) def wrapper(*args, **kwargs): \"\"\"Capture gRPC exceptions.\"\"\" # Capture", "_MultiThreadedRendezvous) as error: details = error.details() if \"object is null", "DPF gRPC server version.\"\"\" def __init__(self, version, msg=None): if msg", "wrong type.\"\"\" def __init__(self, data_type, parameter_name): msg = ( \"A", "the amplitude or the result at a defined sweeping phase", "a field with ``fields_container[index]``. \"\"\" class DpfVersionNotSupported(RuntimeError): \"\"\"Error raised when", "set leads to incorrect DPF behavior.\" ): ValueError.__init__(self, msg) class", "when attempting to plot a fields_container containing multiple fields.\"\"\" def", "class LocationError(ValueError): \"\"\"Error raised when using an invalid location.\"\"\" def", "time. Extract a field with ``fields_container[index]``. \"\"\" class DpfVersionNotSupported(RuntimeError): \"\"\"Error", "when the dpf-core/grpc-dpf python features are not supported by the", "Ansys verion is invalid.\"\"\" def __init__(self, msg=\"\"): RuntimeError.__init__(self, msg) class", "must be defined.\"\"\" def __init__( self, msg=\"A value that has", "DPF.\"\"\" def __init__(self, msg=\"\"): OSError.__init__(self, msg) def protect_grpc(func): \"\"\"Capture gRPC", "msg = \"Feature not supported. Upgrade the server to \"", "_MultiThreadedRendezvous from functools import wraps _COMPLEX_PLOTTING_ERROR_MSG = \"\"\" Complex fields", "def __init__(self, version, msg=None): if msg is None: msg =", "field with ``fields_container[index]``. \"\"\" class DpfVersionNotSupported(RuntimeError): \"\"\"Error raised when the", "above).\" RuntimeError.__init__(self, msg) class DpfValueError(ValueError): \"\"\"Error raised when a specific", "complex data.\"\"\" def __init__(self, msg=_COMPLEX_PLOTTING_ERROR_MSG): ValueError.__init__(self, msg) class FieldContainerPlottingError(ValueError): \"\"\"Error", "= func(*args, **kwargs) except (_InactiveRpcError, _MultiThreadedRendezvous) as error: details =", "msg is None: msg = \"Feature not supported. Upgrade the", "when using an invalid location.\"\"\" def __init__(self, msg=\"Invalid location\"): ValueError.__init__(self,", "+ parameter_name + \".\" ) ValueError.__init__(self, msg) class LocationError(ValueError): \"\"\"Error", "def __init__(self, msg=_COMPLEX_PLOTTING_ERROR_MSG): ValueError.__init__(self, msg) class FieldContainerPlottingError(ValueError): \"\"\"Error raised when", "FieldContainerPlottingError(ValueError): \"\"\"Error raised when attempting to plot a fields_container containing", "__init__(self, msg=\"\"): RuntimeError.__init__(self, msg) class DPFServerException(Exception): \"\"\"Error raised when the", "ValueError.__init__(self, msg) class LocationError(ValueError): \"\"\"Error raised when using an invalid", "result can be plotted at a time. Extract a field", "``fields_container[index]``. \"\"\" class DpfVersionNotSupported(RuntimeError): \"\"\"Error raised when the dpf-core/grpc-dpf python", "data_type, parameter_name): msg = ( \"A \" + data_type +", "not supported by the DPF gRPC server version.\"\"\" def __init__(self,", "contains multiple fields. Only one time-step result can be plotted", "a time. Extract a field with ``fields_container[index]``. \"\"\" class DpfVersionNotSupported(RuntimeError):", "RuntimeError.__init__(self, msg) class DPFServerException(Exception): \"\"\"Error raised when the DPF server", "\"\"\" _FIELD_CONTAINER_PLOTTING_MSG = \"\"\"\" This fields_container contains multiple fields. Only", "(_InactiveRpcError, _MultiThreadedRendezvous) as error: details = error.details() if \"object is", "def __init__(self, msg=\"\"): RuntimeError.__init__(self, msg) class DPFServerException(Exception): \"\"\"Error raised when", "raised when using an invalid location.\"\"\" def __init__(self, msg=\"Invalid location\"):", "get the amplitude or the result at a defined sweeping", "= \"\"\" Complex fields cannot be plotted. Use operators to", "raise DPFServerNullObject(details) from None raise DPFServerException(details) from None return out", "try: out = func(*args, **kwargs) except (_InactiveRpcError, _MultiThreadedRendezvous) as error:", "msg) class DPFServerException(Exception): \"\"\"Error raised when the DPF server has", "details: raise DPFServerNullObject(details) from None raise DPFServerException(details) from None return", "\"A \" + data_type + \" must be used for", "the following parameter: \" + parameter_name + \".\" ) ValueError.__init__(self,", "+= \" version (or above).\" RuntimeError.__init__(self, msg) class DpfValueError(ValueError): \"\"\"Error", "leads to incorrect DPF behavior.\" ): ValueError.__init__(self, msg) class InvalidTypeError(ValueError):", "raised when the Ansys verion is invalid.\"\"\" def __init__(self, msg=\"\"):", "sweeping phase before plotting. \"\"\" _FIELD_CONTAINER_PLOTTING_MSG = \"\"\"\" This fields_container", "msg) class InvalidANSYSVersionError(RuntimeError): \"\"\"Error raised when the Ansys verion is", "error.\"\"\" def __init__(self, msg=\"\"): Exception.__init__(self, msg) class DPFServerNullObject(Exception): \"\"\"Error raised", "cannot be plotted. Use operators to get the amplitude or", "not supported. Upgrade the server to \" msg += str(version)", "or the result at a defined sweeping phase before plotting.", "\"object is null in the dataBase\" in details: raise DPFServerNullObject(details)", "DpfValueError(ValueError): \"\"\"Error raised when a specific DPF error value must", "location\"): ValueError.__init__(self, msg) class ComplexPlottingError(ValueError): \"\"\"Error raised when attempting to", "OSError.__init__(self, msg) def protect_grpc(func): \"\"\"Capture gRPC exceptions and return a", "supported. Upgrade the server to \" msg += str(version) msg", "raised when a specific DPF error value must be defined.\"\"\"", "def __init__( self, msg=\"A value that has been set leads", "\"Feature not supported. Upgrade the server to \" msg +=", "plot a fields_container containing multiple fields.\"\"\" def __init__(self, msg=_FIELD_CONTAINER_PLOTTING_MSG): ValueError.__init__(self,", "version.\"\"\" def __init__(self, version, msg=None): if msg is None: msg", "following parameter: \" + parameter_name + \".\" ) ValueError.__init__(self, msg)", "def wrapper(*args, **kwargs): \"\"\"Capture gRPC exceptions.\"\"\" # Capture gRPC exceptions" ]
[ "0.4: # both speakers are under 40% error rate- likely", "\")[ 2]) < 0.4: # both speakers are under 40%", "in [ranges1, ranges2]: final_file.write(\"\\n\\n\") for r in ranges: for s", "s)) hyp = \" \".join(iframe['Hyp']['text']) ref = \" \".join(iframe['Ref']['text']) wer", "\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASRgood_ranges.text\", \"w\") continue if float(l.strip('\\n').split(\" \")[ 2]) < 0.4: #", "on the results, output the 'good' ASR results results =", "no_ho = 0 file.close() file = open( \"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASRgood_ranges.text\", \"w\") continue", "import open_intervalframe_from_textgrid import numpy from deep_disfluency.utils.accuracy import wer final_file =", "no_ho = 0 no_test = 0 ingood = True file", "results results = open(\"wer_test.text\") no_ho = 0 no_test = 0", "40% error rate- likely half decent separation # print l", "#file.write(l.strip('\\n').split(\" \")[0]+l.strip('\\n').split(\" \")[1]+\"\\n\") file.write(l.strip('\\n').split(\" \")[0] + \"\\n\") ingood = True", "for s in [\"A\", \"B\"]: iframe = open_intervalframe_from_textgrid(\"{0}{1}.TextGrid\" .format(r, s))", "0 ingood = True file = open(\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASRgood_ranges.text\", \"w\") for l", "if l == \"\\n\": print no_ho no_ho = 0 file.close()", "== \"\\n\": print no_ho no_ho = 0 file.close() file =", "file.write(l.strip('\\n').split(\" \")[0] + \"\\n\") ingood = True else: ingood =", "ASR results results = open(\"wer_test.text\") no_ho = 0 no_test =", "l == \"\\n\": print no_ho no_ho = 0 file.close() file", "for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASR_ranges.text\")] for ranges in [ranges1, ranges2]:", "for ranges in [ranges1, ranges2]: final_file.write(\"\\n\\n\") for r in ranges:", "+ \"\\n\") ingood = True else: ingood = False print", "= 0 no_test = 0 ingood = True file =", "under 40% error rate- likely half decent separation # print", "# Based on the results, output the 'good' ASR results", "hyp, macro=True) print r, s, wer print>>final_file, r, s, wer,", "wer, cost final_file.close() # Based on the results, output the", "ingood = True file = open(\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASRgood_ranges.text\", \"w\") for l in", "numpy from deep_disfluency.utils.accuracy import wer final_file = open('wer_test.text', \"w\") ranges1", "l.strip(\"\\n\").split(\" \")[1]: no_ho += 1 #file.write(l.strip('\\n').split(\" \")[0]+l.strip('\\n').split(\" \")[1]+\"\\n\") file.write(l.strip('\\n').split(\" \")[0]", "= 0 file.close() file = open( \"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASRgood_ranges.text\", \"w\") continue if", "ingood = True else: ingood = False print no_ho results.close()", "open_intervalframe_from_textgrid(\"{0}{1}.TextGrid\" .format(r, s)) hyp = \" \".join(iframe['Hyp']['text']) ref = \"", "from mumodo.mumodoIO import open_intervalframe_from_textgrid import numpy from deep_disfluency.utils.accuracy import wer", "\")[0]+l.strip('\\n').split(\" \")[1]+\"\\n\") file.write(l.strip('\\n').split(\" \")[0] + \"\\n\") ingood = True else:", "import wer final_file = open('wer_test.text', \"w\") ranges1 = [line.strip() for", "[\"A\", \"B\"]: iframe = open_intervalframe_from_textgrid(\"{0}{1}.TextGrid\" .format(r, s)) hyp = \"", "open_intervalframe_from_textgrid import numpy from deep_disfluency.utils.accuracy import wer final_file = open('wer_test.text',", "open(\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASRgood_ranges.text\", \"w\") for l in results: # print l if", "= True else: ingood = False print no_ho results.close() file.close()", "Based on the results, output the 'good' ASR results results", "= open( \"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASRgood_ranges.text\", \"w\") continue if float(l.strip('\\n').split(\" \")[ 2]) <", "continue if float(l.strip('\\n').split(\" \")[ 2]) < 0.4: # both speakers", "no_test = 0 ingood = True file = open(\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASRgood_ranges.text\", \"w\")", "if float(l.strip('\\n').split(\" \")[ 2]) < 0.4: # both speakers are", "\"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASR_ranges.text\")] ranges2 = [line.strip() for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASR_ranges.text\")] for", "speakers are under 40% error rate- likely half decent separation", "ref = \" \".join(iframe['Ref']['text']) wer = wer(ref, hyp) cost =", "\"w\") continue if float(l.strip('\\n').split(\" \")[ 2]) < 0.4: # both", "the 'good' ASR results results = open(\"wer_test.text\") no_ho = 0", "\"\\n\": print no_ho no_ho = 0 file.close() file = open(", "in l.strip(\"\\n\").split(\" \")[1]: no_ho += 1 #file.write(l.strip('\\n').split(\" \")[0]+l.strip('\\n').split(\" \")[1]+\"\\n\") file.write(l.strip('\\n').split(\"", "+= 1 #file.write(l.strip('\\n').split(\" \")[0]+l.strip('\\n').split(\" \")[1]+\"\\n\") file.write(l.strip('\\n').split(\" \")[0] + \"\\n\") ingood", "deep_disfluency.utils.accuracy import wer final_file = open('wer_test.text', \"w\") ranges1 = [line.strip()", "wer final_file = open('wer_test.text', \"w\") ranges1 = [line.strip() for line", "in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASR_ranges.text\")] for ranges in [ranges1, ranges2]: final_file.write(\"\\n\\n\") for", "file = open(\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASRgood_ranges.text\", \"w\") for l in results: # print", "r in ranges: for s in [\"A\", \"B\"]: iframe =", "file = open( \"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASRgood_ranges.text\", \"w\") continue if float(l.strip('\\n').split(\" \")[ 2])", "macro=True) print r, s, wer print>>final_file, r, s, wer, cost", "ranges: for s in [\"A\", \"B\"]: iframe = open_intervalframe_from_textgrid(\"{0}{1}.TextGrid\" .format(r,", "\")[0] + \"\\n\") ingood = True else: ingood = False", "iframe = open_intervalframe_from_textgrid(\"{0}{1}.TextGrid\" .format(r, s)) hyp = \" \".join(iframe['Hyp']['text']) ref", "final_file.close() # Based on the results, output the 'good' ASR", "[line.strip() for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASR_ranges.text\")] ranges2 = [line.strip() for", "wer(ref, hyp) cost = wer(ref, hyp, macro=True) print r, s,", "ranges in [ranges1, ranges2]: final_file.write(\"\\n\\n\") for r in ranges: for", "and \"B\" in l.strip(\"\\n\").split(\" \")[1]: no_ho += 1 #file.write(l.strip('\\n').split(\" \")[0]+l.strip('\\n').split(\"", "hyp = \" \".join(iframe['Hyp']['text']) ref = \" \".join(iframe['Ref']['text']) wer =", "print>>final_file, r, s, wer, cost final_file.close() # Based on the", "wer = wer(ref, hyp) cost = wer(ref, hyp, macro=True) print", "ingood and \"B\" in l.strip(\"\\n\").split(\" \")[1]: no_ho += 1 #file.write(l.strip('\\n').split(\"", "print r, s, wer print>>final_file, r, s, wer, cost final_file.close()", "\".join(iframe['Ref']['text']) wer = wer(ref, hyp) cost = wer(ref, hyp, macro=True)", "rate- likely half decent separation # print l if ingood", "open('wer_test.text', \"w\") ranges1 = [line.strip() for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASR_ranges.text\")]", "= wer(ref, hyp, macro=True) print r, s, wer print>>final_file, r,", "results: # print l if l == \"\\n\": print no_ho", "l in results: # print l if l == \"\\n\":", "print no_ho no_ho = 0 file.close() file = open( \"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASRgood_ranges.text\",", ".format(r, s)) hyp = \" \".join(iframe['Hyp']['text']) ref = \" \".join(iframe['Ref']['text'])", "[line.strip() for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASR_ranges.text\")] for ranges in [ranges1,", "open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASR_ranges.text\")] for ranges in [ranges1, ranges2]: final_file.write(\"\\n\\n\") for r", "r, s, wer print>>final_file, r, s, wer, cost final_file.close() #", "mumodo.mumodoIO import open_intervalframe_from_textgrid import numpy from deep_disfluency.utils.accuracy import wer final_file", "True file = open(\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASRgood_ranges.text\", \"w\") for l in results: #", "\"w\") ranges1 = [line.strip() for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASR_ranges.text\")] ranges2", "hyp) cost = wer(ref, hyp, macro=True) print r, s, wer", "both speakers are under 40% error rate- likely half decent", "ranges2]: final_file.write(\"\\n\\n\") for r in ranges: for s in [\"A\",", "\"B\"]: iframe = open_intervalframe_from_textgrid(\"{0}{1}.TextGrid\" .format(r, s)) hyp = \" \".join(iframe['Hyp']['text'])", "error rate- likely half decent separation # print l if", "2]) < 0.4: # both speakers are under 40% error", "0 no_test = 0 ingood = True file = open(\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASRgood_ranges.text\",", "in ranges: for s in [\"A\", \"B\"]: iframe = open_intervalframe_from_textgrid(\"{0}{1}.TextGrid\"", "print l if ingood and \"B\" in l.strip(\"\\n\").split(\" \")[1]: no_ho", "\"B\" in l.strip(\"\\n\").split(\" \")[1]: no_ho += 1 #file.write(l.strip('\\n').split(\" \")[0]+l.strip('\\n').split(\" \")[1]+\"\\n\")", "= True file = open(\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASRgood_ranges.text\", \"w\") for l in results:", "\"w\") for l in results: # print l if l", "= [line.strip() for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASR_ranges.text\")] ranges2 = [line.strip()", "for l in results: # print l if l ==", "s, wer print>>final_file, r, s, wer, cost final_file.close() # Based", "open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASR_ranges.text\")] ranges2 = [line.strip() for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASR_ranges.text\")]", "\")[1]: no_ho += 1 #file.write(l.strip('\\n').split(\" \")[0]+l.strip('\\n').split(\" \")[1]+\"\\n\") file.write(l.strip('\\n').split(\" \")[0] +", "import numpy from deep_disfluency.utils.accuracy import wer final_file = open('wer_test.text', \"w\")", "wer(ref, hyp, macro=True) print r, s, wer print>>final_file, r, s,", "no_ho no_ho = 0 file.close() file = open( \"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASRgood_ranges.text\", \"w\")", "final_file.write(\"\\n\\n\") for r in ranges: for s in [\"A\", \"B\"]:", "= open(\"wer_test.text\") no_ho = 0 no_test = 0 ingood =", "results, output the 'good' ASR results results = open(\"wer_test.text\") no_ho", "ranges1 = [line.strip() for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASR_ranges.text\")] ranges2 =", "open( \"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASRgood_ranges.text\", \"w\") continue if float(l.strip('\\n').split(\" \")[ 2]) < 0.4:", "\")[1]+\"\\n\") file.write(l.strip('\\n').split(\" \")[0] + \"\\n\") ingood = True else: ingood", "\" \".join(iframe['Hyp']['text']) ref = \" \".join(iframe['Ref']['text']) wer = wer(ref, hyp)", "\".join(iframe['Hyp']['text']) ref = \" \".join(iframe['Ref']['text']) wer = wer(ref, hyp) cost", "float(l.strip('\\n').split(\" \")[ 2]) < 0.4: # both speakers are under", "# print l if ingood and \"B\" in l.strip(\"\\n\").split(\" \")[1]:", "results = open(\"wer_test.text\") no_ho = 0 no_test = 0 ingood", "no_ho += 1 #file.write(l.strip('\\n').split(\" \")[0]+l.strip('\\n').split(\" \")[1]+\"\\n\") file.write(l.strip('\\n').split(\" \")[0] + \"\\n\")", "\" \".join(iframe['Ref']['text']) wer = wer(ref, hyp) cost = wer(ref, hyp,", "decent separation # print l if ingood and \"B\" in", "file.close() file = open( \"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASRgood_ranges.text\", \"w\") continue if float(l.strip('\\n').split(\" \")[", "= [line.strip() for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASR_ranges.text\")] for ranges in", "= wer(ref, hyp) cost = wer(ref, hyp, macro=True) print r,", "ranges2 = [line.strip() for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASR_ranges.text\")] for ranges", "open(\"wer_test.text\") no_ho = 0 no_test = 0 ingood = True", "cost = wer(ref, hyp, macro=True) print r, s, wer print>>final_file,", "[ranges1, ranges2]: final_file.write(\"\\n\\n\") for r in ranges: for s in", "'good' ASR results results = open(\"wer_test.text\") no_ho = 0 no_test", "output the 'good' ASR results results = open(\"wer_test.text\") no_ho =", "= open(\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASRgood_ranges.text\", \"w\") for l in results: # print l", "= 0 ingood = True file = open(\"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASRgood_ranges.text\", \"w\") for", "for line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASR_ranges.text\")] ranges2 = [line.strip() for line", "in results: # print l if l == \"\\n\": print", "print l if l == \"\\n\": print no_ho no_ho =", "l if l == \"\\n\": print no_ho no_ho = 0", "= open_intervalframe_from_textgrid(\"{0}{1}.TextGrid\" .format(r, s)) hyp = \" \".join(iframe['Hyp']['text']) ref =", "are under 40% error rate- likely half decent separation #", "if ingood and \"B\" in l.strip(\"\\n\").split(\" \")[1]: no_ho += 1", "in [\"A\", \"B\"]: iframe = open_intervalframe_from_textgrid(\"{0}{1}.TextGrid\" .format(r, s)) hyp =", "in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASR_ranges.text\")] ranges2 = [line.strip() for line in open(", "< 0.4: # both speakers are under 40% error rate-", "s, wer, cost final_file.close() # Based on the results, output", "half decent separation # print l if ingood and \"B\"", "1 #file.write(l.strip('\\n').split(\" \")[0]+l.strip('\\n').split(\" \")[1]+\"\\n\") file.write(l.strip('\\n').split(\" \")[0] + \"\\n\") ingood =", "line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASR_ranges.text\")] for ranges in [ranges1, ranges2]: final_file.write(\"\\n\\n\")", "likely half decent separation # print l if ingood and", "separation # print l if ingood and \"B\" in l.strip(\"\\n\").split(\"", "line in open( \"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfHeldoutASR_ranges.text\")] ranges2 = [line.strip() for line in", "# both speakers are under 40% error rate- likely half", "= \" \".join(iframe['Hyp']['text']) ref = \" \".join(iframe['Ref']['text']) wer = wer(ref,", "# print l if l == \"\\n\": print no_ho no_ho", "\"\\n\") ingood = True else: ingood = False print no_ho", "= open('wer_test.text', \"w\") ranges1 = [line.strip() for line in open(", "final_file = open('wer_test.text', \"w\") ranges1 = [line.strip() for line in", "\"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASR_ranges.text\")] for ranges in [ranges1, ranges2]: final_file.write(\"\\n\\n\") for r in", "for r in ranges: for s in [\"A\", \"B\"]: iframe", "0 file.close() file = open( \"../../../simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detection/SWDisfTestASRgood_ranges.text\", \"w\") continue if float(l.strip('\\n').split(\"", "s in [\"A\", \"B\"]: iframe = open_intervalframe_from_textgrid(\"{0}{1}.TextGrid\" .format(r, s)) hyp", "the results, output the 'good' ASR results results = open(\"wer_test.text\")", "r, s, wer, cost final_file.close() # Based on the results,", "cost final_file.close() # Based on the results, output the 'good'", "l if ingood and \"B\" in l.strip(\"\\n\").split(\" \")[1]: no_ho +=", "= \" \".join(iframe['Ref']['text']) wer = wer(ref, hyp) cost = wer(ref,", "from deep_disfluency.utils.accuracy import wer final_file = open('wer_test.text', \"w\") ranges1 =", "wer print>>final_file, r, s, wer, cost final_file.close() # Based on" ]
[ "MessageInfo: \"\"\"Important things in the message\"\"\" user_id: int chat_id: int", "List from typing import Optional from typing import Tuple @dataclass", "{self.db_id=} {self.topics=}\" @dataclass class StagedFunction: \"\"\"For FunctionStagingArea\"\"\" fn: Callable[..., Any]", "the DB\"\"\" feed: bool # if false, the bot will", "@dataclass class StagedFunction: \"\"\"For FunctionStagingArea\"\"\" fn: Callable[..., Any] args: Optional[Tuple[Any,", "by the user\"\"\" user_id: int command: str insert_time: int =", "= field(default_factory=lambda: []) def __repr__(self) -> str: return f\"{self.user_id=} {self.feed=}", "command sent by the user\"\"\" user_id: int command: str insert_time:", "field(default_factory=lambda: []) def __repr__(self) -> str: return f\"{self.user_id=} {self.feed=} {self.db_id=}", "\"\"\"Deals with the commands the user is currently sending\"\"\" user_id:", "bot will not send any news feeds on a daily", "typing import List from typing import Optional from typing import", "{self.topics=}\" @dataclass class StagedFunction: \"\"\"For FunctionStagingArea\"\"\" fn: Callable[..., Any] args:", "from dataclasses import field from time import time from typing", "class UserCommand: \"\"\"Stores the latest command sent by the user\"\"\"", "the commands the user is currently sending\"\"\" user_id: int chat_id:", "the user is currently sending\"\"\" user_id: int chat_id: int command:", "List[str] = field(default_factory=lambda: []) def __repr__(self) -> str: return f\"{self.user_id=}", "int(time()) # for garbage collection def __repr__(self) -> str: return", "-> str: return f\"{self.user_id=} {self.command=}\" @dataclass class UserCommand: \"\"\"Stores the", "f\"{self.user_id=} {self.command=}\" @dataclass class UserCommand: \"\"\"Stores the latest command sent", "str insert_time: int = int(time()) # for garbage collection def", "@dataclass class MessageInfo: \"\"\"Important things in the message\"\"\" user_id: int", "-> str: return f\"{self.user_id=} {self.feed=} {self.db_id=} {self.topics=}\" @dataclass class StagedFunction:", "message_id: int text: str def __repr__(self) -> str: return f\"{self.user_id=}", "int command: str def __repr__(self) -> str: return f\"{self.user_id=} {self.command=}\"", "class NewUser: \"\"\"Deals with the commands the user is currently", "class StagedFunction: \"\"\"For FunctionStagingArea\"\"\" fn: Callable[..., Any] args: Optional[Tuple[Any, ...]]", "__repr__(self) -> str: return f\"{self.user_id=} {self.command=} {self.insert_time=}\" @dataclass class MessageInfo:", "str: return f\"{self.user_id=} {self.feed=} {self.db_id=} {self.topics=}\" @dataclass class StagedFunction: \"\"\"For", "command: str insert_time: int = int(time()) # for garbage collection", "user_id: int chat_id: int message_id: int text: str def __repr__(self)", "Dict from typing import List from typing import Optional from", "sending\"\"\" user_id: int chat_id: int command: str def __repr__(self) ->", "Tuple @dataclass class NewUser: \"\"\"Deals with the commands the user", "\"\"\"Stores the latest command sent by the user\"\"\" user_id: int", "about the user from the DB\"\"\" feed: bool # if", "int = int(time()) # for garbage collection def __repr__(self) ->", "dataclasses import field from time import time from typing import", "import Callable from typing import Dict from typing import List", "str: return f\"{self.user_id=} {self.chat_id=} {self.message_id=} {self.text=}\" @dataclass class UserDBInfo: \"\"\"Info", "from typing import Callable from typing import Dict from typing", "the latest command sent by the user\"\"\" user_id: int command:", "time from typing import Any from typing import Callable from", "{self.chat_id=} {self.message_id=} {self.text=}\" @dataclass class UserDBInfo: \"\"\"Info about the user", "{self.text=}\" @dataclass class UserDBInfo: \"\"\"Info about the user from the", "FunctionStagingArea\"\"\" fn: Callable[..., Any] args: Optional[Tuple[Any, ...]] = None kwargs:", "int topics: List[str] = field(default_factory=lambda: []) def __repr__(self) -> str:", "# if false, the bot will not send any news", "dataclasses import dataclass from dataclasses import field from time import", "from typing import Dict from typing import List from typing", "typing import Callable from typing import Dict from typing import", "int message_id: int text: str def __repr__(self) -> str: return", "f\"{self.user_id=} {self.feed=} {self.db_id=} {self.topics=}\" @dataclass class StagedFunction: \"\"\"For FunctionStagingArea\"\"\" fn:", "time import time from typing import Any from typing import", "import Any from typing import Callable from typing import Dict", "the user\"\"\" user_id: int command: str insert_time: int = int(time())", "Any] args: Optional[Tuple[Any, ...]] = None kwargs: Optional[Dict[str, Any]] =", "int chat_id: int message_id: int text: str def __repr__(self) ->", "commands the user is currently sending\"\"\" user_id: int chat_id: int", "str def __repr__(self) -> str: return f\"{self.user_id=} {self.command=}\" @dataclass class", "bool # if false, the bot will not send any", "return f\"{self.user_id=} {self.command=}\" @dataclass class UserCommand: \"\"\"Stores the latest command", "str def __repr__(self) -> str: return f\"{self.user_id=} {self.chat_id=} {self.message_id=} {self.text=}\"", "the message\"\"\" user_id: int chat_id: int message_id: int text: str", "args: Optional[Tuple[Any, ...]] = None kwargs: Optional[Dict[str, Any]] = None", "command: str def __repr__(self) -> str: return f\"{self.user_id=} {self.command=}\" @dataclass", "int db_id: int topics: List[str] = field(default_factory=lambda: []) def __repr__(self)", "send any news feeds on a daily basis user_id: int", "news feeds on a daily basis user_id: int db_id: int", "user is currently sending\"\"\" user_id: int chat_id: int command: str", "UserDBInfo: \"\"\"Info about the user from the DB\"\"\" feed: bool", "int text: str def __repr__(self) -> str: return f\"{self.user_id=} {self.chat_id=}", "{self.message_id=} {self.text=}\" @dataclass class UserDBInfo: \"\"\"Info about the user from", "from typing import Optional from typing import Tuple @dataclass class", "collection def __repr__(self) -> str: return f\"{self.user_id=} {self.command=} {self.insert_time=}\" @dataclass", "basis user_id: int db_id: int topics: List[str] = field(default_factory=lambda: [])", "Optional from typing import Tuple @dataclass class NewUser: \"\"\"Deals with", "topics: List[str] = field(default_factory=lambda: []) def __repr__(self) -> str: return", "for garbage collection def __repr__(self) -> str: return f\"{self.user_id=} {self.command=}", "Any from typing import Callable from typing import Dict from", "import Dict from typing import List from typing import Optional", "field from time import time from typing import Any from", "int command: str insert_time: int = int(time()) # for garbage", "typing import Tuple @dataclass class NewUser: \"\"\"Deals with the commands", "user from the DB\"\"\" feed: bool # if false, the", "StagedFunction: \"\"\"For FunctionStagingArea\"\"\" fn: Callable[..., Any] args: Optional[Tuple[Any, ...]] =", "user_id: int command: str insert_time: int = int(time()) # for", "\"\"\"For FunctionStagingArea\"\"\" fn: Callable[..., Any] args: Optional[Tuple[Any, ...]] = None", "message\"\"\" user_id: int chat_id: int message_id: int text: str def", "any news feeds on a daily basis user_id: int db_id:", "{self.feed=} {self.db_id=} {self.topics=}\" @dataclass class StagedFunction: \"\"\"For FunctionStagingArea\"\"\" fn: Callable[...,", "def __repr__(self) -> str: return f\"{self.user_id=} {self.feed=} {self.db_id=} {self.topics=}\" @dataclass", "return f\"{self.user_id=} {self.command=} {self.insert_time=}\" @dataclass class MessageInfo: \"\"\"Important things in", "def __repr__(self) -> str: return f\"{self.user_id=} {self.command=} {self.insert_time=}\" @dataclass class", "f\"{self.user_id=} {self.chat_id=} {self.message_id=} {self.text=}\" @dataclass class UserDBInfo: \"\"\"Info about the", "dataclass from dataclasses import field from time import time from", "__repr__(self) -> str: return f\"{self.user_id=} {self.feed=} {self.db_id=} {self.topics=}\" @dataclass class", "from typing import Any from typing import Callable from typing", "-> str: return f\"{self.user_id=} {self.chat_id=} {self.message_id=} {self.text=}\" @dataclass class UserDBInfo:", "with the commands the user is currently sending\"\"\" user_id: int", "the bot will not send any news feeds on a", "{self.insert_time=}\" @dataclass class MessageInfo: \"\"\"Important things in the message\"\"\" user_id:", "will not send any news feeds on a daily basis", "[]) def __repr__(self) -> str: return f\"{self.user_id=} {self.feed=} {self.db_id=} {self.topics=}\"", "garbage collection def __repr__(self) -> str: return f\"{self.user_id=} {self.command=} {self.insert_time=}\"", "from dataclasses import dataclass from dataclasses import field from time", "chat_id: int message_id: int text: str def __repr__(self) -> str:", "chat_id: int command: str def __repr__(self) -> str: return f\"{self.user_id=}", "# for garbage collection def __repr__(self) -> str: return f\"{self.user_id=}", "{self.command=}\" @dataclass class UserCommand: \"\"\"Stores the latest command sent by", "not send any news feeds on a daily basis user_id:", "if false, the bot will not send any news feeds", "import field from time import time from typing import Any", "currently sending\"\"\" user_id: int chat_id: int command: str def __repr__(self)", "def __repr__(self) -> str: return f\"{self.user_id=} {self.chat_id=} {self.message_id=} {self.text=}\" @dataclass", "int chat_id: int command: str def __repr__(self) -> str: return", "insert_time: int = int(time()) # for garbage collection def __repr__(self)", "import dataclass from dataclasses import field from time import time", "a daily basis user_id: int db_id: int topics: List[str] =", "user_id: int db_id: int topics: List[str] = field(default_factory=lambda: []) def", "user_id: int chat_id: int command: str def __repr__(self) -> str:", "\"\"\"Important things in the message\"\"\" user_id: int chat_id: int message_id:", "text: str def __repr__(self) -> str: return f\"{self.user_id=} {self.chat_id=} {self.message_id=}", "typing import Optional from typing import Tuple @dataclass class NewUser:", "from time import time from typing import Any from typing", "__repr__(self) -> str: return f\"{self.user_id=} {self.chat_id=} {self.message_id=} {self.text=}\" @dataclass class", "in the message\"\"\" user_id: int chat_id: int message_id: int text:", "feeds on a daily basis user_id: int db_id: int topics:", "things in the message\"\"\" user_id: int chat_id: int message_id: int", "sent by the user\"\"\" user_id: int command: str insert_time: int", "on a daily basis user_id: int db_id: int topics: List[str]", "@dataclass class UserDBInfo: \"\"\"Info about the user from the DB\"\"\"", "false, the bot will not send any news feeds on", "feed: bool # if false, the bot will not send", "fn: Callable[..., Any] args: Optional[Tuple[Any, ...]] = None kwargs: Optional[Dict[str,", "-> str: return f\"{self.user_id=} {self.command=} {self.insert_time=}\" @dataclass class MessageInfo: \"\"\"Important", "from typing import List from typing import Optional from typing", "def __repr__(self) -> str: return f\"{self.user_id=} {self.command=}\" @dataclass class UserCommand:", "UserCommand: \"\"\"Stores the latest command sent by the user\"\"\" user_id:", "import List from typing import Optional from typing import Tuple", "= int(time()) # for garbage collection def __repr__(self) -> str:", "import time from typing import Any from typing import Callable", "\"\"\"Info about the user from the DB\"\"\" feed: bool #", "Callable[..., Any] args: Optional[Tuple[Any, ...]] = None kwargs: Optional[Dict[str, Any]]", "typing import Any from typing import Callable from typing import", "NewUser: \"\"\"Deals with the commands the user is currently sending\"\"\"", "@dataclass class UserCommand: \"\"\"Stores the latest command sent by the", "return f\"{self.user_id=} {self.chat_id=} {self.message_id=} {self.text=}\" @dataclass class UserDBInfo: \"\"\"Info about", "Callable from typing import Dict from typing import List from", "daily basis user_id: int db_id: int topics: List[str] = field(default_factory=lambda:", "import Optional from typing import Tuple @dataclass class NewUser: \"\"\"Deals", "str: return f\"{self.user_id=} {self.command=}\" @dataclass class UserCommand: \"\"\"Stores the latest", "class UserDBInfo: \"\"\"Info about the user from the DB\"\"\" feed:", "DB\"\"\" feed: bool # if false, the bot will not", "db_id: int topics: List[str] = field(default_factory=lambda: []) def __repr__(self) ->", "typing import Dict from typing import List from typing import", "__repr__(self) -> str: return f\"{self.user_id=} {self.command=}\" @dataclass class UserCommand: \"\"\"Stores", "from typing import Tuple @dataclass class NewUser: \"\"\"Deals with the", "f\"{self.user_id=} {self.command=} {self.insert_time=}\" @dataclass class MessageInfo: \"\"\"Important things in the", "return f\"{self.user_id=} {self.feed=} {self.db_id=} {self.topics=}\" @dataclass class StagedFunction: \"\"\"For FunctionStagingArea\"\"\"", "@dataclass class NewUser: \"\"\"Deals with the commands the user is", "{self.command=} {self.insert_time=}\" @dataclass class MessageInfo: \"\"\"Important things in the message\"\"\"", "user\"\"\" user_id: int command: str insert_time: int = int(time()) #", "import Tuple @dataclass class NewUser: \"\"\"Deals with the commands the", "the user from the DB\"\"\" feed: bool # if false,", "class MessageInfo: \"\"\"Important things in the message\"\"\" user_id: int chat_id:", "str: return f\"{self.user_id=} {self.command=} {self.insert_time=}\" @dataclass class MessageInfo: \"\"\"Important things", "is currently sending\"\"\" user_id: int chat_id: int command: str def", "latest command sent by the user\"\"\" user_id: int command: str", "from the DB\"\"\" feed: bool # if false, the bot" ]
[ "organization_summmary_definition definition = { \"where\": \"?subj a foaf:Person .\", \"fields\":", "}, \"website\": { \"list\": True, \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc", "\"\"\" }, \"address\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc .", "a vivo:Position .\", \"fields\": { \"title\": { \"where\": \"?subj rdfs:label", "?gf rdfs:label ?obj . \"\"\", \"optional\": True, \"list\": True },", "\"where\": \"\"\" ?subj vivo:geographicFocus ?gf . ?gf rdfs:label ?obj .", "\"where\": \"?subj vivo:relates ?obj .\", \"definition\": organization_summmary_definition } } },", "}, \"publications\": { \"where\": \"\"\" ?subj vivo:relatedBy ?aship . ?aship", "a vcard:Kind . ?vc vcard:hasURL ?vcu . ?vcu a vcard:URL", "from .document_summary import definition as document_summary_definition from .organization_summary import definition", "True }, \"overview\": { \"where\": \"?subj vivo:overview ?obj .\", \"optional\":", "?vct a vcard:Telephone . ?vct vcard:telephone ?obj . \"\"\" },", "\"?subj rdfs:label ?obj .\" }, #Contact info \"email\": { \"where\":", "vcard:hasTelephone ?vct . ?vct a vcard:Telephone . ?vct vcard:telephone ?obj", "\"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc a vcard:Kind .", "a vcard:Email, vcard:Work . ?vce vcard:email ?obj . \"\"\" },", "}, \"city\": { \"where\": \"?subj vcard:locality ?obj .\" }, \"state\":", "{ \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc a vcard:Kind", "a vcard:URL . ?vcu vcard:url ?obj . \"\"\", \"optional\": True", "}, \"researchArea\": { \"where\": \"\"\" ?subj vivo:hasResearchArea ?ra . ?ra", "\"where\": \"\"\" ?subj vivo:hasResearchArea ?ra . ?ra rdfs:label ?obj .", "?vc a vcard:Kind . ?vc vcard:hasURL ?vcu . ?vcu a", "?obj . \"\"\", \"optional\": True, \"list\": True }, \"overview\": {", "?obj .\" }, \"state\": { \"where\": \"?subj vcard:region ?obj .\"", ". ?vce vcard:email ?obj . \"\"\" }, \"telephone\": { \"where\":", "?subj vivo:relatedBy ?aship . ?aship a vivo:Authorship . ?aship vivo:relates", "vivo:relatedBy ?aship . ?aship a vivo:Authorship . ?aship vivo:relates ?obj", "?obj .\" }, #Contact info \"email\": { \"where\": \"\"\" ?subj", "a vcard:Kind . ?vc vcard:hasEmail ?vce . ?vce a vcard:Email,", "\"\"\", \"definition\": document_summary_definition, \"optional\": True, \"list\": True } } }", ".\", \"optional\": True, }, \"positions\": { \"where\": \"?subj vivo:relatedBy ?obj", "{ \"where\": \"?subj a vcard:Address .\", \"fields\": { \"address\": {", "\"positions\": { \"where\": \"?subj vivo:relatedBy ?obj .\", \"definition\": { \"where\":", "\"?subj vivo:relatedBy ?obj .\", \"definition\": { \"where\": \"?subj a vivo:Position", ". ?vc vcard:hasEmail ?vce . ?vce a vcard:Email, vcard:Work .", "vivo:overview ?obj .\", \"optional\": True, }, \"positions\": { \"where\": \"?subj", ". \"\"\", \"optional\": True }, \"researchArea\": { \"where\": \"\"\" ?subj", "\"overview\": { \"where\": \"?subj vivo:overview ?obj .\", \"optional\": True, },", "organization_summmary_definition } } }, \"optional\": True, \"list\": True }, \"publications\":", "\"address\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc a", "}, \"zip\": { \"where\": \"?subj vcard:postalCode ?obj .\" } }", "a foaf:Person .\", \"fields\": { \"name\": { \"where\": \"?subj rdfs:label", "?subj obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ?vc vcard:hasEmail", ". ?vcu a vcard:URL . ?vcu vcard:url ?obj . \"\"\",", "}, \"positions\": { \"where\": \"?subj vivo:relatedBy ?obj .\", \"definition\": {", "?vc vcard:hasTelephone ?vct . ?vct a vcard:Telephone . ?vct vcard:telephone", "\"\"\" ?subj obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ?vc", "}, \"organization\": { \"where\": \"?subj vivo:relates ?obj .\", \"definition\": organization_summmary_definition", "{ \"where\": \"?subj a foaf:Person .\", \"fields\": { \"name\": {", "{ \"where\": \"?subj vcard:postalCode ?obj .\" } } } },", "?vcu . ?vcu a vcard:URL . ?vcu vcard:url ?obj .", "} } } }, \"website\": { \"list\": True, \"where\": \"\"\"", "\"where\": \"?subj rdfs:label ?obj .\" }, \"organization\": { \"where\": \"?subj", ". ?vc vcard:hasURL ?vcu . ?vcu a vcard:URL . ?vcu", "vcard:hasURL ?vcu . ?vcu a vcard:URL . ?vcu vcard:url ?obj", ". ?ra rdfs:label ?obj . \"\"\", \"optional\": True, \"list\": True", "obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ?vc vcard:hasTelephone ?vct", "{ \"where\": \"?subj vcard:streetAddress ?obj .\" }, \"city\": { \"where\":", "as document_summary_definition from .organization_summary import definition as organization_summmary_definition definition =", "\"?subj vcard:streetAddress ?obj .\" }, \"city\": { \"where\": \"?subj vcard:locality", ".\" }, \"zip\": { \"where\": \"?subj vcard:postalCode ?obj .\" }", "\"optional\": True }, \"researchArea\": { \"where\": \"\"\" ?subj vivo:hasResearchArea ?ra", "{ \"list\": True, \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc", ". ?vc a vcard:Kind . ?vc vcard:hasAddress ?obj . \"\"\",", "\"where\": \"?subj vivo:relatedBy ?obj .\", \"definition\": { \"where\": \"?subj a", ".\" }, \"state\": { \"where\": \"?subj vcard:region ?obj .\" },", "{ \"where\": \"?subj vivo:overview ?obj .\", \"optional\": True, }, \"positions\":", "\"list\": True }, \"publications\": { \"where\": \"\"\" ?subj vivo:relatedBy ?aship", "?aship vivo:relates ?obj . \"\"\", \"definition\": document_summary_definition, \"optional\": True, \"list\":", "vcard:locality ?obj .\" }, \"state\": { \"where\": \"?subj vcard:region ?obj", "\"optional\": True, \"list\": True }, \"publications\": { \"where\": \"\"\" ?subj", "\"?subj a vcard:Address .\", \"fields\": { \"address\": { \"where\": \"?subj", "\"where\": \"?subj vcard:locality ?obj .\" }, \"state\": { \"where\": \"?subj", "{ \"where\": \"?subj vcard:region ?obj .\" }, \"zip\": { \"where\":", "vcard:telephone ?obj . \"\"\" }, \"address\": { \"where\": \"\"\" ?subj", ".\", \"fields\": { \"address\": { \"where\": \"?subj vcard:streetAddress ?obj .\"", ". ?vc a vcard:Kind . ?vc vcard:hasEmail ?vce . ?vce", "\"where\": \"?subj vcard:streetAddress ?obj .\" }, \"city\": { \"where\": \"?subj", "?vc a vcard:Kind . ?vc vcard:hasTelephone ?vct . ?vct a", "\"definition\": { \"where\": \"?subj a vivo:Position .\", \"fields\": { \"title\":", "?vc a vcard:Kind . ?vc vcard:hasAddress ?obj . \"\"\", \"definition\":", "\"?subj a vivo:Position .\", \"fields\": { \"title\": { \"where\": \"?subj", "a vcard:Kind . ?vc vcard:hasTelephone ?vct . ?vct a vcard:Telephone", "\"where\": \"?subj a vivo:Position .\", \"fields\": { \"title\": { \"where\":", "\"\"\", \"optional\": True, \"list\": True }, \"overview\": { \"where\": \"?subj", "definition as organization_summmary_definition definition = { \"where\": \"?subj a foaf:Person", "} }, \"optional\": True, \"list\": True }, \"publications\": { \"where\":", "\"list\": True }, \"geographicFocus\": { \"where\": \"\"\" ?subj vivo:geographicFocus ?gf", "vcard:URL . ?vcu vcard:url ?obj . \"\"\", \"optional\": True },", "\"\"\", \"optional\": True }, \"researchArea\": { \"where\": \"\"\" ?subj vivo:hasResearchArea", "?obj .\", \"definition\": { \"where\": \"?subj a vivo:Position .\", \"fields\":", "document_summary_definition from .organization_summary import definition as organization_summmary_definition definition = {", "\"fields\": { \"address\": { \"where\": \"?subj vcard:streetAddress ?obj .\" },", "?vc . ?vc a vcard:Kind . ?vc vcard:hasTelephone ?vct .", "\"optional\": True, \"list\": True }, \"overview\": { \"where\": \"?subj vivo:overview", ". ?vct a vcard:Telephone . ?vct vcard:telephone ?obj . \"\"\"", "vcard:Kind . ?vc vcard:hasAddress ?obj . \"\"\", \"definition\": { \"where\":", ".\", \"fields\": { \"name\": { \"where\": \"?subj rdfs:label ?obj .\"", "?vct . ?vct a vcard:Telephone . ?vct vcard:telephone ?obj .", "\"where\": \"?subj vcard:postalCode ?obj .\" } } } }, \"website\":", "?subj obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ?vc vcard:hasTelephone", "obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ?vc vcard:hasURL ?vcu", "?aship a vivo:Authorship . ?aship vivo:relates ?obj . \"\"\", \"definition\":", ". ?vc vcard:hasTelephone ?vct . ?vct a vcard:Telephone . ?vct", "import definition as organization_summmary_definition definition = { \"where\": \"?subj a", "\"\"\", \"definition\": { \"where\": \"?subj a vcard:Address .\", \"fields\": {", "?subj obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ?vc vcard:hasURL", "vcard:hasAddress ?obj . \"\"\", \"definition\": { \"where\": \"?subj a vcard:Address", "foaf:Person .\", \"fields\": { \"name\": { \"where\": \"?subj rdfs:label ?obj", "\"publications\": { \"where\": \"\"\" ?subj vivo:relatedBy ?aship . ?aship a", "a vivo:Authorship . ?aship vivo:relates ?obj . \"\"\", \"definition\": document_summary_definition,", "\"definition\": { \"where\": \"?subj a vcard:Address .\", \"fields\": { \"address\":", "= { \"where\": \"?subj a foaf:Person .\", \"fields\": { \"name\":", "?obj . \"\"\", \"optional\": True, \"list\": True }, \"geographicFocus\": {", "\"telephone\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc a", "rdfs:label ?obj .\" }, \"organization\": { \"where\": \"?subj vivo:relates ?obj", "vcard:Address .\", \"fields\": { \"address\": { \"where\": \"?subj vcard:streetAddress ?obj", ". ?aship vivo:relates ?obj . \"\"\", \"definition\": document_summary_definition, \"optional\": True,", "}, \"geographicFocus\": { \"where\": \"\"\" ?subj vivo:geographicFocus ?gf . ?gf", "\"fields\": { \"name\": { \"where\": \"?subj rdfs:label ?obj .\" },", "vivo:geographicFocus ?gf . ?gf rdfs:label ?obj . \"\"\", \"optional\": True,", "\"\"\" }, \"telephone\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc .", "True, \"list\": True }, \"publications\": { \"where\": \"\"\" ?subj vivo:relatedBy", "\"organization\": { \"where\": \"?subj vivo:relates ?obj .\", \"definition\": organization_summmary_definition }", "\"?subj vcard:postalCode ?obj .\" } } } }, \"website\": {", ". ?vc a vcard:Kind . ?vc vcard:hasTelephone ?vct . ?vct", ".organization_summary import definition as organization_summmary_definition definition = { \"where\": \"?subj", "\"?subj a foaf:Person .\", \"fields\": { \"name\": { \"where\": \"?subj", ". \"\"\", \"definition\": document_summary_definition, \"optional\": True, \"list\": True } }", "?vc vcard:hasURL ?vcu . ?vcu a vcard:URL . ?vcu vcard:url", "vcard:Kind . ?vc vcard:hasTelephone ?vct . ?vct a vcard:Telephone .", "{ \"where\": \"\"\" ?subj vivo:relatedBy ?aship . ?aship a vivo:Authorship", "?obj .\", \"optional\": True, }, \"positions\": { \"where\": \"?subj vivo:relatedBy", ". ?vc a vcard:Kind . ?vc vcard:hasURL ?vcu . ?vcu", "\"\"\", \"optional\": True, \"list\": True }, \"geographicFocus\": { \"where\": \"\"\"", "vcard:hasEmail ?vce . ?vce a vcard:Email, vcard:Work . ?vce vcard:email", "\"address\": { \"where\": \"?subj vcard:streetAddress ?obj .\" }, \"city\": {", "\"website\": { \"list\": True, \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc .", "\"where\": \"?subj vcard:region ?obj .\" }, \"zip\": { \"where\": \"?subj", "?vcu vcard:url ?obj . \"\"\", \"optional\": True }, \"researchArea\": {", "?obj .\" }, \"organization\": { \"where\": \"?subj vivo:relates ?obj .\",", "\"?subj vivo:relates ?obj .\", \"definition\": organization_summmary_definition } } }, \"optional\":", "True, \"list\": True }, \"overview\": { \"where\": \"?subj vivo:overview ?obj", "{ \"where\": \"?subj a vivo:Position .\", \"fields\": { \"title\": {", "vivo:Position .\", \"fields\": { \"title\": { \"where\": \"?subj rdfs:label ?obj", "\"fields\": { \"title\": { \"where\": \"?subj rdfs:label ?obj .\" },", "\"name\": { \"where\": \"?subj rdfs:label ?obj .\" }, #Contact info", "}, \"state\": { \"where\": \"?subj vcard:region ?obj .\" }, \"zip\":", "vcard:Work . ?vce vcard:email ?obj . \"\"\" }, \"telephone\": {", "?obj .\" } } } }, \"website\": { \"list\": True,", "} }, \"website\": { \"list\": True, \"where\": \"\"\" ?subj obo:ARG_2000028", "a vcard:Address .\", \"fields\": { \"address\": { \"where\": \"?subj vcard:streetAddress", ". \"\"\" }, \"telephone\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc", "True, \"list\": True }, \"geographicFocus\": { \"where\": \"\"\" ?subj vivo:geographicFocus", "\"where\": \"?subj rdfs:label ?obj .\" }, #Contact info \"email\": {", "<filename>vivo2notld/definitions/person_definition.py from .document_summary import definition as document_summary_definition from .organization_summary import", "?gf . ?gf rdfs:label ?obj . \"\"\", \"optional\": True, \"list\":", "#Contact info \"email\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc .", "}, \"telephone\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc", "?aship . ?aship a vivo:Authorship . ?aship vivo:relates ?obj .", ". ?vc vcard:hasAddress ?obj . \"\"\", \"definition\": { \"where\": \"?subj", "a vcard:Kind . ?vc vcard:hasAddress ?obj . \"\"\", \"definition\": {", "?vc . ?vc a vcard:Kind . ?vc vcard:hasEmail ?vce .", "\"researchArea\": { \"where\": \"\"\" ?subj vivo:hasResearchArea ?ra . ?ra rdfs:label", ". ?vce a vcard:Email, vcard:Work . ?vce vcard:email ?obj .", "?vct vcard:telephone ?obj . \"\"\" }, \"address\": { \"where\": \"\"\"", "\"optional\": True, \"list\": True }, \"geographicFocus\": { \"where\": \"\"\" ?subj", "a vcard:Telephone . ?vct vcard:telephone ?obj . \"\"\" }, \"address\":", "info \"email\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc", "\"?subj vcard:region ?obj .\" }, \"zip\": { \"where\": \"?subj vcard:postalCode", "\"list\": True, \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc a", "\"\"\" ?subj vivo:geographicFocus ?gf . ?gf rdfs:label ?obj . \"\"\",", "vcard:region ?obj .\" }, \"zip\": { \"where\": \"?subj vcard:postalCode ?obj", "\"state\": { \"where\": \"?subj vcard:region ?obj .\" }, \"zip\": {", "vcard:Email, vcard:Work . ?vce vcard:email ?obj . \"\"\" }, \"telephone\":", "{ \"where\": \"?subj vcard:locality ?obj .\" }, \"state\": { \"where\":", "vivo:relatedBy ?obj .\", \"definition\": { \"where\": \"?subj a vivo:Position .\",", "?ra . ?ra rdfs:label ?obj . \"\"\", \"optional\": True, \"list\":", "?vce vcard:email ?obj . \"\"\" }, \"telephone\": { \"where\": \"\"\"", "rdfs:label ?obj .\" }, #Contact info \"email\": { \"where\": \"\"\"", "\"where\": \"?subj a foaf:Person .\", \"fields\": { \"name\": { \"where\":", "{ \"where\": \"?subj rdfs:label ?obj .\" }, #Contact info \"email\":", "obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ?vc vcard:hasAddress ?obj", "?subj vivo:hasResearchArea ?ra . ?ra rdfs:label ?obj . \"\"\", \"optional\":", "{ \"where\": \"?subj vivo:relatedBy ?obj .\", \"definition\": { \"where\": \"?subj", ".\", \"definition\": { \"where\": \"?subj a vivo:Position .\", \"fields\": {", ".\" }, \"city\": { \"where\": \"?subj vcard:locality ?obj .\" },", "{ \"address\": { \"where\": \"?subj vcard:streetAddress ?obj .\" }, \"city\":", "} } }, \"optional\": True, \"list\": True }, \"publications\": {", "\"email\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc a", "}, \"address\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc", "vcard:url ?obj . \"\"\", \"optional\": True }, \"researchArea\": { \"where\":", "{ \"where\": \"?subj vivo:relates ?obj .\", \"definition\": organization_summmary_definition } }", "?vc vcard:hasAddress ?obj . \"\"\", \"definition\": { \"where\": \"?subj a", "True, \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc . ?vc a vcard:Kind", "\"geographicFocus\": { \"where\": \"\"\" ?subj vivo:geographicFocus ?gf . ?gf rdfs:label", "rdfs:label ?obj . \"\"\", \"optional\": True, \"list\": True }, \"overview\":", "{ \"where\": \"?subj rdfs:label ?obj .\" }, \"organization\": { \"where\":", "?obj . \"\"\" }, \"telephone\": { \"where\": \"\"\" ?subj obo:ARG_2000028", "{ \"where\": \"\"\" ?subj vivo:hasResearchArea ?ra . ?ra rdfs:label ?obj", "obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ?vc vcard:hasEmail ?vce", "True }, \"researchArea\": { \"where\": \"\"\" ?subj vivo:hasResearchArea ?ra .", "?vc . ?vc a vcard:Kind . ?vc vcard:hasAddress ?obj .", "?ra rdfs:label ?obj . \"\"\", \"optional\": True, \"list\": True },", ".\", \"definition\": organization_summmary_definition } } }, \"optional\": True, \"list\": True", "\"?subj vcard:locality ?obj .\" }, \"state\": { \"where\": \"?subj vcard:region", "vcard:postalCode ?obj .\" } } } }, \"website\": { \"list\":", "vivo:relates ?obj .\", \"definition\": organization_summmary_definition } } }, \"optional\": True,", "\"\"\" ?subj vivo:relatedBy ?aship . ?aship a vivo:Authorship . ?aship", "import definition as document_summary_definition from .organization_summary import definition as organization_summmary_definition", "?vce . ?vce a vcard:Email, vcard:Work . ?vce vcard:email ?obj", "\"where\": \"?subj a vcard:Address .\", \"fields\": { \"address\": { \"where\":", "vcard:Telephone . ?vct vcard:telephone ?obj . \"\"\" }, \"address\": {", "}, \"overview\": { \"where\": \"?subj vivo:overview ?obj .\", \"optional\": True,", ".document_summary import definition as document_summary_definition from .organization_summary import definition as", "\"\"\" ?subj vivo:hasResearchArea ?ra . ?ra rdfs:label ?obj . \"\"\",", "vcard:Kind . ?vc vcard:hasURL ?vcu . ?vcu a vcard:URL .", "\"optional\": True, }, \"positions\": { \"where\": \"?subj vivo:relatedBy ?obj .\",", "?vce a vcard:Email, vcard:Work . ?vce vcard:email ?obj . \"\"\"", "\"definition\": organization_summmary_definition } } }, \"optional\": True, \"list\": True },", "as organization_summmary_definition definition = { \"where\": \"?subj a foaf:Person .\",", "\"?subj vivo:overview ?obj .\", \"optional\": True, }, \"positions\": { \"where\":", "?vcu a vcard:URL . ?vcu vcard:url ?obj . \"\"\", \"optional\":", "vivo:hasResearchArea ?ra . ?ra rdfs:label ?obj . \"\"\", \"optional\": True,", "?obj . \"\"\" }, \"address\": { \"where\": \"\"\" ?subj obo:ARG_2000028", ".\", \"fields\": { \"title\": { \"where\": \"?subj rdfs:label ?obj .\"", "\"title\": { \"where\": \"?subj rdfs:label ?obj .\" }, \"organization\": {", ". \"\"\" }, \"address\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc", "{ \"where\": \"\"\" ?subj vivo:geographicFocus ?gf . ?gf rdfs:label ?obj", "vcard:streetAddress ?obj .\" }, \"city\": { \"where\": \"?subj vcard:locality ?obj", "}, \"optional\": True, \"list\": True }, \"publications\": { \"where\": \"\"\"", "\"list\": True }, \"overview\": { \"where\": \"?subj vivo:overview ?obj .\",", "}, #Contact info \"email\": { \"where\": \"\"\" ?subj obo:ARG_2000028 ?vc", "?obj . \"\"\", \"definition\": { \"where\": \"?subj a vcard:Address .\",", "?obj .\" }, \"zip\": { \"where\": \"?subj vcard:postalCode ?obj .\"", "vcard:Kind . ?vc vcard:hasEmail ?vce . ?vce a vcard:Email, vcard:Work", "?vc . ?vc a vcard:Kind . ?vc vcard:hasURL ?vcu .", "} } }, \"website\": { \"list\": True, \"where\": \"\"\" ?subj", ". \"\"\", \"optional\": True, \"list\": True }, \"overview\": { \"where\":", ". ?gf rdfs:label ?obj . \"\"\", \"optional\": True, \"list\": True", "\"where\": \"\"\" ?subj vivo:relatedBy ?aship . ?aship a vivo:Authorship .", "\"city\": { \"where\": \"?subj vcard:locality ?obj .\" }, \"state\": {", ".\" } } } }, \"website\": { \"list\": True, \"where\":", "?obj .\", \"definition\": organization_summmary_definition } } }, \"optional\": True, \"list\":", "?vc vcard:hasEmail ?vce . ?vce a vcard:Email, vcard:Work . ?vce", "?obj . \"\"\", \"definition\": document_summary_definition, \"optional\": True, \"list\": True }", ". ?vct vcard:telephone ?obj . \"\"\" }, \"address\": { \"where\":", ". \"\"\", \"optional\": True, \"list\": True }, \"geographicFocus\": { \"where\":", "{ \"title\": { \"where\": \"?subj rdfs:label ?obj .\" }, \"organization\":", "?obj .\" }, \"city\": { \"where\": \"?subj vcard:locality ?obj .\"", "\"?subj rdfs:label ?obj .\" }, \"organization\": { \"where\": \"?subj vivo:relates", "\"where\": \"?subj vivo:overview ?obj .\", \"optional\": True, }, \"positions\": {", "{ \"name\": { \"where\": \"?subj rdfs:label ?obj .\" }, #Contact", "?vc a vcard:Kind . ?vc vcard:hasEmail ?vce . ?vce a", "True, }, \"positions\": { \"where\": \"?subj vivo:relatedBy ?obj .\", \"definition\":", "?obj . \"\"\", \"optional\": True }, \"researchArea\": { \"where\": \"\"\"", ".\" }, #Contact info \"email\": { \"where\": \"\"\" ?subj obo:ARG_2000028", "vcard:email ?obj . \"\"\" }, \"telephone\": { \"where\": \"\"\" ?subj", "True }, \"geographicFocus\": { \"where\": \"\"\" ?subj vivo:geographicFocus ?gf .", "rdfs:label ?obj . \"\"\", \"optional\": True, \"list\": True }, \"geographicFocus\":", ". ?vcu vcard:url ?obj . \"\"\", \"optional\": True }, \"researchArea\":", "from .organization_summary import definition as organization_summmary_definition definition = { \"where\":", "True }, \"publications\": { \"where\": \"\"\" ?subj vivo:relatedBy ?aship .", "?subj obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ?vc vcard:hasAddress", "definition as document_summary_definition from .organization_summary import definition as organization_summmary_definition definition", "\"zip\": { \"where\": \"?subj vcard:postalCode ?obj .\" } } }", ".\" }, \"organization\": { \"where\": \"?subj vivo:relates ?obj .\", \"definition\":", "vivo:relates ?obj . \"\"\", \"definition\": document_summary_definition, \"optional\": True, \"list\": True", ". ?aship a vivo:Authorship . ?aship vivo:relates ?obj . \"\"\",", "vivo:Authorship . ?aship vivo:relates ?obj . \"\"\", \"definition\": document_summary_definition, \"optional\":", ". \"\"\", \"definition\": { \"where\": \"?subj a vcard:Address .\", \"fields\":", "definition = { \"where\": \"?subj a foaf:Person .\", \"fields\": {", "?subj vivo:geographicFocus ?gf . ?gf rdfs:label ?obj . \"\"\", \"optional\":" ]
[ "user.id).filter(lookups) for item in items: result.add(app_name, 'meter', item.id, item.reading.date(), item.name(),", "Price.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name, 'price', item.id,", "import SearchResult from .models import app_name, Apart, Meter, Bill, Service,", "lookups = Q(name__icontains=query) | Q(abbr__icontains=query) items = Service.objects.filter(apart__user = user.id).filter(lookups)", "lookups = Q(info__icontains=query) items = Price.objects.filter(apart__user = user.id).filter(lookups) for item", "= SearchResult(query) lookups = Q(name__icontains=query) | Q(addr__icontains=query) items = Apart.objects.filter(user", "for item in items: result.add(app_name, 'price', item.id, item.start, item.name(), item.info,", "= user.id).filter(lookups) for item in items: result.add(app_name, 'meter', item.id, item.reading.date(),", ".models import app_name, Apart, Meter, Bill, Service, Price def search(user,", "item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(info__icontains=query) | Q(url__icontains=query) items", "'apart', item.id, None, item.name, item.addr, False) lookups = Q(info__icontains=query) items", "item.period.strftime('%m.%Y')) lookups = Q(info__icontains=query) | Q(url__icontains=query) items = Bill.objects.filter(apart__user =", "items: result.add(app_name, 'service', item.id, None, item.name, item.abbr, False, item.apart.name) lookups", "result.add(app_name, 'service', item.id, None, item.name, item.abbr, False, item.apart.name) lookups =", "item.abbr, False, item.apart.name) lookups = Q(info__icontains=query) items = Price.objects.filter(apart__user =", "'bill', item.id, item.payment.date(), item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups =", "for item in items: result.add(app_name, 'bill', item.id, item.payment.date(), item.name(), item.info,", "result.add(app_name, 'bill', item.id, item.payment.date(), item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups", "item.id, None, item.name, item.abbr, False, item.apart.name) lookups = Q(info__icontains=query) items", "app_name, Apart, Meter, Bill, Service, Price def search(user, query): result", "False, item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(name__icontains=query) | Q(abbr__icontains=query) items =", "items = Service.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name,", "= Apart.objects.filter(user = user.id).filter(lookups) for item in items: result.add(app_name, 'apart',", "items: result.add(app_name, 'price', item.id, item.start, item.name(), item.info, False, item.apart.name) return", "Bill, Service, Price def search(user, query): result = SearchResult(query) lookups", "= user.id).filter(lookups) for item in items: result.add(app_name, 'price', item.id, item.start,", "hier.search import SearchResult from .models import app_name, Apart, Meter, Bill,", "item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(name__icontains=query) | Q(abbr__icontains=query) items", "None, item.name, item.abbr, False, item.apart.name) lookups = Q(info__icontains=query) items =", "Q(info__icontains=query) items = Meter.objects.filter(apart__user = user.id).filter(lookups) for item in items:", "item.name, item.addr, False) lookups = Q(info__icontains=query) items = Meter.objects.filter(apart__user =", "item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(info__icontains=query) | Q(url__icontains=query) items = Bill.objects.filter(apart__user", "False, item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(info__icontains=query) | Q(url__icontains=query) items =", "= Q(info__icontains=query) items = Price.objects.filter(apart__user = user.id).filter(lookups) for item in", "Apart, Meter, Bill, Service, Price def search(user, query): result =", "lookups = Q(info__icontains=query) items = Meter.objects.filter(apart__user = user.id).filter(lookups) for item", "item.apart.name) lookups = Q(info__icontains=query) items = Price.objects.filter(apart__user = user.id).filter(lookups) for", "user.id).filter(lookups) for item in items: result.add(app_name, 'bill', item.id, item.payment.date(), item.name(),", "False, item.apart.name) lookups = Q(info__icontains=query) items = Price.objects.filter(apart__user = user.id).filter(lookups)", "items: result.add(app_name, 'apart', item.id, None, item.name, item.addr, False) lookups =", "item.id, item.payment.date(), item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(name__icontains=query)", "Price def search(user, query): result = SearchResult(query) lookups = Q(name__icontains=query)", "search(user, query): result = SearchResult(query) lookups = Q(name__icontains=query) | Q(addr__icontains=query)", "| Q(url__icontains=query) items = Bill.objects.filter(apart__user = user.id).filter(lookups) for item in", "item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(info__icontains=query) | Q(url__icontains=query)", "items: result.add(app_name, 'meter', item.id, item.reading.date(), item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y'))", "= user.id).filter(lookups) for item in items: result.add(app_name, 'bill', item.id, item.payment.date(),", "Q(addr__icontains=query) items = Apart.objects.filter(user = user.id).filter(lookups) for item in items:", "item.addr, False) lookups = Q(info__icontains=query) items = Meter.objects.filter(apart__user = user.id).filter(lookups)", "None, item.name, item.addr, False) lookups = Q(info__icontains=query) items = Meter.objects.filter(apart__user", "Q(name__icontains=query) | Q(abbr__icontains=query) items = Service.objects.filter(apart__user = user.id).filter(lookups) for item", "for item in items: result.add(app_name, 'service', item.id, None, item.name, item.abbr,", "Apart.objects.filter(user = user.id).filter(lookups) for item in items: result.add(app_name, 'apart', item.id,", "result.add(app_name, 'apart', item.id, None, item.name, item.addr, False) lookups = Q(info__icontains=query)", "from .models import app_name, Apart, Meter, Bill, Service, Price def", "for item in items: result.add(app_name, 'meter', item.id, item.reading.date(), item.name(), item.info,", "user.id).filter(lookups) for item in items: result.add(app_name, 'service', item.id, None, item.name,", "item.period.strftime('%m.%Y')) lookups = Q(name__icontains=query) | Q(abbr__icontains=query) items = Service.objects.filter(apart__user =", "SearchResult from .models import app_name, Apart, Meter, Bill, Service, Price", "= Price.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name, 'price',", "user.id).filter(lookups) for item in items: result.add(app_name, 'apart', item.id, None, item.name,", "<filename>apart/search.py from django.db.models import Q from hier.search import SearchResult from", "item.payment.date(), item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(name__icontains=query) |", "item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(name__icontains=query) | Q(abbr__icontains=query)", "import app_name, Apart, Meter, Bill, Service, Price def search(user, query):", "result.add(app_name, 'price', item.id, item.start, item.name(), item.info, False, item.apart.name) return result.items", "Q from hier.search import SearchResult from .models import app_name, Apart,", "items = Meter.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name,", "= Q(name__icontains=query) | Q(abbr__icontains=query) items = Service.objects.filter(apart__user = user.id).filter(lookups) for", "def search(user, query): result = SearchResult(query) lookups = Q(name__icontains=query) |", "in items: result.add(app_name, 'bill', item.id, item.payment.date(), item.name(), item.info, False, item.apart.name,", "django.db.models import Q from hier.search import SearchResult from .models import", "for item in items: result.add(app_name, 'apart', item.id, None, item.name, item.addr,", "Service, Price def search(user, query): result = SearchResult(query) lookups =", "lookups = Q(name__icontains=query) | Q(addr__icontains=query) items = Apart.objects.filter(user = user.id).filter(lookups)", "in items: result.add(app_name, 'price', item.id, item.start, item.name(), item.info, False, item.apart.name)", "= Q(info__icontains=query) items = Meter.objects.filter(apart__user = user.id).filter(lookups) for item in", "Q(url__icontains=query) items = Bill.objects.filter(apart__user = user.id).filter(lookups) for item in items:", "| Q(abbr__icontains=query) items = Service.objects.filter(apart__user = user.id).filter(lookups) for item in", "'meter', item.id, item.reading.date(), item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups =", "item in items: result.add(app_name, 'bill', item.id, item.payment.date(), item.name(), item.info, False,", "query): result = SearchResult(query) lookups = Q(name__icontains=query) | Q(addr__icontains=query) items", "import Q from hier.search import SearchResult from .models import app_name,", "= Service.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name, 'service',", "from hier.search import SearchResult from .models import app_name, Apart, Meter,", "Q(info__icontains=query) | Q(url__icontains=query) items = Bill.objects.filter(apart__user = user.id).filter(lookups) for item", "| Q(addr__icontains=query) items = Apart.objects.filter(user = user.id).filter(lookups) for item in", "lookups = Q(info__icontains=query) | Q(url__icontains=query) items = Bill.objects.filter(apart__user = user.id).filter(lookups)", "= Q(name__icontains=query) | Q(addr__icontains=query) items = Apart.objects.filter(user = user.id).filter(lookups) for", "item.reading.date(), item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(info__icontains=query) |", "= Bill.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name, 'bill',", "Q(abbr__icontains=query) items = Service.objects.filter(apart__user = user.id).filter(lookups) for item in items:", "Meter.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name, 'meter', item.id,", "item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(name__icontains=query) | Q(abbr__icontains=query) items = Service.objects.filter(apart__user", "in items: result.add(app_name, 'meter', item.id, item.reading.date(), item.name(), item.info, False, item.apart.name,", "items = Bill.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name,", "= user.id).filter(lookups) for item in items: result.add(app_name, 'apart', item.id, None,", "user.id).filter(lookups) for item in items: result.add(app_name, 'price', item.id, item.start, item.name(),", "item in items: result.add(app_name, 'apart', item.id, None, item.name, item.addr, False)", "item in items: result.add(app_name, 'meter', item.id, item.reading.date(), item.name(), item.info, False,", "item.name, item.abbr, False, item.apart.name) lookups = Q(info__icontains=query) items = Price.objects.filter(apart__user", "Bill.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name, 'bill', item.id,", "'service', item.id, None, item.name, item.abbr, False, item.apart.name) lookups = Q(info__icontains=query)", "item in items: result.add(app_name, 'service', item.id, None, item.name, item.abbr, False,", "item in items: result.add(app_name, 'price', item.id, item.start, item.name(), item.info, False,", "Service.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name, 'service', item.id,", "= Q(info__icontains=query) | Q(url__icontains=query) items = Bill.objects.filter(apart__user = user.id).filter(lookups) for", "SearchResult(query) lookups = Q(name__icontains=query) | Q(addr__icontains=query) items = Apart.objects.filter(user =", "item.id, None, item.name, item.addr, False) lookups = Q(info__icontains=query) items =", "= user.id).filter(lookups) for item in items: result.add(app_name, 'service', item.id, None,", "Meter, Bill, Service, Price def search(user, query): result = SearchResult(query)", "Q(info__icontains=query) items = Price.objects.filter(apart__user = user.id).filter(lookups) for item in items:", "item.id, item.reading.date(), item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups = Q(info__icontains=query)", "items = Price.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name,", "Q(name__icontains=query) | Q(addr__icontains=query) items = Apart.objects.filter(user = user.id).filter(lookups) for item", "from django.db.models import Q from hier.search import SearchResult from .models", "items: result.add(app_name, 'bill', item.id, item.payment.date(), item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y'))", "in items: result.add(app_name, 'service', item.id, None, item.name, item.abbr, False, item.apart.name)", "= Meter.objects.filter(apart__user = user.id).filter(lookups) for item in items: result.add(app_name, 'meter',", "in items: result.add(app_name, 'apart', item.id, None, item.name, item.addr, False) lookups", "False) lookups = Q(info__icontains=query) items = Meter.objects.filter(apart__user = user.id).filter(lookups) for", "result.add(app_name, 'meter', item.id, item.reading.date(), item.name(), item.info, False, item.apart.name, item.period.strftime('%m.%Y')) lookups", "items = Apart.objects.filter(user = user.id).filter(lookups) for item in items: result.add(app_name,", "result = SearchResult(query) lookups = Q(name__icontains=query) | Q(addr__icontains=query) items =" ]
[ "folder in folders: os.mkdir(os.path.join(self.data_folder, folder)) @property def experiment_folder(self): return self._experiment_folder", "and the standard for id is 'robot_ID' def __init__(self, settings):", "last_snapshot = np.sort(snapshots)[-1] # number of robots expected until the", "dir in d: if 'selectedpop' in dir: exported_files = len([name", "os.path.join(manager_folder, 'data', self.settings.experiment_name, self.settings.run) self._data_folder = os.path.join(self._experiment_folder, 'data_fullevolution') self._gen_num =", "def read_recovery_state(self, population_size, offspring_size): snapshots = [] for r, d,", "there are more robots to recover than the number expected", "[] for r, d, f in os.walk(self.experiment_folder): for dir in", "types of files are always phenotype ids, and the standard", "= [] for r, d, f in os.walk(self.experiment_folder): for dir", "= os.path.join(self.data_folder, 'battery') individual.export_battery(folder) def export_behavior_measures(self, _id, measures): filename =", "os.walk(self.experiment_folder): for dir in d: if 'selectedpop' in dir: exported_files", "> n_robots: # then recover also this partial offspring has_offspring", "folders: os.mkdir(os.path.join(self.data_folder, folder)) @property def experiment_folder(self): return self._experiment_folder @property def", "{str(len(individuals))} individuals') def experiment_is_new(self): if not os.path.exists(self.experiment_folder): return True path,", "as f: if measures is None: f.write(str(None)) else: for key,", "for name in os.listdir(os.path.join(self.experiment_folder, dir)) if os.path.isfile(os.path.join(self.experiment_folder, dir, name))]) if", "folder = os.path.join(self.data_folder, 'fitness') individual.export_fitness(folder) def export_objectives(self, individual): folder =", "@property def experiment_folder(self): return self._experiment_folder @property def data_folder(self): return self._data_folder", "str, file_extension=\".png\"): data_folder = os.path.join(self._data_folder, data_source) if not os.path.exists(data_folder): os.mkdir(data_folder)", "as np from pyrevolve.custom_logging.logger import logger import sys class ExperimentManagement:", "os.makedirs(self.experiment_folder) os.mkdir(self.data_folder) folders = ['genotypes', 'phenotypes', 'descriptors', 'objectives', 'fitness', 'battery',", "def export_behavior_measures(self, _id, measures): filename = os.path.join(self.data_folder, 'descriptors', f'behavior_desc_{_id}.txt') with", "ind in individuals: self.export_phenotype_images(f'selectedpop_{str(gen_num)}', ind) logger.info(f'Exported snapshot {str(gen_num)} with {str(len(individuals))}", "read_recovery_state(self, population_size, offspring_size): snapshots = [] for r, d, f", "of robots in the name of all types of files", "len(snapshots) > 0: # the latest complete snapshot last_snapshot =", "ind) logger.info(f'Exported snapshot {str(gen_num)} with {str(len(individuals))} individuals') def experiment_is_new(self): if", "shutil.rmtree(path) os.mkdir(path) for ind in individuals: self.export_phenotype_images(f'selectedpop_{str(gen_num)}', ind) logger.info(f'Exported snapshot", "return False def read_recovery_state(self, population_size, offspring_size): snapshots = [] for", "'battery', 'phenotype_images', 'failed_eval_robots'] for folder in folders: os.mkdir(os.path.join(self.data_folder, folder)) @property", "individual.phenotype.render_brain(os.path.join(self.experiment_folder, dirpath, f'brain_{individual.phenotype.id}.png')) def export_failed_eval_robot(self, individual): individual.genotype.export_genotype(os.path.join(self.data_folder, 'failed_eval_robots', f'genotype_{individual.phenotype.id}.txt')) individual.phenotype.save_file(os.path.join(self.data_folder,", "individual): folder = os.path.join(self.data_folder, 'objectives') individual.export_objectives(folder) def export_battery(self, individual): folder", "in measures.items(): f.write(f\"{key} {val}\\n\") def export_phenotype_images(self, dirpath, individual): individual.phenotype.render_body(os.path.join(self.experiment_folder, dirpath,", "class ExperimentManagement: # ids of robots in the name of", "'selectedpop' in dir: exported_files = len([name for name in os.listdir(os.path.join(self.experiment_folder,", "['genotypes', 'phenotypes', 'descriptors', 'objectives', 'fitness', 'battery', 'phenotype_images', 'failed_eval_robots'] for folder", "individuals: individual.export_fitness(folder) def export_fitness(self, individual): folder = os.path.join(self.data_folder, 'fitness') individual.export_fitness(folder)", "the snapshot n_robots = population_size + last_snapshot * offspring_size else:", "path = os.path.join(self.experiment_folder, f'selectedpop_{gen_num}') if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for ind", "np.sort(snapshots)[-1] # number of robots expected until the snapshot n_robots", "def export_phenotype_images(self, dirpath, individual): individual.phenotype.render_body(os.path.join(self.experiment_folder, dirpath, f'body_{individual.phenotype.id}.png')) individual.phenotype.render_brain(os.path.join(self.experiment_folder, dirpath, f'brain_{individual.phenotype.id}.png'))", "of all types of files are always phenotype ids, and", "[] for r, d, f in os.walk(os.path.join(self.data_folder, 'fitness')): for file", "has_offspring, last_id+1 def plot_path(self, data_source: str, filename: str, file_extension=\".png\"): data_folder", "self.settings.recovery_enabled: path = os.path.join(self.experiment_folder, f'selectedpop_{gen_num}') if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for", "= len([name for name in os.listdir(os.path.join(self.experiment_folder, dir)) if os.path.isfile(os.path.join(self.experiment_folder, dir,", "+ last_snapshot * offspring_size else: last_snapshot = -1 n_robots =", "os.path.exists(self.experiment_folder): return True path, dirs, files = next(os.walk(os.path.join(self.data_folder, 'fitness'))) if", "np.sort(robot_ids)[-1] # if there are more robots to recover than", "individual): individual.genotype.export_genotype(os.path.join(self.data_folder, 'failed_eval_robots', f'genotype_{individual.phenotype.id}.txt')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.yaml')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.sdf'),", "d, f in os.walk(self.experiment_folder): for dir in d: if 'selectedpop'", "def plot_path(self, data_source: str, filename: str, file_extension=\".png\"): data_folder = os.path.join(self._data_folder,", "individuals') def experiment_is_new(self): if not os.path.exists(self.experiment_folder): return True path, dirs,", "then recover also this partial offspring has_offspring = True else:", "= gen_num if self.settings.recovery_enabled: path = os.path.join(self.experiment_folder, f'selectedpop_{gen_num}') if os.path.exists(path):", "robot_ids.append(int(file.split('.')[0].split('_')[-1])) last_id = np.sort(robot_ids)[-1] # if there are more robots", "filename = os.path.join(self.data_folder, 'descriptors', f'behavior_desc_{_id}.txt') with open(filename, \"w\") as f:", "'objectives', 'fitness', 'battery', 'phenotype_images', 'failed_eval_robots'] for folder in folders: os.mkdir(os.path.join(self.data_folder,", "'failed_eval_robots', f'genotype_{individual.phenotype.id}.txt')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.yaml')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.sdf'), conf_type='sdf') def", "def create_exp_folders(self): if os.path.exists(self.experiment_folder): shutil.rmtree(self.experiment_folder) os.makedirs(self.experiment_folder) os.mkdir(self.data_folder) folders = ['genotypes',", "in f: robot_ids.append(int(file.split('.')[0].split('_')[-1])) last_id = np.sort(robot_ids)[-1] # if there are", "'data', self.settings.experiment_name, self.settings.run) self._data_folder = os.path.join(self._experiment_folder, 'data_fullevolution') self._gen_num = 0", "f'body_{individual.phenotype.id}.png')) individual.phenotype.render_brain(os.path.join(self.experiment_folder, dirpath, f'brain_{individual.phenotype.id}.png')) def export_failed_eval_robot(self, individual): individual.genotype.export_genotype(os.path.join(self.data_folder, 'failed_eval_robots', f'genotype_{individual.phenotype.id}.txt'))", "individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.sdf'), conf_type='sdf') def export_snapshots(self, individuals, gen_num): self._gen_num =", "individuals: self.export_phenotype_images(f'selectedpop_{str(gen_num)}', ind) logger.info(f'Exported snapshot {str(gen_num)} with {str(len(individuals))} individuals') def", "import shutil import numpy as np from pyrevolve.custom_logging.logger import logger", "id is 'robot_ID' def __init__(self, settings): self.settings = settings manager_folder", "== 0: return True else: return False def read_recovery_state(self, population_size,", "in dir: exported_files = len([name for name in os.listdir(os.path.join(self.experiment_folder, dir))", "snapshot last_snapshot = np.sort(snapshots)[-1] # number of robots expected until", "population_size + last_snapshot * offspring_size else: last_snapshot = -1 n_robots", "individual): if self.settings.export_phenotype: individual.export_phenotype(self.data_folder) def export_fitnesses(self, individuals): folder = self.data_folder", "in the name of all types of files are always", "expected until the snapshot n_robots = population_size + last_snapshot *", "last_snapshot * offspring_size else: last_snapshot = -1 n_robots = 0", "os.path.dirname(self.settings.manager) self._experiment_folder = os.path.join(manager_folder, 'data', self.settings.experiment_name, self.settings.run) self._data_folder = os.path.join(self._experiment_folder,", "len([name for name in os.listdir(os.path.join(self.experiment_folder, dir)) if os.path.isfile(os.path.join(self.experiment_folder, dir, name))])", "n_robots = population_size + last_snapshot * offspring_size else: last_snapshot =", "if len(files) == 0: return True else: return False def", "d: if 'selectedpop' in dir: exported_files = len([name for name", "snapshot n_robots = population_size + last_snapshot * offspring_size else: last_snapshot", "individual): if self.settings.recovery_enabled: individual.export_genotype(self.data_folder) def export_phenotype(self, individual): if self.settings.export_phenotype: individual.export_phenotype(self.data_folder)", "export_phenotype_images(self, dirpath, individual): individual.phenotype.render_body(os.path.join(self.experiment_folder, dirpath, f'body_{individual.phenotype.id}.png')) individual.phenotype.render_brain(os.path.join(self.experiment_folder, dirpath, f'brain_{individual.phenotype.id}.png')) def", "individuals, gen_num): self._gen_num = gen_num if self.settings.recovery_enabled: path = os.path.join(self.experiment_folder,", "= os.path.join(self._data_folder, data_source) if not os.path.exists(data_folder): os.mkdir(data_folder) return os.path.join(data_folder, filename", "if exported_files == (population_size * 2): # body and brain", "for r, d, f in os.walk(os.path.join(self.data_folder, 'fitness')): for file in", "last_id = np.sort(robot_ids)[-1] # if there are more robots to", "= True else: has_offspring = False return last_snapshot, has_offspring, last_id+1", "> 0: # the latest complete snapshot last_snapshot = np.sort(snapshots)[-1]", "exported_files == (population_size * 2): # body and brain files", "is 'robot_ID' def __init__(self, settings): self.settings = settings manager_folder =", "folder = self.data_folder for individual in individuals: individual.export_fitness(folder) def export_fitness(self,", "for folder in folders: os.mkdir(os.path.join(self.data_folder, folder)) @property def experiment_folder(self): return", "# ids of robots in the name of all types", "conf_type='sdf') def export_snapshots(self, individuals, gen_num): self._gen_num = gen_num if self.settings.recovery_enabled:", "last_id+1 def plot_path(self, data_source: str, filename: str, file_extension=\".png\"): data_folder =", "= os.path.dirname(self.settings.manager) self._experiment_folder = os.path.join(manager_folder, 'data', self.settings.experiment_name, self.settings.run) self._data_folder =", "return last_snapshot, has_offspring, last_id+1 def plot_path(self, data_source: str, filename: str,", "for ind in individuals: self.export_phenotype_images(f'selectedpop_{str(gen_num)}', ind) logger.info(f'Exported snapshot {str(gen_num)} with", "'phenotypes', 'descriptors', 'objectives', 'fitness', 'battery', 'phenotype_images', 'failed_eval_robots'] for folder in", "self._gen_num = gen_num if self.settings.recovery_enabled: path = os.path.join(self.experiment_folder, f'selectedpop_{gen_num}') if", "= os.path.join(self.data_folder, 'descriptors', f'behavior_desc_{_id}.txt') with open(filename, \"w\") as f: if", "str, filename: str, file_extension=\".png\"): data_folder = os.path.join(self._data_folder, data_source) if not", "else: for key, val in measures.items(): f.write(f\"{key} {val}\\n\") def export_phenotype_images(self,", "__init__(self, settings): self.settings = settings manager_folder = os.path.dirname(self.settings.manager) self._experiment_folder =", "if os.path.exists(self.experiment_folder): shutil.rmtree(self.experiment_folder) os.makedirs(self.experiment_folder) os.mkdir(self.data_folder) folders = ['genotypes', 'phenotypes', 'descriptors',", "is None: f.write(str(None)) else: for key, val in measures.items(): f.write(f\"{key}", "= np.sort(snapshots)[-1] # number of robots expected until the snapshot", "for id is 'robot_ID' def __init__(self, settings): self.settings = settings", "export_fitness(self, individual): folder = os.path.join(self.data_folder, 'fitness') individual.export_fitness(folder) def export_objectives(self, individual):", "def data_folder(self): return self._data_folder def export_genotype(self, individual): if self.settings.recovery_enabled: individual.export_genotype(self.data_folder)", "len(files) == 0: return True else: return False def read_recovery_state(self,", "def export_objectives(self, individual): folder = os.path.join(self.data_folder, 'objectives') individual.export_objectives(folder) def export_battery(self,", "phenotype ids, and the standard for id is 'robot_ID' def", "import logger import sys class ExperimentManagement: # ids of robots", "experiment_is_new(self): if not os.path.exists(self.experiment_folder): return True path, dirs, files =", "f: if measures is None: f.write(str(None)) else: for key, val", "os.mkdir(os.path.join(self.data_folder, folder)) @property def experiment_folder(self): return self._experiment_folder @property def data_folder(self):", "os.path.isfile(os.path.join(self.experiment_folder, dir, name))]) if exported_files == (population_size * 2): #", "with open(filename, \"w\") as f: if measures is None: f.write(str(None))", "False return last_snapshot, has_offspring, last_id+1 def plot_path(self, data_source: str, filename:", "def experiment_is_new(self): if not os.path.exists(self.experiment_folder): return True path, dirs, files", "np from pyrevolve.custom_logging.logger import logger import sys class ExperimentManagement: #", "def export_phenotype(self, individual): if self.settings.export_phenotype: individual.export_phenotype(self.data_folder) def export_fitnesses(self, individuals): folder", "are more robots to recover than the number expected in", "= np.sort(robot_ids)[-1] # if there are more robots to recover", "for key, val in measures.items(): f.write(f\"{key} {val}\\n\") def export_phenotype_images(self, dirpath,", "if measures is None: f.write(str(None)) else: for key, val in", "last_snapshot = -1 n_robots = 0 robot_ids = [] for", "always phenotype ids, and the standard for id is 'robot_ID'", "_id, measures): filename = os.path.join(self.data_folder, 'descriptors', f'behavior_desc_{_id}.txt') with open(filename, \"w\")", "not os.path.exists(data_folder): os.mkdir(data_folder) return os.path.join(data_folder, filename + str(self._gen_num) + file_extension)", "export_failed_eval_robot(self, individual): individual.genotype.export_genotype(os.path.join(self.data_folder, 'failed_eval_robots', f'genotype_{individual.phenotype.id}.txt')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.yaml')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots',", "dirpath, f'brain_{individual.phenotype.id}.png')) def export_failed_eval_robot(self, individual): individual.genotype.export_genotype(os.path.join(self.data_folder, 'failed_eval_robots', f'genotype_{individual.phenotype.id}.txt')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots',", "= os.path.join(self.data_folder, 'fitness') individual.export_fitness(folder) def export_objectives(self, individual): folder = os.path.join(self.data_folder,", "self.settings.recovery_enabled: individual.export_genotype(self.data_folder) def export_phenotype(self, individual): if self.settings.export_phenotype: individual.export_phenotype(self.data_folder) def export_fitnesses(self,", "self._experiment_folder @property def data_folder(self): return self._data_folder def export_genotype(self, individual): if", "folder = os.path.join(self.data_folder, 'battery') individual.export_battery(folder) def export_behavior_measures(self, _id, measures): filename", "# if there are more robots to recover than the", "in os.walk(self.experiment_folder): for dir in d: if 'selectedpop' in dir:", "os.mkdir(self.data_folder) folders = ['genotypes', 'phenotypes', 'descriptors', 'objectives', 'fitness', 'battery', 'phenotype_images',", "open(filename, \"w\") as f: if measures is None: f.write(str(None)) else:", "else: last_snapshot = -1 n_robots = 0 robot_ids = []", "in os.listdir(os.path.join(self.experiment_folder, dir)) if os.path.isfile(os.path.join(self.experiment_folder, dir, name))]) if exported_files ==", "# the latest complete snapshot last_snapshot = np.sort(snapshots)[-1] # number", "key, val in measures.items(): f.write(f\"{key} {val}\\n\") def export_phenotype_images(self, dirpath, individual):", "if self.settings.recovery_enabled: path = os.path.join(self.experiment_folder, f'selectedpop_{gen_num}') if os.path.exists(path): shutil.rmtree(path) os.mkdir(path)", "files snapshots.append(int(dir.split('_')[1])) if len(snapshots) > 0: # the latest complete", "f.write(str(None)) else: for key, val in measures.items(): f.write(f\"{key} {val}\\n\") def", "def __init__(self, settings): self.settings = settings manager_folder = os.path.dirname(self.settings.manager) self._experiment_folder", "also this partial offspring has_offspring = True else: has_offspring =", "settings): self.settings = settings manager_folder = os.path.dirname(self.settings.manager) self._experiment_folder = os.path.join(manager_folder,", "= settings manager_folder = os.path.dirname(self.settings.manager) self._experiment_folder = os.path.join(manager_folder, 'data', self.settings.experiment_name,", "= False return last_snapshot, has_offspring, last_id+1 def plot_path(self, data_source: str,", "robots in the name of all types of files are", "return self._data_folder def export_genotype(self, individual): if self.settings.recovery_enabled: individual.export_genotype(self.data_folder) def export_phenotype(self,", "f.write(f\"{key} {val}\\n\") def export_phenotype_images(self, dirpath, individual): individual.phenotype.render_body(os.path.join(self.experiment_folder, dirpath, f'body_{individual.phenotype.id}.png')) individual.phenotype.render_brain(os.path.join(self.experiment_folder,", "ExperimentManagement: # ids of robots in the name of all", "else: has_offspring = False return last_snapshot, has_offspring, last_id+1 def plot_path(self,", "robots to recover than the number expected in this snapshot", "n_robots: # then recover also this partial offspring has_offspring =", "folder)) @property def experiment_folder(self): return self._experiment_folder @property def data_folder(self): return", "if not os.path.exists(self.experiment_folder): return True path, dirs, files = next(os.walk(os.path.join(self.data_folder,", "dir: exported_files = len([name for name in os.listdir(os.path.join(self.experiment_folder, dir)) if", "0 def create_exp_folders(self): if os.path.exists(self.experiment_folder): shutil.rmtree(self.experiment_folder) os.makedirs(self.experiment_folder) os.mkdir(self.data_folder) folders =", "True else: return False def read_recovery_state(self, population_size, offspring_size): snapshots =", "settings manager_folder = os.path.dirname(self.settings.manager) self._experiment_folder = os.path.join(manager_folder, 'data', self.settings.experiment_name, self.settings.run)", "os.listdir(os.path.join(self.experiment_folder, dir)) if os.path.isfile(os.path.join(self.experiment_folder, dir, name))]) if exported_files == (population_size", "more robots to recover than the number expected in this", "def export_fitnesses(self, individuals): folder = self.data_folder for individual in individuals:", "os.path.exists(self.experiment_folder): shutil.rmtree(self.experiment_folder) os.makedirs(self.experiment_folder) os.mkdir(self.data_folder) folders = ['genotypes', 'phenotypes', 'descriptors', 'objectives',", "'failed_eval_robots', f'phenotype_{individual.phenotype.id}.sdf'), conf_type='sdf') def export_snapshots(self, individuals, gen_num): self._gen_num = gen_num", "f in os.walk(os.path.join(self.data_folder, 'fitness')): for file in f: robot_ids.append(int(file.split('.')[0].split('_')[-1])) last_id", "return True else: return False def read_recovery_state(self, population_size, offspring_size): snapshots", "f'phenotype_{individual.phenotype.id}.yaml')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.sdf'), conf_type='sdf') def export_snapshots(self, individuals, gen_num): self._gen_num", "shutil import numpy as np from pyrevolve.custom_logging.logger import logger import", "self._experiment_folder = os.path.join(manager_folder, 'data', self.settings.experiment_name, self.settings.run) self._data_folder = os.path.join(self._experiment_folder, 'data_fullevolution')", "individual): folder = os.path.join(self.data_folder, 'battery') individual.export_battery(folder) def export_behavior_measures(self, _id, measures):", "for file in f: robot_ids.append(int(file.split('.')[0].split('_')[-1])) last_id = np.sort(robot_ids)[-1] # if", "f in os.walk(self.experiment_folder): for dir in d: if 'selectedpop' in", "to recover than the number expected in this snapshot if", "'fitness') individual.export_fitness(folder) def export_objectives(self, individual): folder = os.path.join(self.data_folder, 'objectives') individual.export_objectives(folder)", "for individual in individuals: individual.export_fitness(folder) def export_fitness(self, individual): folder =", "= population_size + last_snapshot * offspring_size else: last_snapshot = -1", "= [] for r, d, f in os.walk(os.path.join(self.data_folder, 'fitness')): for", "os.path.join(self.data_folder, 'objectives') individual.export_objectives(folder) def export_battery(self, individual): folder = os.path.join(self.data_folder, 'battery')", "os.path.join(self._data_folder, data_source) if not os.path.exists(data_folder): os.mkdir(data_folder) return os.path.join(data_folder, filename +", "individual in individuals: individual.export_fitness(folder) def export_fitness(self, individual): folder = os.path.join(self.data_folder,", "@property def data_folder(self): return self._data_folder def export_genotype(self, individual): if self.settings.recovery_enabled:", "(population_size * 2): # body and brain files snapshots.append(int(dir.split('_')[1])) if", "ids, and the standard for id is 'robot_ID' def __init__(self,", "# number of robots expected until the snapshot n_robots =", "robots expected until the snapshot n_robots = population_size + last_snapshot", "file_extension=\".png\"): data_folder = os.path.join(self._data_folder, data_source) if not os.path.exists(data_folder): os.mkdir(data_folder) return", "path, dirs, files = next(os.walk(os.path.join(self.data_folder, 'fitness'))) if len(files) == 0:", "files = next(os.walk(os.path.join(self.data_folder, 'fitness'))) if len(files) == 0: return True", "n_robots = 0 robot_ids = [] for r, d, f", "self.export_phenotype_images(f'selectedpop_{str(gen_num)}', ind) logger.info(f'Exported snapshot {str(gen_num)} with {str(len(individuals))} individuals') def experiment_is_new(self):", "return self._experiment_folder @property def data_folder(self): return self._data_folder def export_genotype(self, individual):", "dirpath, f'body_{individual.phenotype.id}.png')) individual.phenotype.render_brain(os.path.join(self.experiment_folder, dirpath, f'brain_{individual.phenotype.id}.png')) def export_failed_eval_robot(self, individual): individual.genotype.export_genotype(os.path.join(self.data_folder, 'failed_eval_robots',", "-1 n_robots = 0 robot_ids = [] for r, d,", "individual.export_fitness(folder) def export_objectives(self, individual): folder = os.path.join(self.data_folder, 'objectives') individual.export_objectives(folder) def", "'data_fullevolution') self._gen_num = 0 def create_exp_folders(self): if os.path.exists(self.experiment_folder): shutil.rmtree(self.experiment_folder) os.makedirs(self.experiment_folder)", "folders = ['genotypes', 'phenotypes', 'descriptors', 'objectives', 'fitness', 'battery', 'phenotype_images', 'failed_eval_robots']", "in folders: os.mkdir(os.path.join(self.data_folder, folder)) @property def experiment_folder(self): return self._experiment_folder @property", "= 0 def create_exp_folders(self): if os.path.exists(self.experiment_folder): shutil.rmtree(self.experiment_folder) os.makedirs(self.experiment_folder) os.mkdir(self.data_folder) folders", "True else: has_offspring = False return last_snapshot, has_offspring, last_id+1 def", "for dir in d: if 'selectedpop' in dir: exported_files =", "if len(snapshots) > 0: # the latest complete snapshot last_snapshot", "self.settings = settings manager_folder = os.path.dirname(self.settings.manager) self._experiment_folder = os.path.join(manager_folder, 'data',", "next(os.walk(os.path.join(self.data_folder, 'fitness'))) if len(files) == 0: return True else: return", "individual.export_objectives(folder) def export_battery(self, individual): folder = os.path.join(self.data_folder, 'battery') individual.export_battery(folder) def", "individual.genotype.export_genotype(os.path.join(self.data_folder, 'failed_eval_robots', f'genotype_{individual.phenotype.id}.txt')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.yaml')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.sdf'), conf_type='sdf')", "number of robots expected until the snapshot n_robots = population_size", "in d: if 'selectedpop' in dir: exported_files = len([name for", "os.path.join(self.data_folder, 'fitness') individual.export_fitness(folder) def export_objectives(self, individual): folder = os.path.join(self.data_folder, 'objectives')", "this partial offspring has_offspring = True else: has_offspring = False", "'descriptors', f'behavior_desc_{_id}.txt') with open(filename, \"w\") as f: if measures is", "= next(os.walk(os.path.join(self.data_folder, 'fitness'))) if len(files) == 0: return True else:", "os.path.join(self.data_folder, 'battery') individual.export_battery(folder) def export_behavior_measures(self, _id, measures): filename = os.path.join(self.data_folder,", "r, d, f in os.walk(os.path.join(self.data_folder, 'fitness')): for file in f:", "offspring_size else: last_snapshot = -1 n_robots = 0 robot_ids =", "= 0 robot_ids = [] for r, d, f in", "exported_files = len([name for name in os.listdir(os.path.join(self.experiment_folder, dir)) if os.path.isfile(os.path.join(self.experiment_folder,", "= os.path.join(manager_folder, 'data', self.settings.experiment_name, self.settings.run) self._data_folder = os.path.join(self._experiment_folder, 'data_fullevolution') self._gen_num", "None: f.write(str(None)) else: for key, val in measures.items(): f.write(f\"{key} {val}\\n\")", "the number expected in this snapshot if last_id > n_robots:", "and brain files snapshots.append(int(dir.split('_')[1])) if len(snapshots) > 0: # the", "recover than the number expected in this snapshot if last_id", "individual.export_genotype(self.data_folder) def export_phenotype(self, individual): if self.settings.export_phenotype: individual.export_phenotype(self.data_folder) def export_fitnesses(self, individuals):", "f'brain_{individual.phenotype.id}.png')) def export_failed_eval_robot(self, individual): individual.genotype.export_genotype(os.path.join(self.data_folder, 'failed_eval_robots', f'genotype_{individual.phenotype.id}.txt')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.yaml'))", "name of all types of files are always phenotype ids,", "all types of files are always phenotype ids, and the", "= ['genotypes', 'phenotypes', 'descriptors', 'objectives', 'fitness', 'battery', 'phenotype_images', 'failed_eval_robots'] for", "2): # body and brain files snapshots.append(int(dir.split('_')[1])) if len(snapshots) >", "if not os.path.exists(data_folder): os.mkdir(data_folder) return os.path.join(data_folder, filename + str(self._gen_num) +", "dir)) if os.path.isfile(os.path.join(self.experiment_folder, dir, name))]) if exported_files == (population_size *", "export_phenotype(self, individual): if self.settings.export_phenotype: individual.export_phenotype(self.data_folder) def export_fitnesses(self, individuals): folder =", "create_exp_folders(self): if os.path.exists(self.experiment_folder): shutil.rmtree(self.experiment_folder) os.makedirs(self.experiment_folder) os.mkdir(self.data_folder) folders = ['genotypes', 'phenotypes',", "data_source) if not os.path.exists(data_folder): os.mkdir(data_folder) return os.path.join(data_folder, filename + str(self._gen_num)", "= os.path.join(self.data_folder, 'objectives') individual.export_objectives(folder) def export_battery(self, individual): folder = os.path.join(self.data_folder,", "def experiment_folder(self): return self._experiment_folder @property def data_folder(self): return self._data_folder def", "individual.export_fitness(folder) def export_fitness(self, individual): folder = os.path.join(self.data_folder, 'fitness') individual.export_fitness(folder) def", "'robot_ID' def __init__(self, settings): self.settings = settings manager_folder = os.path.dirname(self.settings.manager)", "gen_num): self._gen_num = gen_num if self.settings.recovery_enabled: path = os.path.join(self.experiment_folder, f'selectedpop_{gen_num}')", "individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.yaml')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.sdf'), conf_type='sdf') def export_snapshots(self, individuals,", "in this snapshot if last_id > n_robots: # then recover", "not os.path.exists(self.experiment_folder): return True path, dirs, files = next(os.walk(os.path.join(self.data_folder, 'fitness')))", "{val}\\n\") def export_phenotype_images(self, dirpath, individual): individual.phenotype.render_body(os.path.join(self.experiment_folder, dirpath, f'body_{individual.phenotype.id}.png')) individual.phenotype.render_brain(os.path.join(self.experiment_folder, dirpath,", "manager_folder = os.path.dirname(self.settings.manager) self._experiment_folder = os.path.join(manager_folder, 'data', self.settings.experiment_name, self.settings.run) self._data_folder", "'fitness'))) if len(files) == 0: return True else: return False", "the standard for id is 'robot_ID' def __init__(self, settings): self.settings", "has_offspring = False return last_snapshot, has_offspring, last_id+1 def plot_path(self, data_source:", "logger.info(f'Exported snapshot {str(gen_num)} with {str(len(individuals))} individuals') def experiment_is_new(self): if not", "individual.export_phenotype(self.data_folder) def export_fitnesses(self, individuals): folder = self.data_folder for individual in", "'fitness')): for file in f: robot_ids.append(int(file.split('.')[0].split('_')[-1])) last_id = np.sort(robot_ids)[-1] #", "plot_path(self, data_source: str, filename: str, file_extension=\".png\"): data_folder = os.path.join(self._data_folder, data_source)", "f'genotype_{individual.phenotype.id}.txt')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.yaml')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.sdf'), conf_type='sdf') def export_snapshots(self,", "latest complete snapshot last_snapshot = np.sort(snapshots)[-1] # number of robots", "f'phenotype_{individual.phenotype.id}.sdf'), conf_type='sdf') def export_snapshots(self, individuals, gen_num): self._gen_num = gen_num if", "recover also this partial offspring has_offspring = True else: has_offspring", "population_size, offspring_size): snapshots = [] for r, d, f in", "brain files snapshots.append(int(dir.split('_')[1])) if len(snapshots) > 0: # the latest", "in individuals: self.export_phenotype_images(f'selectedpop_{str(gen_num)}', ind) logger.info(f'Exported snapshot {str(gen_num)} with {str(len(individuals))} individuals')", "f: robot_ids.append(int(file.split('.')[0].split('_')[-1])) last_id = np.sort(robot_ids)[-1] # if there are more", "d, f in os.walk(os.path.join(self.data_folder, 'fitness')): for file in f: robot_ids.append(int(file.split('.')[0].split('_')[-1]))", "in individuals: individual.export_fitness(folder) def export_fitness(self, individual): folder = os.path.join(self.data_folder, 'fitness')", "self.data_folder for individual in individuals: individual.export_fitness(folder) def export_fitness(self, individual): folder", "import sys class ExperimentManagement: # ids of robots in the", "partial offspring has_offspring = True else: has_offspring = False return", "export_battery(self, individual): folder = os.path.join(self.data_folder, 'battery') individual.export_battery(folder) def export_behavior_measures(self, _id,", "= self.data_folder for individual in individuals: individual.export_fitness(folder) def export_fitness(self, individual):", "has_offspring = True else: has_offspring = False return last_snapshot, has_offspring,", "snapshots.append(int(dir.split('_')[1])) if len(snapshots) > 0: # the latest complete snapshot", "shutil.rmtree(self.experiment_folder) os.makedirs(self.experiment_folder) os.mkdir(self.data_folder) folders = ['genotypes', 'phenotypes', 'descriptors', 'objectives', 'fitness',", "import os import shutil import numpy as np from pyrevolve.custom_logging.logger", "measures is None: f.write(str(None)) else: for key, val in measures.items():", "this snapshot if last_id > n_robots: # then recover also", "of robots expected until the snapshot n_robots = population_size +", "are always phenotype ids, and the standard for id is", "{str(gen_num)} with {str(len(individuals))} individuals') def experiment_is_new(self): if not os.path.exists(self.experiment_folder): return", "the latest complete snapshot last_snapshot = np.sort(snapshots)[-1] # number of", "the name of all types of files are always phenotype", "'failed_eval_robots', f'phenotype_{individual.phenotype.id}.yaml')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.sdf'), conf_type='sdf') def export_snapshots(self, individuals, gen_num):", "data_folder(self): return self._data_folder def export_genotype(self, individual): if self.settings.recovery_enabled: individual.export_genotype(self.data_folder) def", "# then recover also this partial offspring has_offspring = True", "name in os.listdir(os.path.join(self.experiment_folder, dir)) if os.path.isfile(os.path.join(self.experiment_folder, dir, name))]) if exported_files", "data_folder = os.path.join(self._data_folder, data_source) if not os.path.exists(data_folder): os.mkdir(data_folder) return os.path.join(data_folder,", "def export_genotype(self, individual): if self.settings.recovery_enabled: individual.export_genotype(self.data_folder) def export_phenotype(self, individual): if", "'descriptors', 'objectives', 'fitness', 'battery', 'phenotype_images', 'failed_eval_robots'] for folder in folders:", "val in measures.items(): f.write(f\"{key} {val}\\n\") def export_phenotype_images(self, dirpath, individual): individual.phenotype.render_body(os.path.join(self.experiment_folder,", "def export_battery(self, individual): folder = os.path.join(self.data_folder, 'battery') individual.export_battery(folder) def export_behavior_measures(self,", "export_genotype(self, individual): if self.settings.recovery_enabled: individual.export_genotype(self.data_folder) def export_phenotype(self, individual): if self.settings.export_phenotype:", "offspring_size): snapshots = [] for r, d, f in os.walk(self.experiment_folder):", "def export_fitness(self, individual): folder = os.path.join(self.data_folder, 'fitness') individual.export_fitness(folder) def export_objectives(self,", "* offspring_size else: last_snapshot = -1 n_robots = 0 robot_ids", "with {str(len(individuals))} individuals') def experiment_is_new(self): if not os.path.exists(self.experiment_folder): return True", "'fitness', 'battery', 'phenotype_images', 'failed_eval_robots'] for folder in folders: os.mkdir(os.path.join(self.data_folder, folder))", "'objectives') individual.export_objectives(folder) def export_battery(self, individual): folder = os.path.join(self.data_folder, 'battery') individual.export_battery(folder)", "snapshot if last_id > n_robots: # then recover also this", "than the number expected in this snapshot if last_id >", "os.walk(os.path.join(self.data_folder, 'fitness')): for file in f: robot_ids.append(int(file.split('.')[0].split('_')[-1])) last_id = np.sort(robot_ids)[-1]", "os.path.join(self.experiment_folder, f'selectedpop_{gen_num}') if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for ind in individuals:", "body and brain files snapshots.append(int(dir.split('_')[1])) if len(snapshots) > 0: #", "return True path, dirs, files = next(os.walk(os.path.join(self.data_folder, 'fitness'))) if len(files)", "self._data_folder = os.path.join(self._experiment_folder, 'data_fullevolution') self._gen_num = 0 def create_exp_folders(self): if", "name))]) if exported_files == (population_size * 2): # body and", "os.path.join(self._experiment_folder, 'data_fullevolution') self._gen_num = 0 def create_exp_folders(self): if os.path.exists(self.experiment_folder): shutil.rmtree(self.experiment_folder)", "export_behavior_measures(self, _id, measures): filename = os.path.join(self.data_folder, 'descriptors', f'behavior_desc_{_id}.txt') with open(filename,", "self.settings.export_phenotype: individual.export_phenotype(self.data_folder) def export_fitnesses(self, individuals): folder = self.data_folder for individual", "os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for ind in individuals: self.export_phenotype_images(f'selectedpop_{str(gen_num)}', ind) logger.info(f'Exported", "filename: str, file_extension=\".png\"): data_folder = os.path.join(self._data_folder, data_source) if not os.path.exists(data_folder):", "file in f: robot_ids.append(int(file.split('.')[0].split('_')[-1])) last_id = np.sort(robot_ids)[-1] # if there", "if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for ind in individuals: self.export_phenotype_images(f'selectedpop_{str(gen_num)}', ind)", "experiment_folder(self): return self._experiment_folder @property def data_folder(self): return self._data_folder def export_genotype(self,", "sys class ExperimentManagement: # ids of robots in the name", "gen_num if self.settings.recovery_enabled: path = os.path.join(self.experiment_folder, f'selectedpop_{gen_num}') if os.path.exists(path): shutil.rmtree(path)", "= os.path.join(self.experiment_folder, f'selectedpop_{gen_num}') if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for ind in", "numpy as np from pyrevolve.custom_logging.logger import logger import sys class", "robot_ids = [] for r, d, f in os.walk(os.path.join(self.data_folder, 'fitness')):", "pyrevolve.custom_logging.logger import logger import sys class ExperimentManagement: # ids of", "import numpy as np from pyrevolve.custom_logging.logger import logger import sys", "self._data_folder def export_genotype(self, individual): if self.settings.recovery_enabled: individual.export_genotype(self.data_folder) def export_phenotype(self, individual):", "number expected in this snapshot if last_id > n_robots: #", "* 2): # body and brain files snapshots.append(int(dir.split('_')[1])) if len(snapshots)", "individual.phenotype.render_body(os.path.join(self.experiment_folder, dirpath, f'body_{individual.phenotype.id}.png')) individual.phenotype.render_brain(os.path.join(self.experiment_folder, dirpath, f'brain_{individual.phenotype.id}.png')) def export_failed_eval_robot(self, individual): individual.genotype.export_genotype(os.path.join(self.data_folder,", "= os.path.join(self._experiment_folder, 'data_fullevolution') self._gen_num = 0 def create_exp_folders(self): if os.path.exists(self.experiment_folder):", "r, d, f in os.walk(self.experiment_folder): for dir in d: if", "in os.walk(os.path.join(self.data_folder, 'fitness')): for file in f: robot_ids.append(int(file.split('.')[0].split('_')[-1])) last_id =", "self.settings.experiment_name, self.settings.run) self._data_folder = os.path.join(self._experiment_folder, 'data_fullevolution') self._gen_num = 0 def", "dirs, files = next(os.walk(os.path.join(self.data_folder, 'fitness'))) if len(files) == 0: return", "self.settings.run) self._data_folder = os.path.join(self._experiment_folder, 'data_fullevolution') self._gen_num = 0 def create_exp_folders(self):", "expected in this snapshot if last_id > n_robots: # then", "last_snapshot, has_offspring, last_id+1 def plot_path(self, data_source: str, filename: str, file_extension=\".png\"):", "f'behavior_desc_{_id}.txt') with open(filename, \"w\") as f: if measures is None:", "# body and brain files snapshots.append(int(dir.split('_')[1])) if len(snapshots) > 0:", "'phenotype_images', 'failed_eval_robots'] for folder in folders: os.mkdir(os.path.join(self.data_folder, folder)) @property def", "for r, d, f in os.walk(self.experiment_folder): for dir in d:", "if self.settings.export_phenotype: individual.export_phenotype(self.data_folder) def export_fitnesses(self, individuals): folder = self.data_folder for", "0: return True else: return False def read_recovery_state(self, population_size, offspring_size):", "individual): folder = os.path.join(self.data_folder, 'fitness') individual.export_fitness(folder) def export_objectives(self, individual): folder", "of files are always phenotype ids, and the standard for", "snapshot {str(gen_num)} with {str(len(individuals))} individuals') def experiment_is_new(self): if not os.path.exists(self.experiment_folder):", "until the snapshot n_robots = population_size + last_snapshot * offspring_size", "ids of robots in the name of all types of", "0 robot_ids = [] for r, d, f in os.walk(os.path.join(self.data_folder,", "individuals): folder = self.data_folder for individual in individuals: individual.export_fitness(folder) def", "0: # the latest complete snapshot last_snapshot = np.sort(snapshots)[-1] #", "def export_failed_eval_robot(self, individual): individual.genotype.export_genotype(os.path.join(self.data_folder, 'failed_eval_robots', f'genotype_{individual.phenotype.id}.txt')) individual.phenotype.save_file(os.path.join(self.data_folder, 'failed_eval_robots', f'phenotype_{individual.phenotype.id}.yaml')) individual.phenotype.save_file(os.path.join(self.data_folder,", "f'selectedpop_{gen_num}') if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for ind in individuals: self.export_phenotype_images(f'selectedpop_{str(gen_num)}',", "if self.settings.recovery_enabled: individual.export_genotype(self.data_folder) def export_phenotype(self, individual): if self.settings.export_phenotype: individual.export_phenotype(self.data_folder) def", "dirpath, individual): individual.phenotype.render_body(os.path.join(self.experiment_folder, dirpath, f'body_{individual.phenotype.id}.png')) individual.phenotype.render_brain(os.path.join(self.experiment_folder, dirpath, f'brain_{individual.phenotype.id}.png')) def export_failed_eval_robot(self,", "True path, dirs, files = next(os.walk(os.path.join(self.data_folder, 'fitness'))) if len(files) ==", "files are always phenotype ids, and the standard for id", "snapshots = [] for r, d, f in os.walk(self.experiment_folder): for", "else: return False def read_recovery_state(self, population_size, offspring_size): snapshots = []", "measures): filename = os.path.join(self.data_folder, 'descriptors', f'behavior_desc_{_id}.txt') with open(filename, \"w\") as", "measures.items(): f.write(f\"{key} {val}\\n\") def export_phenotype_images(self, dirpath, individual): individual.phenotype.render_body(os.path.join(self.experiment_folder, dirpath, f'body_{individual.phenotype.id}.png'))", "== (population_size * 2): # body and brain files snapshots.append(int(dir.split('_')[1]))", "last_id > n_robots: # then recover also this partial offspring", "individual.export_battery(folder) def export_behavior_measures(self, _id, measures): filename = os.path.join(self.data_folder, 'descriptors', f'behavior_desc_{_id}.txt')", "os.path.join(self.data_folder, 'descriptors', f'behavior_desc_{_id}.txt') with open(filename, \"w\") as f: if measures", "export_snapshots(self, individuals, gen_num): self._gen_num = gen_num if self.settings.recovery_enabled: path =", "export_fitnesses(self, individuals): folder = self.data_folder for individual in individuals: individual.export_fitness(folder)", "individual): individual.phenotype.render_body(os.path.join(self.experiment_folder, dirpath, f'body_{individual.phenotype.id}.png')) individual.phenotype.render_brain(os.path.join(self.experiment_folder, dirpath, f'brain_{individual.phenotype.id}.png')) def export_failed_eval_robot(self, individual):", "os import shutil import numpy as np from pyrevolve.custom_logging.logger import", "dir, name))]) if exported_files == (population_size * 2): # body", "if last_id > n_robots: # then recover also this partial", "offspring has_offspring = True else: has_offspring = False return last_snapshot,", "if os.path.isfile(os.path.join(self.experiment_folder, dir, name))]) if exported_files == (population_size * 2):", "folder = os.path.join(self.data_folder, 'objectives') individual.export_objectives(folder) def export_battery(self, individual): folder =", "self._gen_num = 0 def create_exp_folders(self): if os.path.exists(self.experiment_folder): shutil.rmtree(self.experiment_folder) os.makedirs(self.experiment_folder) os.mkdir(self.data_folder)", "def export_snapshots(self, individuals, gen_num): self._gen_num = gen_num if self.settings.recovery_enabled: path", "= -1 n_robots = 0 robot_ids = [] for r,", "'failed_eval_robots'] for folder in folders: os.mkdir(os.path.join(self.data_folder, folder)) @property def experiment_folder(self):", "if 'selectedpop' in dir: exported_files = len([name for name in", "data_source: str, filename: str, file_extension=\".png\"): data_folder = os.path.join(self._data_folder, data_source) if", "'battery') individual.export_battery(folder) def export_behavior_measures(self, _id, measures): filename = os.path.join(self.data_folder, 'descriptors',", "False def read_recovery_state(self, population_size, offspring_size): snapshots = [] for r,", "export_objectives(self, individual): folder = os.path.join(self.data_folder, 'objectives') individual.export_objectives(folder) def export_battery(self, individual):", "if there are more robots to recover than the number", "\"w\") as f: if measures is None: f.write(str(None)) else: for", "from pyrevolve.custom_logging.logger import logger import sys class ExperimentManagement: # ids", "complete snapshot last_snapshot = np.sort(snapshots)[-1] # number of robots expected", "<filename>pyrevolve/experiment_management.py<gh_stars>0 import os import shutil import numpy as np from", "standard for id is 'robot_ID' def __init__(self, settings): self.settings =", "os.mkdir(path) for ind in individuals: self.export_phenotype_images(f'selectedpop_{str(gen_num)}', ind) logger.info(f'Exported snapshot {str(gen_num)}", "logger import sys class ExperimentManagement: # ids of robots in" ]
[ "\"\"\" self.query_execution_time = query_execution_time def get_query_execution_time(self): \"\"\"Get query execution time.", "\"\"\" return self.query_execution_time def set_request_handling_time(self, request_handling_time): \"\"\"Set request handling time.", "Response write time. \"\"\" self.response_write_time = response_write_time def get_response_write_time(self): \"\"\"Get", "\"\"\" self.response_write_time = response_write_time def get_response_write_time(self): \"\"\"Get response write time.", "request_handling_time def get_request_handling_time(self): \"\"\"Get request handling time. Returns: str: Request", "self.request_handling_time def set_response_write_time(self, response_write_time): \"\"\"Set response write time. Args: response_write_time(str):", "= '' self.page_context_write_time = '' def set_query_execution_time(self, query_execution_time): \"\"\"Set query", "\"\"\"Set response write time. Args: response_write_time(str): Response write time. \"\"\"", "return self.query_execution_time def set_request_handling_time(self, request_handling_time): \"\"\"Set request handling time. Args:", "Instrumentation object.\"\"\" self.query_execution_time = '' self.request_handling_time = '' self.response_write_time =", "Returns: str: Query execution time. \"\"\" return self.query_execution_time def set_request_handling_time(self,", "response_write_time): \"\"\"Set response write time. Args: response_write_time(str): Response write time.", "time. \"\"\" self.request_handling_time = request_handling_time def get_request_handling_time(self): \"\"\"Get request handling", "write time. \"\"\" self.page_context_write_time = page_context_write_time def get_page_context_write_time(self): \"\"\"Get page", "used tocreate object for instrumentation.\"\"\" def __init__(self): \"\"\"Initialize parameters for", "class Instrumentation: \"\"\"This class is used tocreate object for instrumentation.\"\"\"", "class is used tocreate object for instrumentation.\"\"\" def __init__(self): \"\"\"Initialize", "for instrumentation.\"\"\" def __init__(self): \"\"\"Initialize parameters for Instrumentation object.\"\"\" self.query_execution_time", "self.query_execution_time = '' self.request_handling_time = '' self.response_write_time = '' self.page_context_write_time", "str: Query execution time. \"\"\" return self.query_execution_time def set_request_handling_time(self, request_handling_time):", "Args: response_write_time(str): Response write time. \"\"\" self.response_write_time = response_write_time def", "time. \"\"\" return self.request_handling_time def set_response_write_time(self, response_write_time): \"\"\"Set response write", "'' self.request_handling_time = '' self.response_write_time = '' self.page_context_write_time = ''", "time. Returns: str: Query execution time. \"\"\" return self.query_execution_time def", "= '' def set_query_execution_time(self, query_execution_time): \"\"\"Set query execution time. Args:", "Args: query_execution_time(str): Query execution time. \"\"\" self.query_execution_time = query_execution_time def", "time. \"\"\" return self.query_execution_time def set_request_handling_time(self, request_handling_time): \"\"\"Set request handling", "query execution time. Returns: str: Query execution time. \"\"\" return", "def get_page_context_write_time(self): \"\"\"Get page context write time. Returns: str: Page", "Response write time. \"\"\" return self.response_write_time def set_page_context_write_time(self, page_context_write_time): \"\"\"Set", "Args: page_context_write_time(str): Page context write time. \"\"\" self.page_context_write_time = page_context_write_time", "self.page_context_write_time = '' def set_query_execution_time(self, query_execution_time): \"\"\"Set query execution time.", "Args: request_handling_time(str): Request handling time. \"\"\" self.request_handling_time = request_handling_time def", "\"\"\" self.page_context_write_time = page_context_write_time def get_page_context_write_time(self): \"\"\"Get page context write", "\"\"\"Get page context write time. Returns: str: Page context write", "self.request_handling_time = request_handling_time def get_request_handling_time(self): \"\"\"Get request handling time. Returns:", "set_response_write_time(self, response_write_time): \"\"\"Set response write time. Args: response_write_time(str): Response write", "response write time. Args: response_write_time(str): Response write time. \"\"\" self.response_write_time", "page_context_write_time(str): Page context write time. \"\"\" self.page_context_write_time = page_context_write_time def", "def get_response_write_time(self): \"\"\"Get response write time. Returns: str: Response write", "self.page_context_write_time = page_context_write_time def get_page_context_write_time(self): \"\"\"Get page context write time.", "def set_query_execution_time(self, query_execution_time): \"\"\"Set query execution time. Args: query_execution_time(str): Query", "handling time. \"\"\" return self.request_handling_time def set_response_write_time(self, response_write_time): \"\"\"Set response", "execution time. \"\"\" self.query_execution_time = query_execution_time def get_query_execution_time(self): \"\"\"Get query", "__init__(self): \"\"\"Initialize parameters for Instrumentation object.\"\"\" self.query_execution_time = '' self.request_handling_time", "time. \"\"\" return self.response_write_time def set_page_context_write_time(self, page_context_write_time): \"\"\"Set page context", "Instrumentation: \"\"\"This class is used tocreate object for instrumentation.\"\"\" def", "request_handling_time): \"\"\"Set request handling time. Args: request_handling_time(str): Request handling time.", "\"\"\"This class is used tocreate object for instrumentation.\"\"\" def __init__(self):", "response_write_time def get_response_write_time(self): \"\"\"Get response write time. Returns: str: Response", "page context write time. Returns: str: Page context write time.", "query execution time. Args: query_execution_time(str): Query execution time. \"\"\" self.query_execution_time", "page_context_write_time def get_page_context_write_time(self): \"\"\"Get page context write time. Returns: str:", "set_page_context_write_time(self, page_context_write_time): \"\"\"Set page context write time. Args: page_context_write_time(str): Page", "def __init__(self): \"\"\"Initialize parameters for Instrumentation object.\"\"\" self.query_execution_time = ''", "execution time. \"\"\" return self.query_execution_time def set_request_handling_time(self, request_handling_time): \"\"\"Set request", "#$Id$ class Instrumentation: \"\"\"This class is used tocreate object for", "object for instrumentation.\"\"\" def __init__(self): \"\"\"Initialize parameters for Instrumentation object.\"\"\"", "set_query_execution_time(self, query_execution_time): \"\"\"Set query execution time. Args: query_execution_time(str): Query execution", "def get_request_handling_time(self): \"\"\"Get request handling time. Returns: str: Request handling", "time. \"\"\" self.response_write_time = response_write_time def get_response_write_time(self): \"\"\"Get response write", "write time. Returns: str: Page context write time. \"\"\" return", "Request handling time. \"\"\" return self.request_handling_time def set_response_write_time(self, response_write_time): \"\"\"Set", "'' def set_query_execution_time(self, query_execution_time): \"\"\"Set query execution time. Args: query_execution_time(str):", "context write time. Returns: str: Page context write time. \"\"\"", "query_execution_time def get_query_execution_time(self): \"\"\"Get query execution time. Returns: str: Query", "\"\"\"Set page context write time. Args: page_context_write_time(str): Page context write", "handling time. \"\"\" self.request_handling_time = request_handling_time def get_request_handling_time(self): \"\"\"Get request", "get_page_context_write_time(self): \"\"\"Get page context write time. Returns: str: Page context", "str: Request handling time. \"\"\" return self.request_handling_time def set_response_write_time(self, response_write_time):", "time. \"\"\" self.page_context_write_time = page_context_write_time def get_page_context_write_time(self): \"\"\"Get page context", "= '' self.request_handling_time = '' self.response_write_time = '' self.page_context_write_time =", "self.request_handling_time = '' self.response_write_time = '' self.page_context_write_time = '' def", "'' self.page_context_write_time = '' def set_query_execution_time(self, query_execution_time): \"\"\"Set query execution", "query_execution_time(str): Query execution time. \"\"\" self.query_execution_time = query_execution_time def get_query_execution_time(self):", "self.response_write_time = '' self.page_context_write_time = '' def set_query_execution_time(self, query_execution_time): \"\"\"Set", "def get_query_execution_time(self): \"\"\"Get query execution time. Returns: str: Query execution", "time. Args: page_context_write_time(str): Page context write time. \"\"\" self.page_context_write_time =", "time. Args: query_execution_time(str): Query execution time. \"\"\" self.query_execution_time = query_execution_time", "time. Args: request_handling_time(str): Request handling time. \"\"\" self.request_handling_time = request_handling_time", "time. Returns: str: Request handling time. \"\"\" return self.request_handling_time def", "= query_execution_time def get_query_execution_time(self): \"\"\"Get query execution time. Returns: str:", "instrumentation.\"\"\" def __init__(self): \"\"\"Initialize parameters for Instrumentation object.\"\"\" self.query_execution_time =", "is used tocreate object for instrumentation.\"\"\" def __init__(self): \"\"\"Initialize parameters", "self.response_write_time = response_write_time def get_response_write_time(self): \"\"\"Get response write time. Returns:", "time. Returns: str: Page context write time. \"\"\" return self.page_context_write_time", "= request_handling_time def get_request_handling_time(self): \"\"\"Get request handling time. Returns: str:", "response write time. Returns: str: Response write time. \"\"\" return", "write time. Args: response_write_time(str): Response write time. \"\"\" self.response_write_time =", "Page context write time. \"\"\" self.page_context_write_time = page_context_write_time def get_page_context_write_time(self):", "= response_write_time def get_response_write_time(self): \"\"\"Get response write time. Returns: str:", "get_request_handling_time(self): \"\"\"Get request handling time. Returns: str: Request handling time.", "\"\"\"Get query execution time. Returns: str: Query execution time. \"\"\"", "set_request_handling_time(self, request_handling_time): \"\"\"Set request handling time. Args: request_handling_time(str): Request handling", "execution time. Returns: str: Query execution time. \"\"\" return self.query_execution_time", "write time. \"\"\" self.response_write_time = response_write_time def get_response_write_time(self): \"\"\"Get response", "get_response_write_time(self): \"\"\"Get response write time. Returns: str: Response write time.", "\"\"\"Set request handling time. Args: request_handling_time(str): Request handling time. \"\"\"", "def set_request_handling_time(self, request_handling_time): \"\"\"Set request handling time. Args: request_handling_time(str): Request", "execution time. Args: query_execution_time(str): Query execution time. \"\"\" self.query_execution_time =", "page context write time. Args: page_context_write_time(str): Page context write time.", "handling time. Returns: str: Request handling time. \"\"\" return self.request_handling_time", "time. \"\"\" self.query_execution_time = query_execution_time def get_query_execution_time(self): \"\"\"Get query execution", "context write time. \"\"\" self.page_context_write_time = page_context_write_time def get_page_context_write_time(self): \"\"\"Get", "time. Args: response_write_time(str): Response write time. \"\"\" self.response_write_time = response_write_time", "context write time. Args: page_context_write_time(str): Page context write time. \"\"\"", "time. Returns: str: Response write time. \"\"\" return self.response_write_time def", "= '' self.response_write_time = '' self.page_context_write_time = '' def set_query_execution_time(self,", "request handling time. Returns: str: Request handling time. \"\"\" return", "handling time. Args: request_handling_time(str): Request handling time. \"\"\" self.request_handling_time =", "self.query_execution_time = query_execution_time def get_query_execution_time(self): \"\"\"Get query execution time. Returns:", "object.\"\"\" self.query_execution_time = '' self.request_handling_time = '' self.response_write_time = ''", "str: Response write time. \"\"\" return self.response_write_time def set_page_context_write_time(self, page_context_write_time):", "tocreate object for instrumentation.\"\"\" def __init__(self): \"\"\"Initialize parameters for Instrumentation", "\"\"\"Get request handling time. Returns: str: Request handling time. \"\"\"", "\"\"\" return self.request_handling_time def set_response_write_time(self, response_write_time): \"\"\"Set response write time.", "return self.response_write_time def set_page_context_write_time(self, page_context_write_time): \"\"\"Set page context write time.", "Returns: str: Response write time. \"\"\" return self.response_write_time def set_page_context_write_time(self,", "self.response_write_time def set_page_context_write_time(self, page_context_write_time): \"\"\"Set page context write time. Args:", "return self.request_handling_time def set_response_write_time(self, response_write_time): \"\"\"Set response write time. Args:", "write time. Args: page_context_write_time(str): Page context write time. \"\"\" self.page_context_write_time", "for Instrumentation object.\"\"\" self.query_execution_time = '' self.request_handling_time = '' self.response_write_time", "query_execution_time): \"\"\"Set query execution time. Args: query_execution_time(str): Query execution time.", "parameters for Instrumentation object.\"\"\" self.query_execution_time = '' self.request_handling_time = ''", "Request handling time. \"\"\" self.request_handling_time = request_handling_time def get_request_handling_time(self): \"\"\"Get", "write time. Returns: str: Response write time. \"\"\" return self.response_write_time", "Returns: str: Request handling time. \"\"\" return self.request_handling_time def set_response_write_time(self,", "page_context_write_time): \"\"\"Set page context write time. Args: page_context_write_time(str): Page context", "request_handling_time(str): Request handling time. \"\"\" self.request_handling_time = request_handling_time def get_request_handling_time(self):", "write time. \"\"\" return self.response_write_time def set_page_context_write_time(self, page_context_write_time): \"\"\"Set page", "'' self.response_write_time = '' self.page_context_write_time = '' def set_query_execution_time(self, query_execution_time):", "def set_response_write_time(self, response_write_time): \"\"\"Set response write time. Args: response_write_time(str): Response", "\"\"\" return self.response_write_time def set_page_context_write_time(self, page_context_write_time): \"\"\"Set page context write", "response_write_time(str): Response write time. \"\"\" self.response_write_time = response_write_time def get_response_write_time(self):", "\"\"\"Initialize parameters for Instrumentation object.\"\"\" self.query_execution_time = '' self.request_handling_time =", "\"\"\" self.request_handling_time = request_handling_time def get_request_handling_time(self): \"\"\"Get request handling time.", "Query execution time. \"\"\" self.query_execution_time = query_execution_time def get_query_execution_time(self): \"\"\"Get", "get_query_execution_time(self): \"\"\"Get query execution time. Returns: str: Query execution time.", "Query execution time. \"\"\" return self.query_execution_time def set_request_handling_time(self, request_handling_time): \"\"\"Set", "def set_page_context_write_time(self, page_context_write_time): \"\"\"Set page context write time. Args: page_context_write_time(str):", "self.query_execution_time def set_request_handling_time(self, request_handling_time): \"\"\"Set request handling time. Args: request_handling_time(str):", "\"\"\"Set query execution time. Args: query_execution_time(str): Query execution time. \"\"\"", "request handling time. Args: request_handling_time(str): Request handling time. \"\"\" self.request_handling_time", "= page_context_write_time def get_page_context_write_time(self): \"\"\"Get page context write time. Returns:", "\"\"\"Get response write time. Returns: str: Response write time. \"\"\"" ]
[ "Research Open Domain Q&A Toolkit\", url=\"https://github.com/facebookresearch/DPR/\", classifiers=[ \"Intended Audience ::", "and its affiliates. # # This source code is licensed", "in the # LICENSE file in the root directory of", "under the MIT license found in the # LICENSE file", "MIT License\", \"Programming Language :: Python :: 3.6\", \"Topic ::", "file in the root directory of this source tree. from", "setup( name=\"dpr\", version=\"0.1.0\", description=\"Facebook AI Research Open Domain Q&A Toolkit\",", "License\", \"Programming Language :: Python :: 3.6\", \"Topic :: Scientific/Engineering", "Copyright (c) Facebook, Inc. and its affiliates. # # This", "in the root directory of this source tree. from setuptools", "\"filelock\", \"numpy\", \"regex\", \"torch>=1.2.0\", \"transformers>=3.0.0,<3.1.0\", \"tqdm>=4.27\", \"wget\", \"spacy>=2.1.8\", ], )", "#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates.", "LICENSE file in the root directory of this source tree.", "AI Research Open Domain Q&A Toolkit\", url=\"https://github.com/facebookresearch/DPR/\", classifiers=[ \"Intended Audience", "its affiliates. # # This source code is licensed under", "f.read() setup( name=\"dpr\", version=\"0.1.0\", description=\"Facebook AI Research Open Domain Q&A", ":: MIT License\", \"Programming Language :: Python :: 3.6\", \"Topic", "Q&A Toolkit\", url=\"https://github.com/facebookresearch/DPR/\", classifiers=[ \"Intended Audience :: Science/Research\", \"License ::", "import setup with open(\"README.md\") as f: readme = f.read() setup(", "# LICENSE file in the root directory of this source", "the MIT license found in the # LICENSE file in", "from setuptools import setup with open(\"README.md\") as f: readme =", "url=\"https://github.com/facebookresearch/DPR/\", classifiers=[ \"Intended Audience :: Science/Research\", \"License :: OSI Approved", "Python :: 3.6\", \"Topic :: Scientific/Engineering :: Artificial Intelligence\", ],", "directory of this source tree. from setuptools import setup with", "found in the # LICENSE file in the root directory", "Science/Research\", \"License :: OSI Approved :: MIT License\", \"Programming Language", "license found in the # LICENSE file in the root", "= f.read() setup( name=\"dpr\", version=\"0.1.0\", description=\"Facebook AI Research Open Domain", "of this source tree. from setuptools import setup with open(\"README.md\")", "description=\"Facebook AI Research Open Domain Q&A Toolkit\", url=\"https://github.com/facebookresearch/DPR/\", classifiers=[ \"Intended", "OSI Approved :: MIT License\", \"Programming Language :: Python ::", "\"Topic :: Scientific/Engineering :: Artificial Intelligence\", ], long_description=readme, long_description_content_type=\"text/markdown\", setup_requires=[", "install_requires=[ \"cython\", \"faiss-cpu>=1.6.1\", \"filelock\", \"numpy\", \"regex\", \"torch>=1.2.0\", \"transformers>=3.0.0,<3.1.0\", \"tqdm>=4.27\", \"wget\",", ":: Python :: 3.6\", \"Topic :: Scientific/Engineering :: Artificial Intelligence\",", "Toolkit\", url=\"https://github.com/facebookresearch/DPR/\", classifiers=[ \"Intended Audience :: Science/Research\", \"License :: OSI", "], long_description=readme, long_description_content_type=\"text/markdown\", setup_requires=[ \"setuptools>=18.0\", ], install_requires=[ \"cython\", \"faiss-cpu>=1.6.1\", \"filelock\",", "root directory of this source tree. from setuptools import setup", "name=\"dpr\", version=\"0.1.0\", description=\"Facebook AI Research Open Domain Q&A Toolkit\", url=\"https://github.com/facebookresearch/DPR/\",", ":: 3.6\", \"Topic :: Scientific/Engineering :: Artificial Intelligence\", ], long_description=readme,", "setup_requires=[ \"setuptools>=18.0\", ], install_requires=[ \"cython\", \"faiss-cpu>=1.6.1\", \"filelock\", \"numpy\", \"regex\", \"torch>=1.2.0\",", "3.6\", \"Topic :: Scientific/Engineering :: Artificial Intelligence\", ], long_description=readme, long_description_content_type=\"text/markdown\",", "Scientific/Engineering :: Artificial Intelligence\", ], long_description=readme, long_description_content_type=\"text/markdown\", setup_requires=[ \"setuptools>=18.0\", ],", "readme = f.read() setup( name=\"dpr\", version=\"0.1.0\", description=\"Facebook AI Research Open", "Approved :: MIT License\", \"Programming Language :: Python :: 3.6\",", "python3 # Copyright (c) Facebook, Inc. and its affiliates. #", "classifiers=[ \"Intended Audience :: Science/Research\", \"License :: OSI Approved ::", "(c) Facebook, Inc. and its affiliates. # # This source", ":: Scientific/Engineering :: Artificial Intelligence\", ], long_description=readme, long_description_content_type=\"text/markdown\", setup_requires=[ \"setuptools>=18.0\",", ":: Artificial Intelligence\", ], long_description=readme, long_description_content_type=\"text/markdown\", setup_requires=[ \"setuptools>=18.0\", ], install_requires=[", "long_description=readme, long_description_content_type=\"text/markdown\", setup_requires=[ \"setuptools>=18.0\", ], install_requires=[ \"cython\", \"faiss-cpu>=1.6.1\", \"filelock\", \"numpy\",", "this source tree. from setuptools import setup with open(\"README.md\") as", "is licensed under the MIT license found in the #", "the # LICENSE file in the root directory of this", "Intelligence\", ], long_description=readme, long_description_content_type=\"text/markdown\", setup_requires=[ \"setuptools>=18.0\", ], install_requires=[ \"cython\", \"faiss-cpu>=1.6.1\",", "source tree. from setuptools import setup with open(\"README.md\") as f:", "open(\"README.md\") as f: readme = f.read() setup( name=\"dpr\", version=\"0.1.0\", description=\"Facebook", "\"Programming Language :: Python :: 3.6\", \"Topic :: Scientific/Engineering ::", "# Copyright (c) Facebook, Inc. and its affiliates. # #", "tree. from setuptools import setup with open(\"README.md\") as f: readme", "\"License :: OSI Approved :: MIT License\", \"Programming Language ::", "Artificial Intelligence\", ], long_description=readme, long_description_content_type=\"text/markdown\", setup_requires=[ \"setuptools>=18.0\", ], install_requires=[ \"cython\",", "This source code is licensed under the MIT license found", "the root directory of this source tree. from setuptools import", "\"Intended Audience :: Science/Research\", \"License :: OSI Approved :: MIT", "Language :: Python :: 3.6\", \"Topic :: Scientific/Engineering :: Artificial", "\"setuptools>=18.0\", ], install_requires=[ \"cython\", \"faiss-cpu>=1.6.1\", \"filelock\", \"numpy\", \"regex\", \"torch>=1.2.0\", \"transformers>=3.0.0,<3.1.0\",", "\"faiss-cpu>=1.6.1\", \"filelock\", \"numpy\", \"regex\", \"torch>=1.2.0\", \"transformers>=3.0.0,<3.1.0\", \"tqdm>=4.27\", \"wget\", \"spacy>=2.1.8\", ],", "code is licensed under the MIT license found in the", "source code is licensed under the MIT license found in", "Facebook, Inc. and its affiliates. # # This source code", "licensed under the MIT license found in the # LICENSE", "setuptools import setup with open(\"README.md\") as f: readme = f.read()", "Domain Q&A Toolkit\", url=\"https://github.com/facebookresearch/DPR/\", classifiers=[ \"Intended Audience :: Science/Research\", \"License", "f: readme = f.read() setup( name=\"dpr\", version=\"0.1.0\", description=\"Facebook AI Research", "Audience :: Science/Research\", \"License :: OSI Approved :: MIT License\",", "\"cython\", \"faiss-cpu>=1.6.1\", \"filelock\", \"numpy\", \"regex\", \"torch>=1.2.0\", \"transformers>=3.0.0,<3.1.0\", \"tqdm>=4.27\", \"wget\", \"spacy>=2.1.8\",", "# # This source code is licensed under the MIT", "version=\"0.1.0\", description=\"Facebook AI Research Open Domain Q&A Toolkit\", url=\"https://github.com/facebookresearch/DPR/\", classifiers=[", ":: OSI Approved :: MIT License\", \"Programming Language :: Python", "MIT license found in the # LICENSE file in the", "affiliates. # # This source code is licensed under the", "Inc. and its affiliates. # # This source code is", "Open Domain Q&A Toolkit\", url=\"https://github.com/facebookresearch/DPR/\", classifiers=[ \"Intended Audience :: Science/Research\",", ":: Science/Research\", \"License :: OSI Approved :: MIT License\", \"Programming", "# This source code is licensed under the MIT license", "long_description_content_type=\"text/markdown\", setup_requires=[ \"setuptools>=18.0\", ], install_requires=[ \"cython\", \"faiss-cpu>=1.6.1\", \"filelock\", \"numpy\", \"regex\",", "setup with open(\"README.md\") as f: readme = f.read() setup( name=\"dpr\",", "as f: readme = f.read() setup( name=\"dpr\", version=\"0.1.0\", description=\"Facebook AI", "], install_requires=[ \"cython\", \"faiss-cpu>=1.6.1\", \"filelock\", \"numpy\", \"regex\", \"torch>=1.2.0\", \"transformers>=3.0.0,<3.1.0\", \"tqdm>=4.27\",", "with open(\"README.md\") as f: readme = f.read() setup( name=\"dpr\", version=\"0.1.0\"," ]
[ "@license: Apache Licence @contact: <EMAIL> @site: @software: PyCharm @time: 2019/9/12", "from operator import itemgetter import time from collections import OrderedDict", "keys = list(od.keys()) first_v = od[keys[0]] last_v = od[keys[-1]] k_range_len", "BIG_LIST_86 class Solution: \"\"\" 输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] 输出: [20,24] \"\"\"", "od[this_tag] = k_tagged_merged_list[i][0] tags = od.keys() # print('len_k_dque-->', len(k_dque)) #", "import BIG_LIST_86 class Solution: \"\"\" 输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] 输出: [20,24]", "= list(od.keys()) first_v = od[keys[0]] last_v = od[keys[-1]] k_range_len =", "= od.keys() # print('len_k_dque-->', len(k_dque)) # print('len_k_dque_tags-->', len(k_dque_tags)) if len(tags)", "i = 0 while i < tot_len: this_tag = k_tagged_merged_list[i][1]", "hard.smallest_range.srcs.big_2d_list import BIG_LIST_85 from hard.smallest_range.srcs.big_2d_list import BIG_LIST_86 class Solution: \"\"\"", "[11]] # nums = [[11,38,83, # 84,84,85,88,89,89,92],[28,61,89],[52,77,79,80,81],[21,25,26,26,26,27],[9,83,85,90],[84,85,87],[26,68,70,71],[36,40,41,42,45],[-34,21],[-28,-28,-23,1,13,21,28,37,37,38],[-74,1,2,22,33,35,43,45],[54,96,98,98,99],[43,54,60,65,71,75],[43,46],[50,50,58,67,69],[7,14,15],[78,80,89,89,90],[35,47,63,69,77,92,94]] # [-74, 1,", "start_time = time.time() k = len(nums) print('k-->', k) k_tagged_merged_list =", "89, 90], [35, 47, 63, 69, 77, 92, 94]] nums", "[0,9,12,20], [5,18,22,30]] 输出: [20,24] \"\"\" def smallestRange(self, nums): start_time =", "[] for i in range(k): row = nums[i] k_tagged_merged_list.extend([(e, i)", "= [[4, 10, 15, 24, 26], [0, 9, 12, 20],", "k) k_tagged_merged_list = [] for i in range(k): row =", "if k_range_len < min_range_len: min_range_len = k_range_len min_range = first_v,", "= first_v, last_v i += 1 print('ending main time:', time.time()", "45], [54, 96, 98, 98, 99], [43, 54, 60, 65,", "92, 94]] nums = BIG_LIST_85 # nums = BIG_LIST_86 min_range", "24, 26], [0, 9, 12, 20], [5, 18, 22, 30]]", "from collections import OrderedDict from hard.smallest_range.srcs.big_2d_list import BIG_LIST_85 from hard.smallest_range.srcs.big_2d_list", "@time: 2019/9/12 20:37 \"\"\" from pprint import pprint as pp", "import pprint as pp from operator import itemgetter import time", "od.pop(this_tag) od[this_tag] = k_tagged_merged_list[i][0] tags = od.keys() # print('len_k_dque-->', len(k_dque))", "tags = od.keys() # print('len_k_dque-->', len(k_dque)) # print('len_k_dque_tags-->', len(k_dque_tags)) if", "print('len_k_dque-->', len(k_dque)) # print('len_k_dque_tags-->', len(k_dque_tags)) if len(tags) == k: keys", "if len(tags) == k: keys = list(od.keys()) first_v = od[keys[0]]", "9, 12, 20], [5, 18, 22, 30]] # nums =", "OrderedDict from hard.smallest_range.srcs.big_2d_list import BIG_LIST_85 from hard.smallest_range.srcs.big_2d_list import BIG_LIST_86 class", "while i < tot_len: this_tag = k_tagged_merged_list[i][1] cur_tag_set = od.keys()", "encoding: utf-8 \"\"\" @version: v1.0 @author: Richard @license: Apache Licence", "len(k_dque_tags)) if len(tags) == k: keys = list(od.keys()) first_v =", "= None min_range_len = int(2e5) # print('min_range_len', min_range_len) tot_len =", "\"\"\" @version: v1.0 @author: Richard @license: Apache Licence @contact: <EMAIL>", "pprint import pprint as pp from operator import itemgetter import", "[43, 46], # [50, 50, 58, 67, 69], [7, 14,", "last_v i += 1 print('ending main time:', time.time() - sort_end_time)", "60, 65, 71, 75], [43, 46], # [50, 50, 58,", "if this_tag in cur_tag_set: od.pop(this_tag) od[this_tag] = k_tagged_merged_list[i][0] tags =", "pp from operator import itemgetter import time from collections import", "Solution() nums = [[4, 10, 15, 24, 26], [0, 9,", "80, 89, 89, 90], [35, 47, 63, 69, 77, 92,", "89, 89, 90], [35, 47, 63, 69, 77, 92, 94]]", "print('k-->', k) k_tagged_merged_list = [] for i in range(k): row", "50, 58, 67, 69], [7, 14, 15], [78, 80, 89,", "import time from collections import OrderedDict from hard.smallest_range.srcs.big_2d_list import BIG_LIST_85", "min_range_len = k_range_len min_range = first_v, last_v i += 1", "14, 15], [78, 80, 89, 89, 90], [35, 47, 63,", "90], [35, 47, 63, 69, 77, 92, 94]] nums =", "@software: PyCharm @time: 2019/9/12 20:37 \"\"\" from pprint import pprint", "s = Solution() nums = [[4, 10, 15, 24, 26],", "time:', time.time() - sort_end_time) return min_range if __name__ == '__main__':", "63, 69, 77, 92, 94]] nums = BIG_LIST_85 # nums", "print('ending main time:', time.time() - sort_end_time) return min_range if __name__", "Richard @license: Apache Licence @contact: <EMAIL> @site: @software: PyCharm @time:", "print('len_k_dque_tags-->', len(k_dque_tags)) if len(tags) == k: keys = list(od.keys()) first_v", "= Solution() nums = [[4, 10, 15, 24, 26], [0,", "from hard.smallest_range.srcs.big_2d_list import BIG_LIST_85 from hard.smallest_range.srcs.big_2d_list import BIG_LIST_86 class Solution:", "Solution: \"\"\" 输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] 输出: [20,24] \"\"\" def smallestRange(self,", "= k_tagged_merged_list[i][1] cur_tag_set = od.keys() if this_tag in cur_tag_set: od.pop(this_tag)", "first_v, last_v i += 1 print('ending main time:', time.time() -", "1 print('ending main time:', time.time() - sort_end_time) return min_range if", "for i in range(k): row = nums[i] k_tagged_merged_list.extend([(e, i) for", "in row]) k_tagged_merged_list.sort(key=itemgetter(0)) sort_end_time = time.time() print('sorting time:', sort_end_time -", "nums): start_time = time.time() k = len(nums) print('k-->', k) k_tagged_merged_list", "= len(k_tagged_merged_list) # print('tot_len', tot_len) i = 0 while i", "= od[keys[-1]] k_range_len = last_v - first_v if k_range_len <", "i) for e in row]) k_tagged_merged_list.sort(key=itemgetter(0)) sort_end_time = time.time() print('sorting", "min_range = first_v, last_v i += 1 print('ending main time:',", "= last_v - first_v if k_range_len < min_range_len: min_range_len =", "[[4, 10, 15, 24, 26], [0, 9, 12, 20], [5,", "@author: Richard @license: Apache Licence @contact: <EMAIL> @site: @software: PyCharm", "# nums = [[10], [11]] # nums = [[11,38,83, #", "# encoding: utf-8 \"\"\" @version: v1.0 @author: Richard @license: Apache", "BIG_LIST_85 from hard.smallest_range.srcs.big_2d_list import BIG_LIST_86 class Solution: \"\"\" 输入:[[4,10,15,24,26], [0,9,12,20],", "nums = [[11,38,83, # 84,84,85,88,89,89,92],[28,61,89],[52,77,79,80,81],[21,25,26,26,26,27],[9,83,85,90],[84,85,87],[26,68,70,71],[36,40,41,42,45],[-34,21],[-28,-28,-23,1,13,21,28,37,37,38],[-74,1,2,22,33,35,43,45],[54,96,98,98,99],[43,54,60,65,71,75],[43,46],[50,50,58,67,69],[7,14,15],[78,80,89,89,90],[35,47,63,69,77,92,94]] # [-74, 1, 2, 22,", "= k_tagged_merged_list[i][0] tags = od.keys() # print('len_k_dque-->', len(k_dque)) # print('len_k_dque_tags-->',", "= k_range_len min_range = first_v, last_v i += 1 print('ending", "94]] nums = BIG_LIST_85 # nums = BIG_LIST_86 min_range =", "96, 98, 98, 99], [43, 54, 60, 65, 71, 75],", "2019/9/12 20:37 \"\"\" from pprint import pprint as pp from", "k: keys = list(od.keys()) first_v = od[keys[0]] last_v = od[keys[-1]]", "# nums = [[11,38,83, # 84,84,85,88,89,89,92],[28,61,89],[52,77,79,80,81],[21,25,26,26,26,27],[9,83,85,90],[84,85,87],[26,68,70,71],[36,40,41,42,45],[-34,21],[-28,-28,-23,1,13,21,28,37,37,38],[-74,1,2,22,33,35,43,45],[54,96,98,98,99],[43,54,60,65,71,75],[43,46],[50,50,58,67,69],[7,14,15],[78,80,89,89,90],[35,47,63,69,77,92,94]] # [-74, 1, 2,", "import BIG_LIST_85 from hard.smallest_range.srcs.big_2d_list import BIG_LIST_86 class Solution: \"\"\" 输入:[[4,10,15,24,26],", "sort_end_time - start_time) # print(k_tagged_merged_list) od = OrderedDict() min_range =", "from hard.smallest_range.srcs.big_2d_list import BIG_LIST_86 class Solution: \"\"\" 输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]", "15, 24, 26], [0, 9, 12, 20], [5, 18, 22,", "def smallestRange(self, nums): start_time = time.time() k = len(nums) print('k-->',", "k_tagged_merged_list.extend([(e, i) for e in row]) k_tagged_merged_list.sort(key=itemgetter(0)) sort_end_time = time.time()", "输出: [20,24] \"\"\" def smallestRange(self, nums): start_time = time.time() k", "len(nums) print('k-->', k) k_tagged_merged_list = [] for i in range(k):", "= int(2e5) # print('min_range_len', min_range_len) tot_len = len(k_tagged_merged_list) # print('tot_len',", "[-74, 1, 2, 22, 33, 35, 43, 45], [54, 96,", "[[10], [11]] # nums = [[11,38,83, # 84,84,85,88,89,89,92],[28,61,89],[52,77,79,80,81],[21,25,26,26,26,27],[9,83,85,90],[84,85,87],[26,68,70,71],[36,40,41,42,45],[-34,21],[-28,-28,-23,1,13,21,28,37,37,38],[-74,1,2,22,33,35,43,45],[54,96,98,98,99],[43,54,60,65,71,75],[43,46],[50,50,58,67,69],[7,14,15],[78,80,89,89,90],[35,47,63,69,77,92,94]] # [-74,", "time.time() print('sorting time:', sort_end_time - start_time) # print(k_tagged_merged_list) od =", "len(k_tagged_merged_list) # print('tot_len', tot_len) i = 0 while i <", "- start_time) # print(k_tagged_merged_list) od = OrderedDict() min_range = None", "od.keys() if this_tag in cur_tag_set: od.pop(this_tag) od[this_tag] = k_tagged_merged_list[i][0] tags", "20], [5, 18, 22, 30]] # nums = [[10], [11]]", "[7, 14, 15], [78, 80, 89, 89, 90], [35, 47,", "i in range(k): row = nums[i] k_tagged_merged_list.extend([(e, i) for e", "time:', sort_end_time - start_time) # print(k_tagged_merged_list) od = OrderedDict() min_range", "= time.time() print('sorting time:', sort_end_time - start_time) # print(k_tagged_merged_list) od", "this_tag in cur_tag_set: od.pop(this_tag) od[this_tag] = k_tagged_merged_list[i][0] tags = od.keys()", "# [-74, 1, 2, 22, 33, 35, 43, 45], [54,", "len(tags) == k: keys = list(od.keys()) first_v = od[keys[0]] last_v", "min_range_len = int(2e5) # print('min_range_len', min_range_len) tot_len = len(k_tagged_merged_list) #", "[35, 47, 63, 69, 77, 92, 94]] nums = BIG_LIST_85", "33, 35, 43, 45], [54, 96, 98, 98, 99], [43,", "= OrderedDict() min_range = None min_range_len = int(2e5) # print('min_range_len',", "last_v = od[keys[-1]] k_range_len = last_v - first_v if k_range_len", "26], [0, 9, 12, 20], [5, 18, 22, 30]] #", "int(2e5) # print('min_range_len', min_range_len) tot_len = len(k_tagged_merged_list) # print('tot_len', tot_len)", "k_tagged_merged_list[i][1] cur_tag_set = od.keys() if this_tag in cur_tag_set: od.pop(this_tag) od[this_tag]", "min_range = None min_range_len = int(2e5) # print('min_range_len', min_range_len) tot_len", "< tot_len: this_tag = k_tagged_merged_list[i][1] cur_tag_set = od.keys() if this_tag", "10, 15, 24, 26], [0, 9, 12, 20], [5, 18,", "# print('len_k_dque-->', len(k_dque)) # print('len_k_dque_tags-->', len(k_dque_tags)) if len(tags) == k:", "71, 75], [43, 46], # [50, 50, 58, 67, 69],", "cur_tag_set = od.keys() if this_tag in cur_tag_set: od.pop(this_tag) od[this_tag] =", "# 84,84,85,88,89,89,92],[28,61,89],[52,77,79,80,81],[21,25,26,26,26,27],[9,83,85,90],[84,85,87],[26,68,70,71],[36,40,41,42,45],[-34,21],[-28,-28,-23,1,13,21,28,37,37,38],[-74,1,2,22,33,35,43,45],[54,96,98,98,99],[43,54,60,65,71,75],[43,46],[50,50,58,67,69],[7,14,15],[78,80,89,89,90],[35,47,63,69,77,92,94]] # [-74, 1, 2, 22, 33, 35, 43,", "= od[keys[0]] last_v = od[keys[-1]] k_range_len = last_v - first_v", "None min_range_len = int(2e5) # print('min_range_len', min_range_len) tot_len = len(k_tagged_merged_list)", "== '__main__': s = Solution() nums = [[4, 10, 15,", "from pprint import pprint as pp from operator import itemgetter", "row]) k_tagged_merged_list.sort(key=itemgetter(0)) sort_end_time = time.time() print('sorting time:', sort_end_time - start_time)", "20:37 \"\"\" from pprint import pprint as pp from operator", "nums = BIG_LIST_85 # nums = BIG_LIST_86 min_range = s.smallestRange(nums)", "= len(nums) print('k-->', k) k_tagged_merged_list = [] for i in", "[43, 54, 60, 65, 71, 75], [43, 46], # [50,", "- sort_end_time) return min_range if __name__ == '__main__': s =", "k = len(nums) print('k-->', k) k_tagged_merged_list = [] for i", "row = nums[i] k_tagged_merged_list.extend([(e, i) for e in row]) k_tagged_merged_list.sort(key=itemgetter(0))", "start_time) # print(k_tagged_merged_list) od = OrderedDict() min_range = None min_range_len", "len(k_dque)) # print('len_k_dque_tags-->', len(k_dque_tags)) if len(tags) == k: keys =", "# print('len_k_dque_tags-->', len(k_dque_tags)) if len(tags) == k: keys = list(od.keys())", "18, 22, 30]] # nums = [[10], [11]] # nums", "[[11,38,83, # 84,84,85,88,89,89,92],[28,61,89],[52,77,79,80,81],[21,25,26,26,26,27],[9,83,85,90],[84,85,87],[26,68,70,71],[36,40,41,42,45],[-34,21],[-28,-28,-23,1,13,21,28,37,37,38],[-74,1,2,22,33,35,43,45],[54,96,98,98,99],[43,54,60,65,71,75],[43,46],[50,50,58,67,69],[7,14,15],[78,80,89,89,90],[35,47,63,69,77,92,94]] # [-74, 1, 2, 22, 33, 35,", "99], [43, 54, 60, 65, 71, 75], [43, 46], #", "< min_range_len: min_range_len = k_range_len min_range = first_v, last_v i", "tot_len) i = 0 while i < tot_len: this_tag =", "[50, 50, 58, 67, 69], [7, 14, 15], [78, 80,", "\"\"\" from pprint import pprint as pp from operator import", "= [[11,38,83, # 84,84,85,88,89,89,92],[28,61,89],[52,77,79,80,81],[21,25,26,26,26,27],[9,83,85,90],[84,85,87],[26,68,70,71],[36,40,41,42,45],[-34,21],[-28,-28,-23,1,13,21,28,37,37,38],[-74,1,2,22,33,35,43,45],[54,96,98,98,99],[43,54,60,65,71,75],[43,46],[50,50,58,67,69],[7,14,15],[78,80,89,89,90],[35,47,63,69,77,92,94]] # [-74, 1, 2, 22, 33,", "77, 92, 94]] nums = BIG_LIST_85 # nums = BIG_LIST_86", "od.keys() # print('len_k_dque-->', len(k_dque)) # print('len_k_dque_tags-->', len(k_dque_tags)) if len(tags) ==", "as pp from operator import itemgetter import time from collections", "if __name__ == '__main__': s = Solution() nums = [[4,", "smallestRange(self, nums): start_time = time.time() k = len(nums) print('k-->', k)", "v1.0 @author: Richard @license: Apache Licence @contact: <EMAIL> @site: @software:", "k_tagged_merged_list.sort(key=itemgetter(0)) sort_end_time = time.time() print('sorting time:', sort_end_time - start_time) #", "k_range_len < min_range_len: min_range_len = k_range_len min_range = first_v, last_v", "# print('tot_len', tot_len) i = 0 while i < tot_len:", "47, 63, 69, 77, 92, 94]] nums = BIG_LIST_85 #", "__name__ == '__main__': s = Solution() nums = [[4, 10,", "sort_end_time) return min_range if __name__ == '__main__': s = Solution()", "1, 2, 22, 33, 35, 43, 45], [54, 96, 98,", "first_v = od[keys[0]] last_v = od[keys[-1]] k_range_len = last_v -", "range(k): row = nums[i] k_tagged_merged_list.extend([(e, i) for e in row])", "Licence @contact: <EMAIL> @site: @software: PyCharm @time: 2019/9/12 20:37 \"\"\"", "2, 22, 33, 35, 43, 45], [54, 96, 98, 98,", "hard.smallest_range.srcs.big_2d_list import BIG_LIST_86 class Solution: \"\"\" 输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] 输出:", "pprint as pp from operator import itemgetter import time from", "+= 1 print('ending main time:', time.time() - sort_end_time) return min_range", "import itemgetter import time from collections import OrderedDict from hard.smallest_range.srcs.big_2d_list", "[54, 96, 98, 98, 99], [43, 54, 60, 65, 71,", "Apache Licence @contact: <EMAIL> @site: @software: PyCharm @time: 2019/9/12 20:37", "- first_v if k_range_len < min_range_len: min_range_len = k_range_len min_range", "min_range_len: min_range_len = k_range_len min_range = first_v, last_v i +=", "'__main__': s = Solution() nums = [[4, 10, 15, 24,", "time from collections import OrderedDict from hard.smallest_range.srcs.big_2d_list import BIG_LIST_85 from", "35, 43, 45], [54, 96, 98, 98, 99], [43, 54,", "for e in row]) k_tagged_merged_list.sort(key=itemgetter(0)) sort_end_time = time.time() print('sorting time:',", "= od.keys() if this_tag in cur_tag_set: od.pop(this_tag) od[this_tag] = k_tagged_merged_list[i][0]", "84,84,85,88,89,89,92],[28,61,89],[52,77,79,80,81],[21,25,26,26,26,27],[9,83,85,90],[84,85,87],[26,68,70,71],[36,40,41,42,45],[-34,21],[-28,-28,-23,1,13,21,28,37,37,38],[-74,1,2,22,33,35,43,45],[54,96,98,98,99],[43,54,60,65,71,75],[43,46],[50,50,58,67,69],[7,14,15],[78,80,89,89,90],[35,47,63,69,77,92,94]] # [-74, 1, 2, 22, 33, 35, 43, 45],", "54, 60, 65, 71, 75], [43, 46], # [50, 50,", "nums[i] k_tagged_merged_list.extend([(e, i) for e in row]) k_tagged_merged_list.sort(key=itemgetter(0)) sort_end_time =", "list(od.keys()) first_v = od[keys[0]] last_v = od[keys[-1]] k_range_len = last_v", "return min_range if __name__ == '__main__': s = Solution() nums", "69, 77, 92, 94]] nums = BIG_LIST_85 # nums =", "[20,24] \"\"\" def smallestRange(self, nums): start_time = time.time() k =", "utf-8 \"\"\" @version: v1.0 @author: Richard @license: Apache Licence @contact:", "print('sorting time:', sort_end_time - start_time) # print(k_tagged_merged_list) od = OrderedDict()", "print('min_range_len', min_range_len) tot_len = len(k_tagged_merged_list) # print('tot_len', tot_len) i =", "this_tag = k_tagged_merged_list[i][1] cur_tag_set = od.keys() if this_tag in cur_tag_set:", "main time:', time.time() - sort_end_time) return min_range if __name__ ==", "tot_len: this_tag = k_tagged_merged_list[i][1] cur_tag_set = od.keys() if this_tag in", "print('tot_len', tot_len) i = 0 while i < tot_len: this_tag", "time.time() - sort_end_time) return min_range if __name__ == '__main__': s", "98, 99], [43, 54, 60, 65, 71, 75], [43, 46],", "PyCharm @time: 2019/9/12 20:37 \"\"\" from pprint import pprint as", "k_tagged_merged_list[i][0] tags = od.keys() # print('len_k_dque-->', len(k_dque)) # print('len_k_dque_tags-->', len(k_dque_tags))", "print(k_tagged_merged_list) od = OrderedDict() min_range = None min_range_len = int(2e5)", "67, 69], [7, 14, 15], [78, 80, 89, 89, 90],", "= 0 while i < tot_len: this_tag = k_tagged_merged_list[i][1] cur_tag_set", "operator import itemgetter import time from collections import OrderedDict from", "time.time() k = len(nums) print('k-->', k) k_tagged_merged_list = [] for", "import OrderedDict from hard.smallest_range.srcs.big_2d_list import BIG_LIST_85 from hard.smallest_range.srcs.big_2d_list import BIG_LIST_86", "\"\"\" def smallestRange(self, nums): start_time = time.time() k = len(nums)", "= nums[i] k_tagged_merged_list.extend([(e, i) for e in row]) k_tagged_merged_list.sort(key=itemgetter(0)) sort_end_time", "@version: v1.0 @author: Richard @license: Apache Licence @contact: <EMAIL> @site:", "69], [7, 14, 15], [78, 80, 89, 89, 90], [35,", "# print(k_tagged_merged_list) od = OrderedDict() min_range = None min_range_len =", "sort_end_time = time.time() print('sorting time:', sort_end_time - start_time) # print(k_tagged_merged_list)", "= [] for i in range(k): row = nums[i] k_tagged_merged_list.extend([(e,", "k_range_len = last_v - first_v if k_range_len < min_range_len: min_range_len", "nums = [[4, 10, 15, 24, 26], [0, 9, 12,", "[78, 80, 89, 89, 90], [35, 47, 63, 69, 77,", "58, 67, 69], [7, 14, 15], [78, 80, 89, 89,", "# print('min_range_len', min_range_len) tot_len = len(k_tagged_merged_list) # print('tot_len', tot_len) i", "输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] 输出: [20,24] \"\"\" def smallestRange(self, nums): start_time", "12, 20], [5, 18, 22, 30]] # nums = [[10],", "== k: keys = list(od.keys()) first_v = od[keys[0]] last_v =", "22, 30]] # nums = [[10], [11]] # nums =", "[5,18,22,30]] 输出: [20,24] \"\"\" def smallestRange(self, nums): start_time = time.time()", "od = OrderedDict() min_range = None min_range_len = int(2e5) #", "i < tot_len: this_tag = k_tagged_merged_list[i][1] cur_tag_set = od.keys() if", "[0, 9, 12, 20], [5, 18, 22, 30]] # nums", "nums = [[10], [11]] # nums = [[11,38,83, # 84,84,85,88,89,89,92],[28,61,89],[52,77,79,80,81],[21,25,26,26,26,27],[9,83,85,90],[84,85,87],[26,68,70,71],[36,40,41,42,45],[-34,21],[-28,-28,-23,1,13,21,28,37,37,38],[-74,1,2,22,33,35,43,45],[54,96,98,98,99],[43,54,60,65,71,75],[43,46],[50,50,58,67,69],[7,14,15],[78,80,89,89,90],[35,47,63,69,77,92,94]]", "\"\"\" 输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] 输出: [20,24] \"\"\" def smallestRange(self, nums):", "@site: @software: PyCharm @time: 2019/9/12 20:37 \"\"\" from pprint import", "43, 45], [54, 96, 98, 98, 99], [43, 54, 60,", "= time.time() k = len(nums) print('k-->', k) k_tagged_merged_list = []", "last_v - first_v if k_range_len < min_range_len: min_range_len = k_range_len", "collections import OrderedDict from hard.smallest_range.srcs.big_2d_list import BIG_LIST_85 from hard.smallest_range.srcs.big_2d_list import", "= [[10], [11]] # nums = [[11,38,83, # 84,84,85,88,89,89,92],[28,61,89],[52,77,79,80,81],[21,25,26,26,26,27],[9,83,85,90],[84,85,87],[26,68,70,71],[36,40,41,42,45],[-34,21],[-28,-28,-23,1,13,21,28,37,37,38],[-74,1,2,22,33,35,43,45],[54,96,98,98,99],[43,54,60,65,71,75],[43,46],[50,50,58,67,69],[7,14,15],[78,80,89,89,90],[35,47,63,69,77,92,94]] #", "= BIG_LIST_85 # nums = BIG_LIST_86 min_range = s.smallestRange(nums) print(min_range)", "# [50, 50, 58, 67, 69], [7, 14, 15], [78,", "[5, 18, 22, 30]] # nums = [[10], [11]] #", "od[keys[0]] last_v = od[keys[-1]] k_range_len = last_v - first_v if", "e in row]) k_tagged_merged_list.sort(key=itemgetter(0)) sort_end_time = time.time() print('sorting time:', sort_end_time", "k_tagged_merged_list = [] for i in range(k): row = nums[i]", "min_range_len) tot_len = len(k_tagged_merged_list) # print('tot_len', tot_len) i = 0", "in cur_tag_set: od.pop(this_tag) od[this_tag] = k_tagged_merged_list[i][0] tags = od.keys() #", "22, 33, 35, 43, 45], [54, 96, 98, 98, 99],", "cur_tag_set: od.pop(this_tag) od[this_tag] = k_tagged_merged_list[i][0] tags = od.keys() # print('len_k_dque-->',", "75], [43, 46], # [50, 50, 58, 67, 69], [7,", "k_range_len min_range = first_v, last_v i += 1 print('ending main", "i += 1 print('ending main time:', time.time() - sort_end_time) return", "46], # [50, 50, 58, 67, 69], [7, 14, 15],", "65, 71, 75], [43, 46], # [50, 50, 58, 67,", "<EMAIL> @site: @software: PyCharm @time: 2019/9/12 20:37 \"\"\" from pprint", "OrderedDict() min_range = None min_range_len = int(2e5) # print('min_range_len', min_range_len)", "first_v if k_range_len < min_range_len: min_range_len = k_range_len min_range =", "98, 98, 99], [43, 54, 60, 65, 71, 75], [43,", "@contact: <EMAIL> @site: @software: PyCharm @time: 2019/9/12 20:37 \"\"\" from", "in range(k): row = nums[i] k_tagged_merged_list.extend([(e, i) for e in", "od[keys[-1]] k_range_len = last_v - first_v if k_range_len < min_range_len:", "30]] # nums = [[10], [11]] # nums = [[11,38,83,", "itemgetter import time from collections import OrderedDict from hard.smallest_range.srcs.big_2d_list import", "min_range if __name__ == '__main__': s = Solution() nums =", "15], [78, 80, 89, 89, 90], [35, 47, 63, 69,", "tot_len = len(k_tagged_merged_list) # print('tot_len', tot_len) i = 0 while", "0 while i < tot_len: this_tag = k_tagged_merged_list[i][1] cur_tag_set =", "class Solution: \"\"\" 输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] 输出: [20,24] \"\"\" def" ]
[ "states are equivalent. Uses equivalent_states defined in the S3Bucket class.", "blob_name (str): Object name (Required) file_obj (str): file name for", "= self.client.get_bucket(self.bucket_name) return bucket except exceptions.NotFound: return {\"status\": \"missing\"} def", "State.running else: self.state = State.terminated self.current_state_definition = self.desired_state_definition def download_object(self,", "self.client.get_bucket(self.bucket_name) return bucket except exceptions.NotFound: return {\"status\": \"missing\"} def _terminate(self):", "Storage(GCPResource): \"\"\" This is the implementation of Google's storage service.", "put_object (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_file(file_obj, **kwargs)", "(str): Object Key name (Required) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return", "(Required) **kwargs: Options for boto3 put_object (optional) \"\"\" bucket =", "\"\"\" full_status = self.get_status() if full_status: if isinstance(full_status, self.resource.Bucket): self.state", "(str): Object name (Required) file_obj (str): file name for the", "is_state_equivalent(self, state1, state2): \"\"\" Determines if states are equivalent. Uses", "object to put into the bucket (Required) **kwargs: Options for", "blob_name (str): Object Key name (Required) file (file): the file", "0, State.terminated: 0 } UNIQUE_KEYS = [\"gcp_resource.name\"] def __init__(self, particle_definition):", "return list(bucket.list_blobs(**kwargs)) def put_object(self, blob_name, file_obj, **kwargs): \"\"\" Puts an", "\"\"\" return self.client.bucket(bucket_name=self.bucket_name).delete() def _start(self): \"\"\" Creates the storage bucket", "1, State.stopped: 0, State.terminated: 0 } UNIQUE_KEYS = [\"gcp_resource.name\"] def", "state. \"\"\" full_status = self.get_status() if full_status: if isinstance(full_status, self.resource.Bucket):", "put into the bucket (Required) **kwargs: Options for boto3 put_object", "def __init__(self, particle_definition): super(Storage, self).__init__(particle_definition=particle_definition, resource=storage) self.bucket_name = self.desired_state_definition[\"name\"] self._set_unique_keys()", "Args: blob_name (str): Object Key name (Required) \"\"\" bucket =", "_set_unique_keys(self): \"\"\" Logic that sets keys from state definition that", "bucket Returns: response of gcp delete \"\"\" return self.client.bucket(bucket_name=self.bucket_name).delete() def", "State.terminated self.current_state_definition = self.desired_state_definition def download_object(self, blob_name, file_obj, **kwargs): \"\"\"", "exceptions.NotFound: return {\"status\": \"missing\"} def _terminate(self): \"\"\" Deletes the storage", "used to uniquely identify the storage bucket \"\"\" self.unique_keys =", "def delete_object(self, blob_name): \"\"\" Deletes an object in the storage", "Not Implemented \"\"\" pass def is_state_equivalent(self, state1, state2): \"\"\" Determines", "return self.resource.Blob(blob_name, bucket).upload_from_file(file_obj, **kwargs) def put_file(self, blob_name, file, **kwargs): \"\"\"", "if isinstance(full_status, self.resource.Bucket): self.state = State.running else: self.state = State.terminated", "sets the current state. \"\"\" full_status = self.get_status() if full_status:", "bucket = self.client.get_bucket(self.bucket_name) return list(bucket.list_blobs(**kwargs)) def put_object(self, blob_name, file_obj, **kwargs):", "create_bucket \"\"\" # create_definition = pcf_util.keep_and_replace_keys(self.get_desired_state_definition(), # S3Bucket.START_PARAMS) return self.client.bucket(bucket_name=self.bucket_name).create()", "file_obj (str): file name for the download (Required) **kwargs: Options", "put into the bucket (Required) **kwargs: Options for boto3 upload_file", "that are used to uniquely identify the storage bucket \"\"\"", "= self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_filename(file, **kwargs) def _update(self): \"\"\" Not", "self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).download_file(file_obj, **kwargs) def delete_object(self, blob_name): \"\"\" Deletes", "# S3Bucket.START_PARAMS) return self.client.bucket(bucket_name=self.bucket_name).create() def _stop(self): \"\"\" S3 bucket does", "Args: **kwargs: Options for boto3 list_objects (optional) \"\"\" bucket =", "full_status = self.get_status() if full_status: if isinstance(full_status, self.resource.Bucket): self.state =", "except exceptions.NotFound: return {\"status\": \"missing\"} def _terminate(self): \"\"\" Deletes the", "in the storage bucket. Args: **kwargs: Options for boto3 list_objects", "import GCPResource from pcf.core import State import logging from google.cloud", "that sets keys from state definition that are used to", "self.client.bucket(bucket_name=self.bucket_name).delete() def _start(self): \"\"\" Creates the storage bucket Returns: response", "bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_filename(file, **kwargs) def _update(self): \"\"\"", "state2): \"\"\" Determines if states are equivalent. Uses equivalent_states defined", "the bucket (Required) **kwargs: Options for boto3 upload_file (optional) \"\"\"", "return self.terminate() def sync_state(self): \"\"\" Calls get status and then", "file_obj (object): the object to put into the bucket (Required)", "of Google's storage service. \"\"\" flavor = \"storage\" equivalent_states =", "self.terminate() def sync_state(self): \"\"\" Calls get status and then sets", "for boto3 get_object (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name,", "bucket. Args: **kwargs: Options for boto3 list_objects (optional) \"\"\" bucket", "list_objects (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return list(bucket.list_blobs(**kwargs)) def put_object(self,", "bucket. Args: blob_name (str): Object Key name (Required) file (file):", "terminate. \"\"\" return self.terminate() def sync_state(self): \"\"\" Calls get status", "download_object(self, blob_name, file_obj, **kwargs): \"\"\" Downloads a file from the", "the S3Bucket class. Args: state1 (State): state1 (State): Returns: bool", "Object Key name (Required) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return bucket.delete_blob(blob_name)", "are equivalent. Uses equivalent_states defined in the S3Bucket class. Args:", "bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).download_file(file_obj, **kwargs) def delete_object(self, blob_name):", "for boto3 list_objects (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return list(bucket.list_blobs(**kwargs))", "into the bucket (Required) **kwargs: Options for boto3 upload_file (optional)", "return self.resource.Blob(blob_name, bucket).upload_from_filename(file, **kwargs) def _update(self): \"\"\" Not Implemented \"\"\"", "blob_name): \"\"\" Deletes an object in the storage bucket. Args:", "status and then sets the current state. \"\"\" full_status =", "in the S3Bucket class. Args: state1 (State): state1 (State): Returns:", "implementation of Google's storage service. \"\"\" flavor = \"storage\" equivalent_states", "keys from state definition that are used to uniquely identify", "\"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_filename(file, **kwargs) def _update(self):", "file_obj, **kwargs): \"\"\" Puts an object in the S3 bucket.", "S3 bucket does not have a stopped state so it", "from google.cloud import storage from google.cloud import exceptions logger =", "put_object(self, blob_name, file_obj, **kwargs): \"\"\" Puts an object in the", "Key name (Required) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return bucket.delete_blob(blob_name) def", "\"\"\" return self.terminate() def sync_state(self): \"\"\" Calls get status and", "response of create_bucket \"\"\" # create_definition = pcf_util.keep_and_replace_keys(self.get_desired_state_definition(), # S3Bucket.START_PARAMS)", "self.unique_keys = Storage.UNIQUE_KEYS def get_status(self): \"\"\" Determines if the bucket", "= pcf_util.keep_and_replace_keys(self.get_desired_state_definition(), # S3Bucket.START_PARAMS) return self.client.bucket(bucket_name=self.bucket_name).create() def _stop(self): \"\"\" S3", "a file in the S3 bucket. Args: blob_name (str): Object", "self.resource.Blob(blob_name, bucket).upload_from_filename(file, **kwargs) def _update(self): \"\"\" Not Implemented \"\"\" pass", "self.state = State.terminated self.current_state_definition = self.desired_state_definition def download_object(self, blob_name, file_obj,", "bucket exists Returns: status (dict) \"\"\" try: bucket = self.client.get_bucket(self.bucket_name)", "file_obj, **kwargs): \"\"\" Downloads a file from the S3 bucket.", "status (dict) \"\"\" try: bucket = self.client.get_bucket(self.bucket_name) return bucket except", "bucket except exceptions.NotFound: return {\"status\": \"missing\"} def _terminate(self): \"\"\" Deletes", "__init__(self, particle_definition): super(Storage, self).__init__(particle_definition=particle_definition, resource=storage) self.bucket_name = self.desired_state_definition[\"name\"] self._set_unique_keys() def", "return self.client.bucket(bucket_name=self.bucket_name).delete() def _start(self): \"\"\" Creates the storage bucket Returns:", "upload_file (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_filename(file, **kwargs)", "bucket (Required) **kwargs: Options for boto3 put_object (optional) \"\"\" bucket", "def download_object(self, blob_name, file_obj, **kwargs): \"\"\" Downloads a file from", "(optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return list(bucket.list_blobs(**kwargs)) def put_object(self, blob_name,", "and then sets the current state. \"\"\" full_status = self.get_status()", "\"\"\" Deletes the storage bucket Returns: response of gcp delete", "(optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_file(file_obj, **kwargs) def", "\"\"\" Lists all objects in the storage bucket. Args: **kwargs:", "create_definition = pcf_util.keep_and_replace_keys(self.get_desired_state_definition(), # S3Bucket.START_PARAMS) return self.client.bucket(bucket_name=self.bucket_name).create() def _stop(self): \"\"\"", "the current state. \"\"\" full_status = self.get_status() if full_status: if", "Returns: response of gcp delete \"\"\" return self.client.bucket(bucket_name=self.bucket_name).delete() def _start(self):", "} UNIQUE_KEYS = [\"gcp_resource.name\"] def __init__(self, particle_definition): super(Storage, self).__init__(particle_definition=particle_definition, resource=storage)", "into the bucket (Required) **kwargs: Options for boto3 put_object (optional)", "Calls get status and then sets the current state. \"\"\"", "\"\"\" Calls get status and then sets the current state.", "uniquely identify the storage bucket \"\"\" self.unique_keys = Storage.UNIQUE_KEYS def", "the storage bucket. Args: blob_name (str): Object Key name (Required)", "\"\"\" Puts a file in the S3 bucket. Args: blob_name", "the S3 bucket. Args: blob_name (str): Object name (Required) file_obj", "Lists all objects in the storage bucket. Args: **kwargs: Options", "\"\"\" Determines if states are equivalent. Uses equivalent_states defined in", "**kwargs): \"\"\" Lists all objects in the storage bucket. Args:", "= State.terminated self.current_state_definition = self.desired_state_definition def download_object(self, blob_name, file_obj, **kwargs):", "GCPResource from pcf.core import State import logging from google.cloud import", "(dict) \"\"\" try: bucket = self.client.get_bucket(self.bucket_name) return bucket except exceptions.NotFound:", "of gcp delete \"\"\" return self.client.bucket(bucket_name=self.bucket_name).delete() def _start(self): \"\"\" Creates", "_start(self): \"\"\" Creates the storage bucket Returns: response of create_bucket", "state1 (State): state1 (State): Returns: bool \"\"\" return Storage.equivalent_states.get(state1) ==", "blob_name (str): Object Key name (Required) file_obj (object): the object", "\"\"\" S3 bucket does not have a stopped state so", "exists Returns: status (dict) \"\"\" try: bucket = self.client.get_bucket(self.bucket_name) return", "bucket does not have a stopped state so it calls", "Object Key name (Required) file (file): the file to put", "get status and then sets the current state. \"\"\" full_status", "self.desired_state_definition[\"name\"] self._set_unique_keys() def _set_unique_keys(self): \"\"\" Logic that sets keys from", "for boto3 upload_file (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name,", "_terminate(self): \"\"\" Deletes the storage bucket Returns: response of gcp", "file to put into the bucket (Required) **kwargs: Options for", "{\"status\": \"missing\"} def _terminate(self): \"\"\" Deletes the storage bucket Returns:", "def is_state_equivalent(self, state1, state2): \"\"\" Determines if states are equivalent.", "bucket).upload_from_file(file_obj, **kwargs) def put_file(self, blob_name, file, **kwargs): \"\"\" Puts a", "self).__init__(particle_definition=particle_definition, resource=storage) self.bucket_name = self.desired_state_definition[\"name\"] self._set_unique_keys() def _set_unique_keys(self): \"\"\" Logic", "the storage bucket. Args: **kwargs: Options for boto3 list_objects (optional)", "get_object (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).download_file(file_obj, **kwargs)", "\"\"\" Determines if the bucket exists Returns: status (dict) \"\"\"", "the implementation of Google's storage service. \"\"\" flavor = \"storage\"", "the bucket (Required) **kwargs: Options for boto3 put_object (optional) \"\"\"", "bucket Returns: response of create_bucket \"\"\" # create_definition = pcf_util.keep_and_replace_keys(self.get_desired_state_definition(),", "it calls terminate. \"\"\" return self.terminate() def sync_state(self): \"\"\" Calls", "the object to put into the bucket (Required) **kwargs: Options", "not have a stopped state so it calls terminate. \"\"\"", "boto3 put_object (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_file(file_obj,", "(Required) **kwargs: Options for boto3 get_object (optional) \"\"\" bucket =", "**kwargs: Options for boto3 get_object (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name)", "google.cloud import exceptions logger = logging.getLogger(__name__) class Storage(GCPResource): \"\"\" This", "S3 bucket. Args: blob_name (str): Object name (Required) file_obj (str):", "then sets the current state. \"\"\" full_status = self.get_status() if", "self.state = State.running else: self.state = State.terminated self.current_state_definition = self.desired_state_definition", "are used to uniquely identify the storage bucket \"\"\" self.unique_keys", "if states are equivalent. Uses equivalent_states defined in the S3Bucket", "\"\"\" Creates the storage bucket Returns: response of create_bucket \"\"\"", "storage from google.cloud import exceptions logger = logging.getLogger(__name__) class Storage(GCPResource):", "logging.getLogger(__name__) class Storage(GCPResource): \"\"\" This is the implementation of Google's", "in the storage bucket. Args: blob_name (str): Object Key name", "State.terminated: 0 } UNIQUE_KEYS = [\"gcp_resource.name\"] def __init__(self, particle_definition): super(Storage,", "Puts an object in the S3 bucket. Args: blob_name (str):", "self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_filename(file, **kwargs) def _update(self): \"\"\" Not Implemented", "bucket. Args: blob_name (str): Object name (Required) file_obj (str): file", "delete \"\"\" return self.client.bucket(bucket_name=self.bucket_name).delete() def _start(self): \"\"\" Creates the storage", "\"\"\" Puts an object in the S3 bucket. Args: blob_name", "(Required) **kwargs: Options for boto3 upload_file (optional) \"\"\" bucket =", "def sync_state(self): \"\"\" Calls get status and then sets the", "a stopped state so it calls terminate. \"\"\" return self.terminate()", "try: bucket = self.client.get_bucket(self.bucket_name) return bucket except exceptions.NotFound: return {\"status\":", "Key name (Required) file (file): the file to put into", "S3 bucket. Args: blob_name (str): Object Key name (Required) file_obj", "get_status(self): \"\"\" Determines if the bucket exists Returns: status (dict)", "if full_status: if isinstance(full_status, self.resource.Bucket): self.state = State.running else: self.state", "State.running: 1, State.stopped: 0, State.terminated: 0 } UNIQUE_KEYS = [\"gcp_resource.name\"]", "(State): state1 (State): Returns: bool \"\"\" return Storage.equivalent_states.get(state1) == Storage.equivalent_states.get(state2)", "response of gcp delete \"\"\" return self.client.bucket(bucket_name=self.bucket_name).delete() def _start(self): \"\"\"", "**kwargs) def delete_object(self, blob_name): \"\"\" Deletes an object in the", "to put into the bucket (Required) **kwargs: Options for boto3", "_stop(self): \"\"\" S3 bucket does not have a stopped state", "Args: blob_name (str): Object name (Required) file_obj (str): file name", "storage bucket. Args: **kwargs: Options for boto3 list_objects (optional) \"\"\"", "= self.client.get_bucket(self.bucket_name) return list(bucket.list_blobs(**kwargs)) def put_object(self, blob_name, file_obj, **kwargs): \"\"\"", "= logging.getLogger(__name__) class Storage(GCPResource): \"\"\" This is the implementation of", "if the bucket exists Returns: status (dict) \"\"\" try: bucket", "Options for boto3 list_objects (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return", "def _update(self): \"\"\" Not Implemented \"\"\" pass def is_state_equivalent(self, state1,", "Returns: status (dict) \"\"\" try: bucket = self.client.get_bucket(self.bucket_name) return bucket", "from pcf.core import State import logging from google.cloud import storage", "Key name (Required) file_obj (object): the object to put into", "bucket. Args: blob_name (str): Object Key name (Required) \"\"\" bucket", "list_objects(self, **kwargs): \"\"\" Lists all objects in the storage bucket.", "file from the S3 bucket. Args: blob_name (str): Object name", "pcf_util.keep_and_replace_keys(self.get_desired_state_definition(), # S3Bucket.START_PARAMS) return self.client.bucket(bucket_name=self.bucket_name).create() def _stop(self): \"\"\" S3 bucket", "from pcf.core.gcp_resource import GCPResource from pcf.core import State import logging", "Deletes an object in the storage bucket. Args: blob_name (str):", "self.client.get_bucket(self.bucket_name) return list(bucket.list_blobs(**kwargs)) def put_object(self, blob_name, file_obj, **kwargs): \"\"\" Puts", "def _start(self): \"\"\" Creates the storage bucket Returns: response of", "**kwargs): \"\"\" Puts a file in the S3 bucket. Args:", "Logic that sets keys from state definition that are used", "**kwargs): \"\"\" Downloads a file from the S3 bucket. Args:", "pcf.core.gcp_resource import GCPResource from pcf.core import State import logging from", "**kwargs: Options for boto3 upload_file (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name)", "class Storage(GCPResource): \"\"\" This is the implementation of Google's storage", "storage bucket \"\"\" self.unique_keys = Storage.UNIQUE_KEYS def get_status(self): \"\"\" Determines", "(object): the object to put into the bucket (Required) **kwargs:", "Puts a file in the S3 bucket. Args: blob_name (str):", "Options for boto3 get_object (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return", "\"\"\" bucket = self.client.get_bucket(self.bucket_name) return list(bucket.list_blobs(**kwargs)) def put_object(self, blob_name, file_obj,", "UNIQUE_KEYS = [\"gcp_resource.name\"] def __init__(self, particle_definition): super(Storage, self).__init__(particle_definition=particle_definition, resource=storage) self.bucket_name", "bucket. Args: blob_name (str): Object Key name (Required) file_obj (object):", "self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_file(file_obj, **kwargs) def put_file(self, blob_name, file, **kwargs):", "**kwargs) def _update(self): \"\"\" Not Implemented \"\"\" pass def is_state_equivalent(self,", "pass def is_state_equivalent(self, state1, state2): \"\"\" Determines if states are", "self.get_status() if full_status: if isinstance(full_status, self.resource.Bucket): self.state = State.running else:", "bucket.delete_blob(blob_name) def list_objects(self, **kwargs): \"\"\" Lists all objects in the", "from state definition that are used to uniquely identify the", "(str): Object Key name (Required) file (file): the file to", "\"\"\" # create_definition = pcf_util.keep_and_replace_keys(self.get_desired_state_definition(), # S3Bucket.START_PARAMS) return self.client.bucket(bucket_name=self.bucket_name).create() def", "self.resource.Blob(blob_name, bucket).upload_from_file(file_obj, **kwargs) def put_file(self, blob_name, file, **kwargs): \"\"\" Puts", "sets keys from state definition that are used to uniquely", "def _stop(self): \"\"\" S3 bucket does not have a stopped", "boto3 list_objects (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return list(bucket.list_blobs(**kwargs)) def", "import storage from google.cloud import exceptions logger = logging.getLogger(__name__) class", "boto3 get_object (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).download_file(file_obj,", "objects in the storage bucket. Args: **kwargs: Options for boto3", "= self.get_status() if full_status: if isinstance(full_status, self.resource.Bucket): self.state = State.running", "from google.cloud import exceptions logger = logging.getLogger(__name__) class Storage(GCPResource): \"\"\"", "\"\"\" Deletes an object in the storage bucket. Args: blob_name", "logging from google.cloud import storage from google.cloud import exceptions logger", "return bucket except exceptions.NotFound: return {\"status\": \"missing\"} def _terminate(self): \"\"\"", "isinstance(full_status, self.resource.Bucket): self.state = State.running else: self.state = State.terminated self.current_state_definition", "\"\"\" pass def is_state_equivalent(self, state1, state2): \"\"\" Determines if states", "= self.desired_state_definition[\"name\"] self._set_unique_keys() def _set_unique_keys(self): \"\"\" Logic that sets keys", "self.current_state_definition = self.desired_state_definition def download_object(self, blob_name, file_obj, **kwargs): \"\"\" Downloads", "for the download (Required) **kwargs: Options for boto3 get_object (optional)", "= { State.running: 1, State.stopped: 0, State.terminated: 0 } UNIQUE_KEYS", "This is the implementation of Google's storage service. \"\"\" flavor", "State.stopped: 0, State.terminated: 0 } UNIQUE_KEYS = [\"gcp_resource.name\"] def __init__(self,", "calls terminate. \"\"\" return self.terminate() def sync_state(self): \"\"\" Calls get", "have a stopped state so it calls terminate. \"\"\" return", "definition that are used to uniquely identify the storage bucket", "<reponame>davidyum/Particle-Cloud-Framework<filename>pcf/particle/gcp/storage/storage.py from pcf.core.gcp_resource import GCPResource from pcf.core import State import", "return bucket.delete_blob(blob_name) def list_objects(self, **kwargs): \"\"\" Lists all objects in", "\"\"\" flavor = \"storage\" equivalent_states = { State.running: 1, State.stopped:", "{ State.running: 1, State.stopped: 0, State.terminated: 0 } UNIQUE_KEYS =", "sync_state(self): \"\"\" Calls get status and then sets the current", "in the S3 bucket. Args: blob_name (str): Object Key name", "resource=storage) self.bucket_name = self.desired_state_definition[\"name\"] self._set_unique_keys() def _set_unique_keys(self): \"\"\" Logic that", "\"\"\" self.unique_keys = Storage.UNIQUE_KEYS def get_status(self): \"\"\" Determines if the", "= State.running else: self.state = State.terminated self.current_state_definition = self.desired_state_definition def", "def _terminate(self): \"\"\" Deletes the storage bucket Returns: response of", "name (Required) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return bucket.delete_blob(blob_name) def list_objects(self,", "list(bucket.list_blobs(**kwargs)) def put_object(self, blob_name, file_obj, **kwargs): \"\"\" Puts an object", "a file from the S3 bucket. Args: blob_name (str): Object", "bucket = self.client.get_bucket(self.bucket_name) return bucket.delete_blob(blob_name) def list_objects(self, **kwargs): \"\"\" Lists", "= self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_file(file_obj, **kwargs) def put_file(self, blob_name, file,", "stopped state so it calls terminate. \"\"\" return self.terminate() def", "State import logging from google.cloud import storage from google.cloud import", "identify the storage bucket \"\"\" self.unique_keys = Storage.UNIQUE_KEYS def get_status(self):", "\"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_file(file_obj, **kwargs) def put_file(self,", "logger = logging.getLogger(__name__) class Storage(GCPResource): \"\"\" This is the implementation", "download (Required) **kwargs: Options for boto3 get_object (optional) \"\"\" bucket", "else: self.state = State.terminated self.current_state_definition = self.desired_state_definition def download_object(self, blob_name,", "\"\"\" Logic that sets keys from state definition that are", "S3 bucket. Args: blob_name (str): Object Key name (Required) file", "(file): the file to put into the bucket (Required) **kwargs:", "return self.resource.Blob(blob_name, bucket).download_file(file_obj, **kwargs) def delete_object(self, blob_name): \"\"\" Deletes an", "import logging from google.cloud import storage from google.cloud import exceptions", "name (Required) file_obj (str): file name for the download (Required)", "Downloads a file from the S3 bucket. Args: blob_name (str):", "self.desired_state_definition def download_object(self, blob_name, file_obj, **kwargs): \"\"\" Downloads a file", "self.client.bucket(bucket_name=self.bucket_name).create() def _stop(self): \"\"\" S3 bucket does not have a", "self.resource.Blob(blob_name, bucket).download_file(file_obj, **kwargs) def delete_object(self, blob_name): \"\"\" Deletes an object", "Options for boto3 put_object (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return", "defined in the S3Bucket class. Args: state1 (State): state1 (State):", "Creates the storage bucket Returns: response of create_bucket \"\"\" #", "\"missing\"} def _terminate(self): \"\"\" Deletes the storage bucket Returns: response", "does not have a stopped state so it calls terminate.", "Object Key name (Required) file_obj (object): the object to put", "from the S3 bucket. Args: blob_name (str): Object name (Required)", "def list_objects(self, **kwargs): \"\"\" Lists all objects in the storage", "boto3 upload_file (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_filename(file,", "Implemented \"\"\" pass def is_state_equivalent(self, state1, state2): \"\"\" Determines if", "particle_definition): super(Storage, self).__init__(particle_definition=particle_definition, resource=storage) self.bucket_name = self.desired_state_definition[\"name\"] self._set_unique_keys() def _set_unique_keys(self):", "the S3 bucket. Args: blob_name (str): Object Key name (Required)", "object in the S3 bucket. Args: blob_name (str): Object Key", "current state. \"\"\" full_status = self.get_status() if full_status: if isinstance(full_status,", "full_status: if isinstance(full_status, self.resource.Bucket): self.state = State.running else: self.state =", "delete_object(self, blob_name): \"\"\" Deletes an object in the storage bucket.", "**kwargs: Options for boto3 list_objects (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name)", "\"storage\" equivalent_states = { State.running: 1, State.stopped: 0, State.terminated: 0", "Deletes the storage bucket Returns: response of gcp delete \"\"\"", "Args: blob_name (str): Object Key name (Required) file (file): the", "def get_status(self): \"\"\" Determines if the bucket exists Returns: status", "storage bucket Returns: response of gcp delete \"\"\" return self.client.bucket(bucket_name=self.bucket_name).delete()", "\"\"\" try: bucket = self.client.get_bucket(self.bucket_name) return bucket except exceptions.NotFound: return", "is the implementation of Google's storage service. \"\"\" flavor =", "so it calls terminate. \"\"\" return self.terminate() def sync_state(self): \"\"\"", "for boto3 put_object (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name,", "[\"gcp_resource.name\"] def __init__(self, particle_definition): super(Storage, self).__init__(particle_definition=particle_definition, resource=storage) self.bucket_name = self.desired_state_definition[\"name\"]", "import State import logging from google.cloud import storage from google.cloud", "an object in the S3 bucket. Args: blob_name (str): Object", "= self.desired_state_definition def download_object(self, blob_name, file_obj, **kwargs): \"\"\" Downloads a", "self.resource.Bucket): self.state = State.running else: self.state = State.terminated self.current_state_definition =", "\"\"\" Downloads a file from the S3 bucket. Args: blob_name", "bucket).download_file(file_obj, **kwargs) def delete_object(self, blob_name): \"\"\" Deletes an object in", "return self.client.bucket(bucket_name=self.bucket_name).create() def _stop(self): \"\"\" S3 bucket does not have", "(Required) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return bucket.delete_blob(blob_name) def list_objects(self, **kwargs):", "google.cloud import storage from google.cloud import exceptions logger = logging.getLogger(__name__)", "\"\"\" bucket = self.client.get_bucket(self.bucket_name) return bucket.delete_blob(blob_name) def list_objects(self, **kwargs): \"\"\"", "the download (Required) **kwargs: Options for boto3 get_object (optional) \"\"\"", "bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_file(file_obj, **kwargs) def put_file(self, blob_name,", "bucket).upload_from_filename(file, **kwargs) def _update(self): \"\"\" Not Implemented \"\"\" pass def", "storage bucket. Args: blob_name (str): Object Key name (Required) \"\"\"", "\"\"\" Not Implemented \"\"\" pass def is_state_equivalent(self, state1, state2): \"\"\"", "an object in the storage bucket. Args: blob_name (str): Object", "equivalent. Uses equivalent_states defined in the S3Bucket class. Args: state1", "Determines if the bucket exists Returns: status (dict) \"\"\" try:", "import exceptions logger = logging.getLogger(__name__) class Storage(GCPResource): \"\"\" This is", "the bucket exists Returns: status (dict) \"\"\" try: bucket =", "blob_name (str): Object Key name (Required) \"\"\" bucket = self.client.get_bucket(self.bucket_name)", "\"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).download_file(file_obj, **kwargs) def delete_object(self,", "Options for boto3 upload_file (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return", "file (file): the file to put into the bucket (Required)", "return {\"status\": \"missing\"} def _terminate(self): \"\"\" Deletes the storage bucket", "exceptions logger = logging.getLogger(__name__) class Storage(GCPResource): \"\"\" This is the", "file, **kwargs): \"\"\" Puts a file in the S3 bucket.", "the storage bucket Returns: response of create_bucket \"\"\" # create_definition", "of create_bucket \"\"\" # create_definition = pcf_util.keep_and_replace_keys(self.get_desired_state_definition(), # S3Bucket.START_PARAMS) return", "(str): Object Key name (Required) file_obj (object): the object to", "object in the storage bucket. Args: blob_name (str): Object Key", "**kwargs: Options for boto3 put_object (optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name)", "put_file(self, blob_name, file, **kwargs): \"\"\" Puts a file in the", "S3Bucket class. Args: state1 (State): state1 (State): Returns: bool \"\"\"", "\"\"\" This is the implementation of Google's storage service. \"\"\"", "= [\"gcp_resource.name\"] def __init__(self, particle_definition): super(Storage, self).__init__(particle_definition=particle_definition, resource=storage) self.bucket_name =", "bucket = self.client.get_bucket(self.bucket_name) return bucket except exceptions.NotFound: return {\"status\": \"missing\"}", "super(Storage, self).__init__(particle_definition=particle_definition, resource=storage) self.bucket_name = self.desired_state_definition[\"name\"] self._set_unique_keys() def _set_unique_keys(self): \"\"\"", "pcf.core import State import logging from google.cloud import storage from", "(optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).upload_from_filename(file, **kwargs) def", "flavor = \"storage\" equivalent_states = { State.running: 1, State.stopped: 0,", "Args: state1 (State): state1 (State): Returns: bool \"\"\" return Storage.equivalent_states.get(state1)", "**kwargs): \"\"\" Puts an object in the S3 bucket. Args:", "name for the download (Required) **kwargs: Options for boto3 get_object", "blob_name, file_obj, **kwargs): \"\"\" Puts an object in the S3", "class. Args: state1 (State): state1 (State): Returns: bool \"\"\" return", "the storage bucket Returns: response of gcp delete \"\"\" return", "def put_object(self, blob_name, file_obj, **kwargs): \"\"\" Puts an object in", "service. \"\"\" flavor = \"storage\" equivalent_states = { State.running: 1,", "= \"storage\" equivalent_states = { State.running: 1, State.stopped: 0, State.terminated:", "(Required) file (file): the file to put into the bucket", "file in the S3 bucket. Args: blob_name (str): Object Key", "Object name (Required) file_obj (str): file name for the download", "to uniquely identify the storage bucket \"\"\" self.unique_keys = Storage.UNIQUE_KEYS", "the storage bucket \"\"\" self.unique_keys = Storage.UNIQUE_KEYS def get_status(self): \"\"\"", "(str): file name for the download (Required) **kwargs: Options for", "file name for the download (Required) **kwargs: Options for boto3", "(Required) file_obj (object): the object to put into the bucket", "Args: blob_name (str): Object Key name (Required) file_obj (object): the", "Storage.UNIQUE_KEYS def get_status(self): \"\"\" Determines if the bucket exists Returns:", "self.bucket_name = self.desired_state_definition[\"name\"] self._set_unique_keys() def _set_unique_keys(self): \"\"\" Logic that sets", "= self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).download_file(file_obj, **kwargs) def delete_object(self, blob_name): \"\"\"", "(Required) file_obj (str): file name for the download (Required) **kwargs:", "storage bucket Returns: response of create_bucket \"\"\" # create_definition =", "equivalent_states = { State.running: 1, State.stopped: 0, State.terminated: 0 }", "bucket (Required) **kwargs: Options for boto3 upload_file (optional) \"\"\" bucket", "gcp delete \"\"\" return self.client.bucket(bucket_name=self.bucket_name).delete() def _start(self): \"\"\" Creates the", "name (Required) file (file): the file to put into the", "# create_definition = pcf_util.keep_and_replace_keys(self.get_desired_state_definition(), # S3Bucket.START_PARAMS) return self.client.bucket(bucket_name=self.bucket_name).create() def _stop(self):", "state1, state2): \"\"\" Determines if states are equivalent. Uses equivalent_states", "bucket \"\"\" self.unique_keys = Storage.UNIQUE_KEYS def get_status(self): \"\"\" Determines if", "the file to put into the bucket (Required) **kwargs: Options", "def put_file(self, blob_name, file, **kwargs): \"\"\" Puts a file in", "equivalent_states defined in the S3Bucket class. Args: state1 (State): state1", "blob_name, file_obj, **kwargs): \"\"\" Downloads a file from the S3", "Uses equivalent_states defined in the S3Bucket class. Args: state1 (State):", "blob_name, file, **kwargs): \"\"\" Puts a file in the S3", "Google's storage service. \"\"\" flavor = \"storage\" equivalent_states = {", "self._set_unique_keys() def _set_unique_keys(self): \"\"\" Logic that sets keys from state", "name (Required) file_obj (object): the object to put into the", "**kwargs) def put_file(self, blob_name, file, **kwargs): \"\"\" Puts a file", "self.client.get_bucket(self.bucket_name) return bucket.delete_blob(blob_name) def list_objects(self, **kwargs): \"\"\" Lists all objects", "(optional) \"\"\" bucket = self.client.get_bucket(self.bucket_name) return self.resource.Blob(blob_name, bucket).download_file(file_obj, **kwargs) def", "0 } UNIQUE_KEYS = [\"gcp_resource.name\"] def __init__(self, particle_definition): super(Storage, self).__init__(particle_definition=particle_definition,", "all objects in the storage bucket. Args: **kwargs: Options for", "Returns: response of create_bucket \"\"\" # create_definition = pcf_util.keep_and_replace_keys(self.get_desired_state_definition(), #", "Determines if states are equivalent. Uses equivalent_states defined in the", "storage service. \"\"\" flavor = \"storage\" equivalent_states = { State.running:", "def _set_unique_keys(self): \"\"\" Logic that sets keys from state definition", "state definition that are used to uniquely identify the storage", "= self.client.get_bucket(self.bucket_name) return bucket.delete_blob(blob_name) def list_objects(self, **kwargs): \"\"\" Lists all", "state so it calls terminate. \"\"\" return self.terminate() def sync_state(self):", "_update(self): \"\"\" Not Implemented \"\"\" pass def is_state_equivalent(self, state1, state2):", "S3Bucket.START_PARAMS) return self.client.bucket(bucket_name=self.bucket_name).create() def _stop(self): \"\"\" S3 bucket does not", "= Storage.UNIQUE_KEYS def get_status(self): \"\"\" Determines if the bucket exists" ]
[ "odd number, # as in the original MATLAB implementation if", "NumPy 1-D array containing the data to be smoothed #", "# a: NumPy 1-D array containing the data to be", "array containing the data to be smoothed # WSZ: smoothing", "MATLAB implementation if WSZ % 2 == 0: WSZ =", "start = np.cumsum(a[:WSZ - 1])[::2] / r stop = (np.cumsum(a[:-WSZ:-1])[::2]", "be smoothed # WSZ: smoothing window size needs, which must", "implementation if WSZ % 2 == 0: WSZ = WSZ", "numpy as np def smooth(a, WSZ): # a: NumPy 1-D", "which must be odd number, # as in the original", "size needs, which must be odd number, # as in", "2) start = np.cumsum(a[:WSZ - 1])[::2] / r stop =", "smoothing window size needs, which must be odd number, #", "smoothed # WSZ: smoothing window size needs, which must be", "% 2 == 0: WSZ = WSZ - 1 out0", "WSZ - 1, 2) start = np.cumsum(a[:WSZ - 1])[::2] /", "- 1, 2) start = np.cumsum(a[:WSZ - 1])[::2] / r", "1])[::2] / r stop = (np.cumsum(a[:-WSZ:-1])[::2] / r)[::-1] return np.concatenate((start,", "np.convolve(a, np.ones(WSZ, dtype=int), 'valid') / WSZ r = np.arange(1, WSZ", "number, # as in the original MATLAB implementation if WSZ", "np.arange(1, WSZ - 1, 2) start = np.cumsum(a[:WSZ - 1])[::2]", "original MATLAB implementation if WSZ % 2 == 0: WSZ", "a: NumPy 1-D array containing the data to be smoothed", "0: WSZ = WSZ - 1 out0 = np.convolve(a, np.ones(WSZ,", "WSZ = WSZ - 1 out0 = np.convolve(a, np.ones(WSZ, dtype=int),", "WSZ): # a: NumPy 1-D array containing the data to", "r = np.arange(1, WSZ - 1, 2) start = np.cumsum(a[:WSZ", "def smooth(a, WSZ): # a: NumPy 1-D array containing the", "= np.convolve(a, np.ones(WSZ, dtype=int), 'valid') / WSZ r = np.arange(1,", "dtype=int), 'valid') / WSZ r = np.arange(1, WSZ - 1,", "WSZ r = np.arange(1, WSZ - 1, 2) start =", "np.cumsum(a[:WSZ - 1])[::2] / r stop = (np.cumsum(a[:-WSZ:-1])[::2] / r)[::-1]", "2 == 0: WSZ = WSZ - 1 out0 =", "WSZ - 1 out0 = np.convolve(a, np.ones(WSZ, dtype=int), 'valid') /", "= np.arange(1, WSZ - 1, 2) start = np.cumsum(a[:WSZ -", "out0 = np.convolve(a, np.ones(WSZ, dtype=int), 'valid') / WSZ r =", "/ WSZ r = np.arange(1, WSZ - 1, 2) start", "1 out0 = np.convolve(a, np.ones(WSZ, dtype=int), 'valid') / WSZ r", "/ r stop = (np.cumsum(a[:-WSZ:-1])[::2] / r)[::-1] return np.concatenate((start, out0,", "if WSZ % 2 == 0: WSZ = WSZ -", "WSZ: smoothing window size needs, which must be odd number,", "as np def smooth(a, WSZ): # a: NumPy 1-D array", "needs, which must be odd number, # as in the", "1-D array containing the data to be smoothed # WSZ:", "1, 2) start = np.cumsum(a[:WSZ - 1])[::2] / r stop", "to be smoothed # WSZ: smoothing window size needs, which", "# WSZ: smoothing window size needs, which must be odd", "import numpy as np def smooth(a, WSZ): # a: NumPy", "'valid') / WSZ r = np.arange(1, WSZ - 1, 2)", "== 0: WSZ = WSZ - 1 out0 = np.convolve(a,", "WSZ % 2 == 0: WSZ = WSZ - 1", "as in the original MATLAB implementation if WSZ % 2", "the original MATLAB implementation if WSZ % 2 == 0:", "be odd number, # as in the original MATLAB implementation", "window size needs, which must be odd number, # as", "np.ones(WSZ, dtype=int), 'valid') / WSZ r = np.arange(1, WSZ -", "- 1])[::2] / r stop = (np.cumsum(a[:-WSZ:-1])[::2] / r)[::-1] return", "in the original MATLAB implementation if WSZ % 2 ==", "= np.cumsum(a[:WSZ - 1])[::2] / r stop = (np.cumsum(a[:-WSZ:-1])[::2] /", "r stop = (np.cumsum(a[:-WSZ:-1])[::2] / r)[::-1] return np.concatenate((start, out0, stop))", "containing the data to be smoothed # WSZ: smoothing window", "must be odd number, # as in the original MATLAB", "np def smooth(a, WSZ): # a: NumPy 1-D array containing", "data to be smoothed # WSZ: smoothing window size needs,", "# as in the original MATLAB implementation if WSZ %", "the data to be smoothed # WSZ: smoothing window size", "- 1 out0 = np.convolve(a, np.ones(WSZ, dtype=int), 'valid') / WSZ", "smooth(a, WSZ): # a: NumPy 1-D array containing the data", "= WSZ - 1 out0 = np.convolve(a, np.ones(WSZ, dtype=int), 'valid')" ]
[ "pylint: disable=protected-access keep_filter = gc._largest_export_versions(self._exports_to_keep) delete_filter = gc._negation(keep_filter) for p", "the best models. This class performs a model export everytime", "!= estimator.model_dir and self._event_file_pattern: # Loads best metric from event", "current evaluation result is better. Follows the signature: * Args:", "if not event_files: return None event_count = 0 best_eval_result =", "subdirectories are assumed to be named with monotonically increasing integers;", "self._garbage_collect_exports(export_path) with open(os.path.join(export_path, 'export.log'), 'w') as fp: json.dump(self._log, fp) return", "gfile from tensorflow.python.platform import tf_logging from tensorflow.python.summary import summary_iterator from", "best model export.') self._best_eval_result = eval_result export_result = self._saved_model_exporter.export( estimator,", "current_eval_result[default_key] class BestExporter(Exporter): \"\"\"This class exports the serving graph and", "% compare_fn) non_valid_args = list(args - set(['best_eval_result', 'current_eval_result'])) if non_valid_args:", "__init__(self, name='best_exporter', serving_input_receiver_fn=None, event_file_pattern='eval/*.tfevents.*', compare_fn=_loss_smaller, assets_extra=None, as_text=False, exports_to_keep=5): \"\"\"Create an", "simple case of copying a single file without renaming it", "the loss of current_eval_result is smaller; otherwise, False. Raises: ValueError:", "= tf.estimator.BestExporter( name=\"best_exporter\", serving_input_receiver_fn=serving_input_receiver_fn, exports_to_keep=5) train_spec = tf.estimator.TrainSpec(...) eval_spec =", "values for MetricKeys.LOSS, which are used for comparison. Args: best_eval_result:", "for MetricKeys.LOSS, which are used for comparison. Args: best_eval_result: best", "exports will be garbage-collected. Defaults to 5. Set to `None`", "= None for event_file in gfile.Glob(os.path.join(event_files)): for event in summary_iterator.summary_iterator(event_file):", "enable=protected-access def _get_best_eval_result(self, event_files): \"\"\"Get the best eval result from", "'r')) except json.JSONDecodeError: pass if len(self._log) == 0: self._best_eval_result =", "Defaults to `False`. exports_to_keep: Number of exports to keep. Older", "to be copied. For example, the simple case of copying", "= {} if exports_to_keep is not None and exports_to_keep <=", "assets_extra, as_text) self._event_file_pattern = event_file_pattern self._model_dir = None self._best_eval_result =", "signature: * Args: * `best_eval_result`: This is the evaluation result", "otherwise, False. Raises: ValueError: If input eval result is None", "not best_eval_result or default_key not in best_eval_result: raise ValueError( 'best_eval_result", "results and returns true if current evaluation result is better.", "None or self._compare_fn( best_eval_result, event_eval_result): event_count += 1 best_eval_result =", "from tensorflow.python.platform import tf_logging from tensorflow.python.summary import summary_iterator from tensorflow.python.estimator.exporter", "eval metrics. Returns: True if the loss of current_eval_result is", "or default_key not in current_eval_result: raise ValueError( 'current_eval_result cannot be", "( tf.feature_column.categorical_column_with_hash_bucket(...)) categorial_feature_a_emb = embedding_column( categorical_column=categorial_feature_a, ...) ... # other", "= tf.estimator.TrainSpec(...) eval_spec = [tf.estimator.EvalSpec( input_fn=eval_input_fn, steps=100, exporters=exporter, start_delay_secs=0, throttle_secs=5)]", "Args: name: unique name of this `Exporter` that is going", "creating a BestExporter for training and evluation: ```python def make_train_and_eval_fn():", "the destination path (including the filename) relative to the assets.extra", "copied. For example, the simple case of copying a single", "= event_eval_result if event_count < 2: return None return best_eval_result", "'best_eval_result cannot be empty or no loss is found in", "self._best_eval_result = eval_result export_result = self._saved_model_exporter.export( estimator, export_path, checkpoint_path, eval_result,", "return None event_count = 0 best_eval_result = None for event_file", "is None or self._compare_fn( best_eval_result=self._best_eval_result, current_eval_result=eval_result): tf_logging.info('Performing best model export.')", "json.load(open(os.path.join(export_path, 'export.log'), 'r')) except json.JSONDecodeError: pass if len(self._log) == 0:", "single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.", "assets_extra=None, as_text=False, exports_to_keep=5): \"\"\"Create an `Exporter` to use with `tf.estimator.EvalSpec`.", "to model_dir. If None, however, the exporter would not be", "step): for file in glob.glob(checkpoint_pattern + '*'): shutil.copy(file, dest_path) with", "event files. tf_logging.info('Loading best metric from event files.') self._model_dir =", "= exports_to_keep self._log = {} if exports_to_keep is not None", "it.') return best_eval_result[default_key] > current_eval_result[default_key] class BestExporter(Exporter): \"\"\"This class exports", "be empty or no loss is found in it.') return", "tf.feature_column.make_parse_example_spec( categorial_feature_a_emb) serving_input_receiver_fn = ( tf.estimator.export.build_parsing_serving_input_receiver_fn( serving_feature_spec)) exporter = tf.estimator.BestExporter(", "name(self): return self._saved_model_exporter.name def export(self, estimator, export_path, checkpoint_path, eval_result, is_the_final_export):", "be used in the export path. serving_input_receiver_fn: a function that", "self._copy_checkpoint(checkpoint_path, export_result_path, eval_result[\"global_step\"]) self._garbage_collect_exports(export_path) with open(os.path.join(export_path, 'export.log'), 'w') as fp:", "tensorflow.python.estimator.exporter import Exporter, _SavedModelExporter def _verify_compare_fn_args(compare_fn): \"\"\"Verifies compare_fn arguments.\"\"\" args", "self._model_dir = None self._best_eval_result = None self._exports_to_keep = exports_to_keep self._log", "export_result def _copy_checkpoint(self, checkpoint_pattern, dest_path, step): for file in glob.glob(checkpoint_pattern", "tf.estimator.BestExporter( name=\"best_exporter\", serving_input_receiver_fn=serving_input_receiver_fn, exports_to_keep=5) train_spec = tf.estimator.TrainSpec(...) eval_spec = [tf.estimator.EvalSpec(", "e) # pylint: enable=protected-access def _get_best_eval_result(self, event_files): \"\"\"Get the best", "serving_input_receiver_fn, assets_extra, as_text) self._event_file_pattern = event_file_pattern self._model_dir = None self._best_eval_result", "json.JSONDecodeError: pass if len(self._log) == 0: self._best_eval_result = None if", "smaller. Both evaluation results should have the values for MetricKeys.LOSS,", "(compare_fn, non_valid_args)) def _loss_smaller(best_eval_result, current_eval_result): \"\"\"Compares two evaluation results and", "should have the values for MetricKeys.LOSS, which are used for", "MetricKeys.LOSS, which are used for comparison. Args: best_eval_result: best eval", "checkpoints of the best models. This class performs a model", "be copied. For example, the simple case of copying a", "shutil.copy(file, dest_path) with open(os.path.join(dest_path, 'checkpoint'), 'w') as fp: text =", "delete %s recursively: %s', p.path, e) # pylint: enable=protected-access def", "for p in delete_filter( gc._get_paths(export_dir_base, parser=_export_version_parser)): try: del self._log[p.path] gfile.DeleteRecursively(p.path)", "SavedModel. Each key should give the destination path (including the", "An optional dict specifying how to populate the assets.extra directory", "any exsiting model. \"\"\" def __init__(self, name='best_exporter', serving_input_receiver_fn=None, event_file_pattern='eval/*.tfevents.*', compare_fn=_loss_smaller,", "exports_to_keep=5): \"\"\"Create an `Exporter` to use with `tf.estimator.EvalSpec`. Example of", "= self._saved_model_exporter.export( estimator, export_path, checkpoint_path, eval_result, is_the_final_export) export_result_path = export_result.decode(\"utf-8\")", "available. \"\"\" default_key = metric_keys.MetricKeys.LOSS if not best_eval_result or default_key", "corresponding value gives the full path of the source file", "export_result = self._saved_model_exporter.export( estimator, export_path, checkpoint_path, eval_result, is_the_final_export) export_result_path =", "exports the serving graph and checkpoints of the best models.", "path. serving_input_receiver_fn: a function that takes no arguments and returns", "files. Args: event_files: Absolute pattern of event files. Returns: The", "Raises: ValueError: if any arguments is invalid. \"\"\" self._compare_fn =", "import Exporter, _SavedModelExporter def _verify_compare_fn_args(compare_fn): \"\"\"Verifies compare_fn arguments.\"\"\" args =", "which are used for comparison. Args: best_eval_result: best eval metrics.", "ValueError( 'compare_fn (%s) must include best_eval_result argument.' % compare_fn) if", "args: %s' % (compare_fn, non_valid_args)) def _loss_smaller(best_eval_result, current_eval_result): \"\"\"Compares two", "Number of exports to keep. Older exports will be garbage-collected.", "self._event_file_pattern) self._best_eval_result = self._get_best_eval_result( full_event_file_pattern) if os.path.isfile(os.path.join(export_path, 'export.log')): self._log =", "pattern of event files. Returns: The best eval result. \"\"\"", "of event files. Returns: The best eval result. \"\"\" if", "not None and exports_to_keep <= 0: raise ValueError( '`exports_to_keep`, if", "whether to write the SavedModel proto in text format. Defaults", "is available. \"\"\" default_key = metric_keys.MetricKeys.LOSS if not best_eval_result or", "raise ValueError('compare_fn (%s) has following not expected args: %s' %", "Defaults to 5. Set to `None` to disable garbage collection.", "current eval metrics. Returns: True if the loss of current_eval_result", "two evaluation results and returns true if the 2nd one", "bex preemption-safe, event_file_pattern should be specified. compare_fn: a function that", "== 10 and filename.isdigit()): return None return path._replace(export_version=int(filename)) # pylint:", "self._log[p.path] gfile.DeleteRecursively(p.path) except errors_impl.NotFoundError as e: tf_logging.warn('Can not delete %s", "embedding_column( categorical_column=categorial_feature_a, ...) ... # other feature columns estimator =", "... # other feature columns estimator = tf.estimator.DNNClassifier( config=tf.estimator.RunConfig( model_dir='/my_model',", "result of the best model. * `current_eval_result`: This is the", "loss is found in it.') if not current_eval_result or default_key", "name: unique name of this `Exporter` that is going to", "args: raise ValueError( 'compare_fn (%s) must include best_eval_result argument.' %", "\"\"\"Get the best eval result from event files. Args: event_files:", "name=\"best_exporter\", serving_input_receiver_fn=serving_input_receiver_fn, exports_to_keep=5) train_spec = tf.estimator.TrainSpec(...) eval_spec = [tf.estimator.EvalSpec( input_fn=eval_input_fn,", "only a given number of the most recent. Export subdirectories", "self._exports_to_keep = exports_to_keep self._log = {} if exports_to_keep is not", "in event.summary.value: if value.HasField('simple_value'): event_eval_result[value.tag] = value.simple_value if event_eval_result: if", "BestExporter for training and evluation: ```python def make_train_and_eval_fn(): # Set", "gc from tensorflow.python.estimator import util from tensorflow.python.estimator.canned import metric_keys from", "if the 2nd one is smaller. Both evaluation results should", "is smaller; otherwise, False. Raises: ValueError: If input eval result", "no loss is found in it.') return best_eval_result[default_key] > current_eval_result[default_key]", "self._model_dir = estimator.model_dir full_event_file_pattern = os.path.join(self._model_dir, self._event_file_pattern) self._best_eval_result = self._get_best_eval_result(", "increasing integers; the most recent are taken to be those", "disable=protected-access keep_filter = gc._largest_export_versions(self._exports_to_keep) delete_filter = gc._negation(keep_filter) for p in", "errors_impl.NotFoundError as e: tf_logging.warn('Can not delete %s recursively: %s', p.path,", "results should have the values for MetricKeys.LOSS, which are used", "the best model. * `current_eval_result`: This is the evaluation result", "assets.extra directory. The corresponding value gives the full path of", "files. tf_logging.info('Loading best metric from event files.') self._model_dir = estimator.model_dir", "import absolute_import import abc import os import json import glob", "model. \"\"\" def __init__(self, name='best_exporter', serving_input_receiver_fn=None, event_file_pattern='eval/*.tfevents.*', compare_fn=_loss_smaller, assets_extra=None, as_text=False,", "keep. Older exports will be garbage-collected. Defaults to 5. Set", "( tf.estimator.export.build_parsing_serving_input_receiver_fn( serving_feature_spec)) exporter = tf.estimator.BestExporter( name=\"best_exporter\", serving_input_receiver_fn=serving_input_receiver_fn, exports_to_keep=5) train_spec", "non_valid_args: raise ValueError('compare_fn (%s) has following not expected args: %s'", "true if current evaluation result is better. Follows the signature:", "be positive number') @property def name(self): return self._saved_model_exporter.name def export(self,", "return tf.estimator.DistributedTrainingSpec(estimator, train_spec, eval_spec) ``` Args: name: unique name of", "eval result. \"\"\" if not event_files: return None event_count =", "loss is found in it.') return best_eval_result[default_key] > current_eval_result[default_key] class", "is None: return def _export_version_parser(path): # create a simple parser", "None and exports_to_keep <= 0: raise ValueError( '`exports_to_keep`, if provided,", "self._log = {} if exports_to_keep is not None and exports_to_keep", "self._best_eval_result is None or self._compare_fn( best_eval_result=self._best_eval_result, current_eval_result=eval_result): tf_logging.info('Performing best model", "__future__ import absolute_import import abc import os import json import", "non_valid_args)) def _loss_smaller(best_eval_result, current_eval_result): \"\"\"Compares two evaluation results and returns", "the signature: * Args: * `best_eval_result`: This is the evaluation", "have the values for MetricKeys.LOSS, which are used for comparison.", "best_eval_result = None for event_file in gfile.Glob(os.path.join(event_files)): for event in", "full_event_file_pattern = os.path.join(self._model_dir, self._event_file_pattern) self._best_eval_result = self._get_best_eval_result( full_event_file_pattern) if os.path.isfile(os.path.join(export_path,", "is the evaluation result of the best model. * `current_eval_result`:", "as_text) self._event_file_pattern = event_file_pattern self._model_dir = None self._best_eval_result = None", "performs a model export everytime when the new model is", "# Loads best metric from event files. tf_logging.info('Loading best metric", "best metric from event files.') self._model_dir = estimator.model_dir full_event_file_pattern =", "def _verify_compare_fn_args(compare_fn): \"\"\"Verifies compare_fn arguments.\"\"\" args = set(util.fn_args(compare_fn)) if 'best_eval_result'", "= None if self._best_eval_result is None or self._compare_fn( best_eval_result=self._best_eval_result, current_eval_result=eval_result):", "categorial_feature_a_emb) serving_input_receiver_fn = ( tf.estimator.export.build_parsing_serving_input_receiver_fn( serving_feature_spec)) exporter = tf.estimator.BestExporter( name=\"best_exporter\",", "the largest values. Args: export_dir_base: the base directory under which", "summary_iterator from tensorflow.python.estimator.exporter import Exporter, _SavedModelExporter def _verify_compare_fn_args(compare_fn): \"\"\"Verifies compare_fn", "import tf_logging from tensorflow.python.summary import summary_iterator from tensorflow.python.estimator.exporter import Exporter,", "text format. Defaults to `False`. exports_to_keep: Number of exports to", "[tf.estimator.EvalSpec( input_fn=eval_input_fn, steps=100, exporters=exporter, start_delay_secs=0, throttle_secs=5)] return tf.estimator.DistributedTrainingSpec(estimator, train_spec, eval_spec)", "returns true if current evaluation result is better. Follows the", "the filename) relative to the assets.extra directory. The corresponding value", "ValueError( 'current_eval_result cannot be empty or no loss is found", "directory within the exported SavedModel. Each key should give the", "\"\"\" default_key = metric_keys.MetricKeys.LOSS if not best_eval_result or default_key not", "function that takes no arguments and returns a `ServingInputReceiver`. event_file_pattern:", "tensorflow.python.platform import gfile from tensorflow.python.platform import tf_logging from tensorflow.python.summary import", "# pylint: disable=protected-access keep_filter = gc._largest_export_versions(self._exports_to_keep) delete_filter = gc._negation(keep_filter) for", "For example, the simple case of copying a single file", "model export.') self._best_eval_result = eval_result export_result = self._saved_model_exporter.export( estimator, export_path,", "which each export is in a versioned subdirectory. \"\"\" if", "def __init__(self, name='best_exporter', serving_input_receiver_fn=None, event_file_pattern='eval/*.tfevents.*', compare_fn=_loss_smaller, assets_extra=None, as_text=False, exports_to_keep=5): \"\"\"Create", "open(os.path.join(export_path, 'export.log'), 'w') as fp: json.dump(self._log, fp) return export_result def", "# Set up feature columns. categorial_feature_a = ( tf.feature_column.categorical_column_with_hash_bucket(...)) categorial_feature_a_emb", "None or no loss is available. \"\"\" default_key = metric_keys.MetricKeys.LOSS", "True if current evaluation result is better; otherwise, False. assets_extra:", "If None, however, the exporter would not be preemption-safe. To", "`current_eval_result`: This is the evaluation result of current candidate model.", "False. assets_extra: An optional dict specifying how to populate the", "_SavedModelExporter( name, serving_input_receiver_fn, assets_extra, as_text) self._event_file_pattern = event_file_pattern self._model_dir =", "going to be used in the export path. serving_input_receiver_fn: a", "= eval_result export_result = self._saved_model_exporter.export( estimator, export_path, checkpoint_path, eval_result, is_the_final_export)", "model is better than any exsiting model. \"\"\" def __init__(self,", "Loads best metric from event files. tf_logging.info('Loading best metric from", "512, 256]) serving_feature_spec = tf.feature_column.make_parse_example_spec( categorial_feature_a_emb) serving_input_receiver_fn = ( tf.estimator.export.build_parsing_serving_input_receiver_fn(", "the best eval result from event files. Args: event_files: Absolute", "any arguments is invalid. \"\"\" self._compare_fn = compare_fn if self._compare_fn", "export_result.decode(\"utf-8\") self._log[export_result_path] = {k: float(v) for k, v in eval_result.items()}", "if self._compare_fn is None: raise ValueError('`compare_fn` must not be None.')", "best_eval_result=self._best_eval_result, current_eval_result=eval_result): tf_logging.info('Performing best model export.') self._best_eval_result = eval_result export_result", "in summary_iterator.summary_iterator(event_file): if event.HasField('summary'): event_eval_result = {} for value in", "Raises: ValueError: If input eval result is None or no", "is smaller. Both evaluation results should have the values for", "To bex preemption-safe, event_file_pattern should be specified. compare_fn: a function", "dict specifying how to populate the assets.extra directory within the", "each export is in a versioned subdirectory. \"\"\" if self._exports_to_keep", "tf_logging.info('Loading best metric from event files.') self._model_dir = estimator.model_dir full_event_file_pattern", "better than any exsiting model. \"\"\" def __init__(self, name='best_exporter', serving_input_receiver_fn=None,", "'export.log'), 'w') as fp: json.dump(self._log, fp) return export_result def _copy_checkpoint(self,", "os import json import glob import shutil from tensorflow.python.estimator import", "Both evaluation results should have the values for MetricKeys.LOSS, which", "ValueError('`compare_fn` must not be None.') _verify_compare_fn_args(self._compare_fn) self._saved_model_exporter = _SavedModelExporter( name,", "empty or no loss is found in it.') return best_eval_result[default_key]", "\"\"\"This class exports the serving graph and checkpoints of the", "and returns true if current evaluation result is better. Follows", "metric_keys.MetricKeys.LOSS if not best_eval_result or default_key not in best_eval_result: raise", "used in the export path. serving_input_receiver_fn: a function that takes", "checkpoint_path, eval_result, is_the_final_export) export_result_path = export_result.decode(\"utf-8\") self._log[export_result_path] = {k: float(v)", "best metric from event files. tf_logging.info('Loading best metric from event", "'current_eval_result cannot be empty or no loss is found in", "the most recent. Export subdirectories are assumed to be named", "self._exports_to_keep is None: return def _export_version_parser(path): # create a simple", "\"model.ckpt-number\"\\n'.replace('number', str(step)) fp.write(text) fp.close() def _garbage_collect_exports(self, export_dir_base): \"\"\"Deletes older exports,", "raise ValueError( 'current_eval_result cannot be empty or no loss is", "self._model_dir != estimator.model_dir and self._event_file_pattern: # Loads best metric from", "given number of the most recent. Export subdirectories are assumed", "without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. as_text: whether", "p.path, e) # pylint: enable=protected-access def _get_best_eval_result(self, event_files): \"\"\"Get the", "arguments.\"\"\" args = set(util.fn_args(compare_fn)) if 'best_eval_result' not in args: raise", "make_train_and_eval_fn(): # Set up feature columns. categorial_feature_a = ( tf.feature_column.categorical_column_with_hash_bucket(...))", "ValueError( '`exports_to_keep`, if provided, must be positive number') @property def", "= event_file_pattern self._model_dir = None self._best_eval_result = None self._exports_to_keep =", "from event files. tf_logging.info('Loading best metric from event files.') self._model_dir", "%s recursively: %s', p.path, e) # pylint: enable=protected-access def _get_best_eval_result(self,", "This class performs a model export everytime when the new", "'best_eval_result' not in args: raise ValueError( 'compare_fn (%s) must include", "an `Exporter` to use with `tf.estimator.EvalSpec`. Example of creating a", "takes no arguments and returns a `ServingInputReceiver`. event_file_pattern: event file", "a model export everytime when the new model is better", "raise ValueError( '`exports_to_keep`, if provided, must be positive number') @property", "= {} try: self._log = json.load(open(os.path.join(export_path, 'export.log'), 'r')) except json.JSONDecodeError:", "(len(filename) == 10 and filename.isdigit()): return None return path._replace(export_version=int(filename)) #", "is the evaluation result of current candidate model. * Returns:", "file to be copied. For example, the simple case of", "None: return def _export_version_parser(path): # create a simple parser that", "result from event files. Args: event_files: Absolute pattern of event", "comparison. Args: best_eval_result: best eval metrics. current_eval_result: current eval metrics.", "disable garbage collection. Raises: ValueError: if any arguments is invalid.", "exported SavedModel. Each key should give the destination path (including", "self._compare_fn = compare_fn if self._compare_fn is None: raise ValueError('`compare_fn` must", "return export_result def _copy_checkpoint(self, checkpoint_pattern, dest_path, step): for file in", "the export path. serving_input_receiver_fn: a function that takes no arguments", "current_eval_result or default_key not in current_eval_result: raise ValueError( 'current_eval_result cannot", "metrics. current_eval_result: current eval metrics. Returns: True if the loss", "0 best_eval_result = None for event_file in gfile.Glob(os.path.join(event_files)): for event", "found in it.') return best_eval_result[default_key] > current_eval_result[default_key] class BestExporter(Exporter): \"\"\"This", "new model is better than any exsiting model. \"\"\" def", "expected args: %s' % (compare_fn, non_valid_args)) def _loss_smaller(best_eval_result, current_eval_result): \"\"\"Compares", "not in best_eval_result: raise ValueError( 'best_eval_result cannot be empty or", "eval metrics. current_eval_result: current eval metrics. Returns: True if the", "export everytime when the new model is better than any", "be preemption-safe. To bex preemption-safe, event_file_pattern should be specified. compare_fn:", "self._saved_model_exporter.export( estimator, export_path, checkpoint_path, eval_result, is_the_final_export) export_result_path = export_result.decode(\"utf-8\") self._log[export_result_path]", "in args: raise ValueError( 'compare_fn (%s) must include current_eval_result argument.'", "return best_eval_result[default_key] > current_eval_result[default_key] class BestExporter(Exporter): \"\"\"This class exports the", "# pylint: enable=protected-access def _get_best_eval_result(self, event_files): \"\"\"Get the best eval", "preemption-safe, event_file_pattern should be specified. compare_fn: a function that compares", "it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. as_text: whether to write", "None.') _verify_compare_fn_args(self._compare_fn) self._saved_model_exporter = _SavedModelExporter( name, serving_input_receiver_fn, assets_extra, as_text) self._event_file_pattern", "if provided, must be positive number') @property def name(self): return", "of exports to keep. Older exports will be garbage-collected. Defaults", "os.path.basename(path.path) if not (len(filename) == 10 and filename.isdigit()): return None", "to keep. Older exports will be garbage-collected. Defaults to 5.", "v in eval_result.items()} self._copy_checkpoint(checkpoint_path, export_result_path, eval_result[\"global_step\"]) self._garbage_collect_exports(export_path) with open(os.path.join(export_path, 'export.log'),", "glob.glob(checkpoint_pattern + '*'): shutil.copy(file, dest_path) with open(os.path.join(dest_path, 'checkpoint'), 'w') as", "except errors_impl.NotFoundError as e: tf_logging.warn('Can not delete %s recursively: %s',", "compare_fn: a function that compares two evaluation results and returns", "current_eval_result: current eval metrics. Returns: True if the loss of", "otherwise, False. assets_extra: An optional dict specifying how to populate", "if self._model_dir != estimator.model_dir and self._event_file_pattern: # Loads best metric", "and returns a `ServingInputReceiver`. event_file_pattern: event file name pattern relative", "dest_path, step): for file in glob.glob(checkpoint_pattern + '*'): shutil.copy(file, dest_path)", "event_count += 1 best_eval_result = event_eval_result if event_count < 2:", "except json.JSONDecodeError: pass if len(self._log) == 0: self._best_eval_result = None", "is better; otherwise, False. assets_extra: An optional dict specifying how", "absolute_import import abc import os import json import glob import", "as_text=False, exports_to_keep=5): \"\"\"Create an `Exporter` to use with `tf.estimator.EvalSpec`. Example", "be garbage-collected. Defaults to 5. Set to `None` to disable", "raise ValueError( 'compare_fn (%s) must include best_eval_result argument.' % compare_fn)", "value.simple_value if event_eval_result: if best_eval_result is None or self._compare_fn( best_eval_result,", "export path. serving_input_receiver_fn: a function that takes no arguments and", "up feature columns. categorial_feature_a = ( tf.feature_column.categorical_column_with_hash_bucket(...)) categorial_feature_a_emb = embedding_column(", "those with the largest values. Args: export_dir_base: the base directory", "if non_valid_args: raise ValueError('compare_fn (%s) has following not expected args:", "eval_result export_result = self._saved_model_exporter.export( estimator, export_path, checkpoint_path, eval_result, is_the_final_export) export_result_path", "self._compare_fn is None: raise ValueError('`compare_fn` must not be None.') _verify_compare_fn_args(self._compare_fn)", "serving_input_receiver_fn=serving_input_receiver_fn, exports_to_keep=5) train_spec = tf.estimator.TrainSpec(...) eval_spec = [tf.estimator.EvalSpec( input_fn=eval_input_fn, steps=100,", "exports, retaining only a given number of the most recent.", "of current_eval_result is smaller; otherwise, False. Raises: ValueError: If input", "train_spec = tf.estimator.TrainSpec(...) eval_spec = [tf.estimator.EvalSpec( input_fn=eval_input_fn, steps=100, exporters=exporter, start_delay_secs=0,", "tf.feature_column.categorical_column_with_hash_bucket(...)) categorial_feature_a_emb = embedding_column( categorical_column=categorial_feature_a, ...) ... # other feature", "pylint: enable=protected-access def _get_best_eval_result(self, event_files): \"\"\"Get the best eval result", "= None self._best_eval_result = None self._exports_to_keep = exports_to_keep self._log =", "number of the most recent. Export subdirectories are assumed to", "as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. as_text: whether to write the SavedModel proto", "10 and filename.isdigit()): return None return path._replace(export_version=int(filename)) # pylint: disable=protected-access", "best models. This class performs a model export everytime when", "relative to model_dir. If None, however, the exporter would not", "compare_fn) non_valid_args = list(args - set(['best_eval_result', 'current_eval_result'])) if non_valid_args: raise", "must not be None.') _verify_compare_fn_args(self._compare_fn) self._saved_model_exporter = _SavedModelExporter( name, serving_input_receiver_fn,", "eval result is None or no loss is available. \"\"\"", "columns estimator = tf.estimator.DNNClassifier( config=tf.estimator.RunConfig( model_dir='/my_model', save_summary_steps=100), feature_columns=[categorial_feature_a_emb, ...], hidden_units=[1024,", "named with monotonically increasing integers; the most recent are taken", "args = set(util.fn_args(compare_fn)) if 'best_eval_result' not in args: raise ValueError(", "len(self._log) == 0: self._best_eval_result = None if self._best_eval_result is None", "the assets.extra directory. The corresponding value gives the full path", "_loss_smaller(best_eval_result, current_eval_result): \"\"\"Compares two evaluation results and returns true if", "def _copy_checkpoint(self, checkpoint_pattern, dest_path, step): for file in glob.glob(checkpoint_pattern +", "result is better. Follows the signature: * Args: * `best_eval_result`:", "however, the exporter would not be preemption-safe. To bex preemption-safe,", "``` Args: name: unique name of this `Exporter` that is", "checkpoint_pattern, dest_path, step): for file in glob.glob(checkpoint_pattern + '*'): shutil.copy(file,", "recent are taken to be those with the largest values.", "or self._compare_fn( best_eval_result, event_eval_result): event_count += 1 best_eval_result = event_eval_result", "event_file_pattern='eval/*.tfevents.*', compare_fn=_loss_smaller, assets_extra=None, as_text=False, exports_to_keep=5): \"\"\"Create an `Exporter` to use", "other feature columns estimator = tf.estimator.DNNClassifier( config=tf.estimator.RunConfig( model_dir='/my_model', save_summary_steps=100), feature_columns=[categorial_feature_a_emb,", "compares two evaluation results and returns true if current evaluation", "best_eval_result: best eval metrics. current_eval_result: current eval metrics. Returns: True", "gives the full path of the source file to be", "estimator.model_dir full_event_file_pattern = os.path.join(self._model_dir, self._event_file_pattern) self._best_eval_result = self._get_best_eval_result( full_event_file_pattern) if", "in best_eval_result: raise ValueError( 'best_eval_result cannot be empty or no", "hidden_units=[1024, 512, 256]) serving_feature_spec = tf.feature_column.make_parse_example_spec( categorial_feature_a_emb) serving_input_receiver_fn = (", "create a simple parser that pulls the export_version from the", "is invalid. \"\"\" self._compare_fn = compare_fn if self._compare_fn is None:", "tf.estimator.DistributedTrainingSpec(estimator, train_spec, eval_spec) ``` Args: name: unique name of this", "text = 'model_checkpoint_path: \"model.ckpt-number\"\\n'.replace('number', str(step)) fp.write(text) fp.close() def _garbage_collect_exports(self, export_dir_base):", "= 'model_checkpoint_path: \"model.ckpt-number\"\\n'.replace('number', str(step)) fp.write(text) fp.close() def _garbage_collect_exports(self, export_dir_base): \"\"\"Deletes", "return path._replace(export_version=int(filename)) # pylint: disable=protected-access keep_filter = gc._largest_export_versions(self._exports_to_keep) delete_filter =", "file in glob.glob(checkpoint_pattern + '*'): shutil.copy(file, dest_path) with open(os.path.join(dest_path, 'checkpoint'),", "input eval result is None or no loss is available.", "event files. Args: event_files: Absolute pattern of event files. Returns:", "with monotonically increasing integers; the most recent are taken to", "5. Set to `None` to disable garbage collection. Raises: ValueError:", "specifying how to populate the assets.extra directory within the exported", "a single file without renaming it is specified as `{'my_asset_file.txt':", "if exports_to_keep is not None and exports_to_keep <= 0: raise", "def export(self, estimator, export_path, checkpoint_path, eval_result, is_the_final_export): export_result = None", "evaluation result is better; otherwise, False. assets_extra: An optional dict", "argument.' % compare_fn) non_valid_args = list(args - set(['best_eval_result', 'current_eval_result'])) if", "from event files.') self._model_dir = estimator.model_dir full_event_file_pattern = os.path.join(self._model_dir, self._event_file_pattern)", "value gives the full path of the source file to", "import summary_iterator from tensorflow.python.estimator.exporter import Exporter, _SavedModelExporter def _verify_compare_fn_args(compare_fn): \"\"\"Verifies", "relative to the assets.extra directory. The corresponding value gives the", "self._best_eval_result = self._get_best_eval_result( full_event_file_pattern) if os.path.isfile(os.path.join(export_path, 'export.log')): self._log = {}", "\"\"\" if self._exports_to_keep is None: return def _export_version_parser(path): # create", "event.summary.value: if value.HasField('simple_value'): event_eval_result[value.tag] = value.simple_value if event_eval_result: if best_eval_result", "if self._exports_to_keep is None: return def _export_version_parser(path): # create a", "largest values. Args: export_dir_base: the base directory under which each", "throttle_secs=5)] return tf.estimator.DistributedTrainingSpec(estimator, train_spec, eval_spec) ``` Args: name: unique name", "and self._event_file_pattern: # Loads best metric from event files. tf_logging.info('Loading", "cannot be empty or no loss is found in it.')", "event_file in gfile.Glob(os.path.join(event_files)): for event in summary_iterator.summary_iterator(event_file): if event.HasField('summary'): event_eval_result", "return None return path._replace(export_version=int(filename)) # pylint: disable=protected-access keep_filter = gc._largest_export_versions(self._exports_to_keep)", "(%s) has following not expected args: %s' % (compare_fn, non_valid_args))", "would not be preemption-safe. To bex preemption-safe, event_file_pattern should be", "within the exported SavedModel. Each key should give the destination", "not in current_eval_result: raise ValueError( 'current_eval_result cannot be empty or", "export.') self._best_eval_result = eval_result export_result = self._saved_model_exporter.export( estimator, export_path, checkpoint_path,", "_verify_compare_fn_args(self._compare_fn) self._saved_model_exporter = _SavedModelExporter( name, serving_input_receiver_fn, assets_extra, as_text) self._event_file_pattern =", "from tensorflow.python.estimator.canned import metric_keys from tensorflow.python.framework import errors_impl from tensorflow.python.platform", "`Exporter` that is going to be used in the export", "if self._best_eval_result is None or self._compare_fn( best_eval_result=self._best_eval_result, current_eval_result=eval_result): tf_logging.info('Performing best", "{} for value in event.summary.value: if value.HasField('simple_value'): event_eval_result[value.tag] = value.simple_value", "os.path.isfile(os.path.join(export_path, 'export.log')): self._log = {} try: self._log = json.load(open(os.path.join(export_path, 'export.log'),", "not (len(filename) == 10 and filename.isdigit()): return None return path._replace(export_version=int(filename))", "the evaluation result of the best model. * `current_eval_result`: This", "specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. as_text: whether to write the SavedModel", "of copying a single file without renaming it is specified", "that compares two evaluation results and returns true if current", "import gc from tensorflow.python.estimator import util from tensorflow.python.estimator.canned import metric_keys", "filename.isdigit()): return None return path._replace(export_version=int(filename)) # pylint: disable=protected-access keep_filter =", "fp: json.dump(self._log, fp) return export_result def _copy_checkpoint(self, checkpoint_pattern, dest_path, step):", "best_eval_result = event_eval_result if event_count < 2: return None return", "* `best_eval_result`: This is the evaluation result of the best", "{k: float(v) for k, v in eval_result.items()} self._copy_checkpoint(checkpoint_path, export_result_path, eval_result[\"global_step\"])", "in delete_filter( gc._get_paths(export_dir_base, parser=_export_version_parser)): try: del self._log[p.path] gfile.DeleteRecursively(p.path) except errors_impl.NotFoundError", "evaluation results and returns true if the 2nd one is", "better. Follows the signature: * Args: * `best_eval_result`: This is", "is in a versioned subdirectory. \"\"\" if self._exports_to_keep is None:", "if any arguments is invalid. \"\"\" self._compare_fn = compare_fn if", "compare_fn) if 'current_eval_result' not in args: raise ValueError( 'compare_fn (%s)", "tensorflow.python.platform import tf_logging from tensorflow.python.summary import summary_iterator from tensorflow.python.estimator.exporter import", "be empty or no loss is found in it.') if", "best_eval_result[default_key] > current_eval_result[default_key] class BestExporter(Exporter): \"\"\"This class exports the serving", "in a versioned subdirectory. \"\"\" if self._exports_to_keep is None: return", "under which each export is in a versioned subdirectory. \"\"\"", "self._event_file_pattern = event_file_pattern self._model_dir = None self._best_eval_result = None self._exports_to_keep", "None or self._compare_fn( best_eval_result=self._best_eval_result, current_eval_result=eval_result): tf_logging.info('Performing best model export.') self._best_eval_result", "evaluation results should have the values for MetricKeys.LOSS, which are", "must include best_eval_result argument.' % compare_fn) if 'current_eval_result' not in", "graph and checkpoints of the best models. This class performs", "Returns: True if current evaluation result is better; otherwise, False.", "assets.extra directory within the exported SavedModel. Each key should give", "garbage-collected. Defaults to 5. Set to `None` to disable garbage", "serving_input_receiver_fn = ( tf.estimator.export.build_parsing_serving_input_receiver_fn( serving_feature_spec)) exporter = tf.estimator.BestExporter( name=\"best_exporter\", serving_input_receiver_fn=serving_input_receiver_fn,", "list(args - set(['best_eval_result', 'current_eval_result'])) if non_valid_args: raise ValueError('compare_fn (%s) has", "model. * `current_eval_result`: This is the evaluation result of current", "gc._largest_export_versions(self._exports_to_keep) delete_filter = gc._negation(keep_filter) for p in delete_filter( gc._get_paths(export_dir_base, parser=_export_version_parser)):", "float(v) for k, v in eval_result.items()} self._copy_checkpoint(checkpoint_path, export_result_path, eval_result[\"global_step\"]) self._garbage_collect_exports(export_path)", "recursively: %s', p.path, e) # pylint: enable=protected-access def _get_best_eval_result(self, event_files):", "self._log[export_result_path] = {k: float(v) for k, v in eval_result.items()} self._copy_checkpoint(checkpoint_path,", "serving_feature_spec = tf.feature_column.make_parse_example_spec( categorial_feature_a_emb) serving_input_receiver_fn = ( tf.estimator.export.build_parsing_serving_input_receiver_fn( serving_feature_spec)) exporter", "to `None` to disable garbage collection. Raises: ValueError: if any", "Exporter, _SavedModelExporter def _verify_compare_fn_args(compare_fn): \"\"\"Verifies compare_fn arguments.\"\"\" args = set(util.fn_args(compare_fn))", "None return path._replace(export_version=int(filename)) # pylint: disable=protected-access keep_filter = gc._largest_export_versions(self._exports_to_keep) delete_filter", "raise ValueError( 'compare_fn (%s) must include current_eval_result argument.' % compare_fn)", "will be garbage-collected. Defaults to 5. Set to `None` to", "default_key not in current_eval_result: raise ValueError( 'current_eval_result cannot be empty", "to 5. Set to `None` to disable garbage collection. Raises:", "a BestExporter for training and evluation: ```python def make_train_and_eval_fn(): #", "categorial_feature_a = ( tf.feature_column.categorical_column_with_hash_bucket(...)) categorial_feature_a_emb = embedding_column( categorical_column=categorial_feature_a, ...) ...", "or no loss is found in it.') if not current_eval_result", "a `ServingInputReceiver`. event_file_pattern: event file name pattern relative to model_dir.", "Returns: The best eval result. \"\"\" if not event_files: return", "the serving graph and checkpoints of the best models. This", "export_result = None if self._model_dir != estimator.model_dir and self._event_file_pattern: #", "exports_to_keep self._log = {} if exports_to_keep is not None and", "delete_filter( gc._get_paths(export_dir_base, parser=_export_version_parser)): try: del self._log[p.path] gfile.DeleteRecursively(p.path) except errors_impl.NotFoundError as", "versioned subdirectory. \"\"\" if self._exports_to_keep is None: return def _export_version_parser(path):", "def _garbage_collect_exports(self, export_dir_base): \"\"\"Deletes older exports, retaining only a given", "1 best_eval_result = event_eval_result if event_count < 2: return None", "Older exports will be garbage-collected. Defaults to 5. Set to", "eval_spec = [tf.estimator.EvalSpec( input_fn=eval_input_fn, steps=100, exporters=exporter, start_delay_secs=0, throttle_secs=5)] return tf.estimator.DistributedTrainingSpec(estimator,", "in it.') if not current_eval_result or default_key not in current_eval_result:", "Each key should give the destination path (including the filename)", "steps=100, exporters=exporter, start_delay_secs=0, throttle_secs=5)] return tf.estimator.DistributedTrainingSpec(estimator, train_spec, eval_spec) ``` Args:", "raise ValueError('`compare_fn` must not be None.') _verify_compare_fn_args(self._compare_fn) self._saved_model_exporter = _SavedModelExporter(", "directory. filename = os.path.basename(path.path) if not (len(filename) == 10 and", "files. Returns: The best eval result. \"\"\" if not event_files:", "if best_eval_result is None or self._compare_fn( best_eval_result, event_eval_result): event_count +=", "tensorflow.python.estimator.canned import metric_keys from tensorflow.python.framework import errors_impl from tensorflow.python.platform import", "serving graph and checkpoints of the best models. This class", "if len(self._log) == 0: self._best_eval_result = None if self._best_eval_result is", "open(os.path.join(dest_path, 'checkpoint'), 'w') as fp: text = 'model_checkpoint_path: \"model.ckpt-number\"\\n'.replace('number', str(step))", "== 0: self._best_eval_result = None if self._best_eval_result is None or", "the simple case of copying a single file without renaming", "self._compare_fn( best_eval_result=self._best_eval_result, current_eval_result=eval_result): tf_logging.info('Performing best model export.') self._best_eval_result = eval_result", "is found in it.') return best_eval_result[default_key] > current_eval_result[default_key] class BestExporter(Exporter):", "delete_filter = gc._negation(keep_filter) for p in delete_filter( gc._get_paths(export_dir_base, parser=_export_version_parser)): try:", "filename) relative to the assets.extra directory. The corresponding value gives", "fp) return export_result def _copy_checkpoint(self, checkpoint_pattern, dest_path, step): for file", "self._log = json.load(open(os.path.join(export_path, 'export.log'), 'r')) except json.JSONDecodeError: pass if len(self._log)", "event_count = 0 best_eval_result = None for event_file in gfile.Glob(os.path.join(event_files)):", "from event files. Args: event_files: Absolute pattern of event files.", "than any exsiting model. \"\"\" def __init__(self, name='best_exporter', serving_input_receiver_fn=None, event_file_pattern='eval/*.tfevents.*',", "destination path (including the filename) relative to the assets.extra directory.", "monotonically increasing integers; the most recent are taken to be", "= _SavedModelExporter( name, serving_input_receiver_fn, assets_extra, as_text) self._event_file_pattern = event_file_pattern self._model_dir", "Example of creating a BestExporter for training and evluation: ```python", "serving_input_receiver_fn: a function that takes no arguments and returns a", "case of copying a single file without renaming it is", "eval_result, is_the_final_export): export_result = None if self._model_dir != estimator.model_dir and", "\"\"\"Create an `Exporter` to use with `tf.estimator.EvalSpec`. Example of creating", "= None self._exports_to_keep = exports_to_keep self._log = {} if exports_to_keep", "specified. compare_fn: a function that compares two evaluation results and", "config=tf.estimator.RunConfig( model_dir='/my_model', save_summary_steps=100), feature_columns=[categorial_feature_a_emb, ...], hidden_units=[1024, 512, 256]) serving_feature_spec =", "'`exports_to_keep`, if provided, must be positive number') @property def name(self):", "is found in it.') if not current_eval_result or default_key not", "\"\"\" self._compare_fn = compare_fn if self._compare_fn is None: raise ValueError('`compare_fn`", "the new model is better than any exsiting model. \"\"\"", "with open(os.path.join(dest_path, 'checkpoint'), 'w') as fp: text = 'model_checkpoint_path: \"model.ckpt-number\"\\n'.replace('number',", "= set(util.fn_args(compare_fn)) if 'best_eval_result' not in args: raise ValueError( 'compare_fn", "Args: event_files: Absolute pattern of event files. Returns: The best", "file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. as_text:", "errors_impl from tensorflow.python.platform import gfile from tensorflow.python.platform import tf_logging from", "current evaluation result is better; otherwise, False. assets_extra: An optional", "export_result_path = export_result.decode(\"utf-8\") self._log[export_result_path] = {k: float(v) for k, v", "evaluation result is better. Follows the signature: * Args: *", "json.dump(self._log, fp) return export_result def _copy_checkpoint(self, checkpoint_pattern, dest_path, step): for", "or no loss is available. \"\"\" default_key = metric_keys.MetricKeys.LOSS if", "class exports the serving graph and checkpoints of the best", "if 'best_eval_result' not in args: raise ValueError( 'compare_fn (%s) must", "collection. Raises: ValueError: if any arguments is invalid. \"\"\" self._compare_fn", "be those with the largest values. Args: export_dir_base: the base", "in it.') return best_eval_result[default_key] > current_eval_result[default_key] class BestExporter(Exporter): \"\"\"This class", "are assumed to be named with monotonically increasing integers; the", "taken to be those with the largest values. Args: export_dir_base:", "gc._get_paths(export_dir_base, parser=_export_version_parser)): try: del self._log[p.path] gfile.DeleteRecursively(p.path) except errors_impl.NotFoundError as e:", "proto in text format. Defaults to `False`. exports_to_keep: Number of", "current candidate model. * Returns: True if current evaluation result", "glob import shutil from tensorflow.python.estimator import gc from tensorflow.python.estimator import", "if os.path.isfile(os.path.join(export_path, 'export.log')): self._log = {} try: self._log = json.load(open(os.path.join(export_path,", "argument.' % compare_fn) if 'current_eval_result' not in args: raise ValueError(", "fp.close() def _garbage_collect_exports(self, export_dir_base): \"\"\"Deletes older exports, retaining only a", "tf.estimator.export.build_parsing_serving_input_receiver_fn( serving_feature_spec)) exporter = tf.estimator.BestExporter( name=\"best_exporter\", serving_input_receiver_fn=serving_input_receiver_fn, exports_to_keep=5) train_spec =", "and exports_to_keep <= 0: raise ValueError( '`exports_to_keep`, if provided, must", "util from tensorflow.python.estimator.canned import metric_keys from tensorflow.python.framework import errors_impl from", "loss is available. \"\"\" default_key = metric_keys.MetricKeys.LOSS if not best_eval_result", "arguments and returns a `ServingInputReceiver`. event_file_pattern: event file name pattern", "best_eval_result: raise ValueError( 'best_eval_result cannot be empty or no loss", "columns. categorial_feature_a = ( tf.feature_column.categorical_column_with_hash_bucket(...)) categorial_feature_a_emb = embedding_column( categorical_column=categorial_feature_a, ...)", "{} try: self._log = json.load(open(os.path.join(export_path, 'export.log'), 'r')) except json.JSONDecodeError: pass", "training and evluation: ```python def make_train_and_eval_fn(): # Set up feature", "path of the source file to be copied. For example,", "to write the SavedModel proto in text format. Defaults to", "self._best_eval_result = None if self._best_eval_result is None or self._compare_fn( best_eval_result=self._best_eval_result,", "name, serving_input_receiver_fn, assets_extra, as_text) self._event_file_pattern = event_file_pattern self._model_dir = None", "if current evaluation result is better. Follows the signature: *", "import errors_impl from tensorflow.python.platform import gfile from tensorflow.python.platform import tf_logging", "= estimator.model_dir full_event_file_pattern = os.path.join(self._model_dir, self._event_file_pattern) self._best_eval_result = self._get_best_eval_result( full_event_file_pattern)", "of the most recent. Export subdirectories are assumed to be", "values. Args: export_dir_base: the base directory under which each export", "result of current candidate model. * Returns: True if current", "exports_to_keep is not None and exports_to_keep <= 0: raise ValueError(", "no arguments and returns a `ServingInputReceiver`. event_file_pattern: event file name", "(%s) must include current_eval_result argument.' % compare_fn) non_valid_args = list(args", "source file to be copied. For example, the simple case", "_copy_checkpoint(self, checkpoint_pattern, dest_path, step): for file in glob.glob(checkpoint_pattern + '*'):", "for training and evluation: ```python def make_train_and_eval_fn(): # Set up", "of the source file to be copied. For example, the", "return def _export_version_parser(path): # create a simple parser that pulls", "False. Raises: ValueError: If input eval result is None or", "model_dir='/my_model', save_summary_steps=100), feature_columns=[categorial_feature_a_emb, ...], hidden_units=[1024, 512, 256]) serving_feature_spec = tf.feature_column.make_parse_example_spec(", "gfile.Glob(os.path.join(event_files)): for event in summary_iterator.summary_iterator(event_file): if event.HasField('summary'): event_eval_result = {}", "key should give the destination path (including the filename) relative", "The corresponding value gives the full path of the source", "event_file_pattern should be specified. compare_fn: a function that compares two", "self._event_file_pattern: # Loads best metric from event files. tf_logging.info('Loading best", "for value in event.summary.value: if value.HasField('simple_value'): event_eval_result[value.tag] = value.simple_value if", "best model. * `current_eval_result`: This is the evaluation result of", "Set to `None` to disable garbage collection. Raises: ValueError: if", "unique name of this `Exporter` that is going to be", "+= 1 best_eval_result = event_eval_result if event_count < 2: return", "= self._get_best_eval_result( full_event_file_pattern) if os.path.isfile(os.path.join(export_path, 'export.log')): self._log = {} try:", "copying a single file without renaming it is specified as", "to populate the assets.extra directory within the exported SavedModel. Each", "\"\"\" def __init__(self, name='best_exporter', serving_input_receiver_fn=None, event_file_pattern='eval/*.tfevents.*', compare_fn=_loss_smaller, assets_extra=None, as_text=False, exports_to_keep=5):", "ValueError('compare_fn (%s) has following not expected args: %s' % (compare_fn,", "tf_logging from tensorflow.python.summary import summary_iterator from tensorflow.python.estimator.exporter import Exporter, _SavedModelExporter", "tf.estimator.DNNClassifier( config=tf.estimator.RunConfig( model_dir='/my_model', save_summary_steps=100), feature_columns=[categorial_feature_a_emb, ...], hidden_units=[1024, 512, 256]) serving_feature_spec", "event_file_pattern self._model_dir = None self._best_eval_result = None self._exports_to_keep = exports_to_keep", "is not None and exports_to_keep <= 0: raise ValueError( '`exports_to_keep`,", "= json.load(open(os.path.join(export_path, 'export.log'), 'r')) except json.JSONDecodeError: pass if len(self._log) ==", "from tensorflow.python.estimator import util from tensorflow.python.estimator.canned import metric_keys from tensorflow.python.framework", "current_eval_result): \"\"\"Compares two evaluation results and returns true if the", "%s' % (compare_fn, non_valid_args)) def _loss_smaller(best_eval_result, current_eval_result): \"\"\"Compares two evaluation", "feature_columns=[categorial_feature_a_emb, ...], hidden_units=[1024, 512, 256]) serving_feature_spec = tf.feature_column.make_parse_example_spec( categorial_feature_a_emb) serving_input_receiver_fn", "exports to keep. Older exports will be garbage-collected. Defaults to", "= list(args - set(['best_eval_result', 'current_eval_result'])) if non_valid_args: raise ValueError('compare_fn (%s)", "ValueError( 'compare_fn (%s) must include current_eval_result argument.' % compare_fn) non_valid_args", "garbage collection. Raises: ValueError: if any arguments is invalid. \"\"\"", "save_summary_steps=100), feature_columns=[categorial_feature_a_emb, ...], hidden_units=[1024, 512, 256]) serving_feature_spec = tf.feature_column.make_parse_example_spec( categorial_feature_a_emb)", "event_files: Absolute pattern of event files. Returns: The best eval", "the source file to be copied. For example, the simple", "to use with `tf.estimator.EvalSpec`. Example of creating a BestExporter for", "self._log = {} try: self._log = json.load(open(os.path.join(export_path, 'export.log'), 'r')) except", "metric from event files.') self._model_dir = estimator.model_dir full_event_file_pattern = os.path.join(self._model_dir,", "export_result_path, eval_result[\"global_step\"]) self._garbage_collect_exports(export_path) with open(os.path.join(export_path, 'export.log'), 'w') as fp: json.dump(self._log,", "gc._negation(keep_filter) for p in delete_filter( gc._get_paths(export_dir_base, parser=_export_version_parser)): try: del self._log[p.path]", "def _loss_smaller(best_eval_result, current_eval_result): \"\"\"Compares two evaluation results and returns true", "serving_input_receiver_fn=None, event_file_pattern='eval/*.tfevents.*', compare_fn=_loss_smaller, assets_extra=None, as_text=False, exports_to_keep=5): \"\"\"Create an `Exporter` to", "returns a `ServingInputReceiver`. event_file_pattern: event file name pattern relative to", "event files.') self._model_dir = estimator.model_dir full_event_file_pattern = os.path.join(self._model_dir, self._event_file_pattern) self._best_eval_result", "= {k: float(v) for k, v in eval_result.items()} self._copy_checkpoint(checkpoint_path, export_result_path,", "feature columns estimator = tf.estimator.DNNClassifier( config=tf.estimator.RunConfig( model_dir='/my_model', save_summary_steps=100), feature_columns=[categorial_feature_a_emb, ...],", "in args: raise ValueError( 'compare_fn (%s) must include best_eval_result argument.'", "from __future__ import absolute_import import abc import os import json", "_get_best_eval_result(self, event_files): \"\"\"Get the best eval result from event files.", "pulls the export_version from the directory. filename = os.path.basename(path.path) if", "...) ... # other feature columns estimator = tf.estimator.DNNClassifier( config=tf.estimator.RunConfig(", "assets_extra: An optional dict specifying how to populate the assets.extra", "e: tf_logging.warn('Can not delete %s recursively: %s', p.path, e) #", "not current_eval_result or default_key not in current_eval_result: raise ValueError( 'current_eval_result", "to be named with monotonically increasing integers; the most recent", "best eval result. \"\"\" if not event_files: return None event_count", "dest_path) with open(os.path.join(dest_path, 'checkpoint'), 'w') as fp: text = 'model_checkpoint_path:", "exports_to_keep <= 0: raise ValueError( '`exports_to_keep`, if provided, must be", "set(['best_eval_result', 'current_eval_result'])) if non_valid_args: raise ValueError('compare_fn (%s) has following not", "exsiting model. \"\"\" def __init__(self, name='best_exporter', serving_input_receiver_fn=None, event_file_pattern='eval/*.tfevents.*', compare_fn=_loss_smaller, assets_extra=None,", "should be specified. compare_fn: a function that compares two evaluation", "'/path/to/my_asset_file.txt'}`. as_text: whether to write the SavedModel proto in text", "import json import glob import shutil from tensorflow.python.estimator import gc", "checkpoint_path, eval_result, is_the_final_export): export_result = None if self._model_dir != estimator.model_dir", "exporters=exporter, start_delay_secs=0, throttle_secs=5)] return tf.estimator.DistributedTrainingSpec(estimator, train_spec, eval_spec) ``` Args: name:", "evluation: ```python def make_train_and_eval_fn(): # Set up feature columns. categorial_feature_a", "@property def name(self): return self._saved_model_exporter.name def export(self, estimator, export_path, checkpoint_path,", "If input eval result is None or no loss is", "with the largest values. Args: export_dir_base: the base directory under", "abc import os import json import glob import shutil from", "`ServingInputReceiver`. event_file_pattern: event file name pattern relative to model_dir. If", "'w') as fp: text = 'model_checkpoint_path: \"model.ckpt-number\"\\n'.replace('number', str(step)) fp.write(text) fp.close()", "event file name pattern relative to model_dir. If None, however,", "if event.HasField('summary'): event_eval_result = {} for value in event.summary.value: if", "event_eval_result = {} for value in event.summary.value: if value.HasField('simple_value'): event_eval_result[value.tag]", "the exporter would not be preemption-safe. To bex preemption-safe, event_file_pattern", "if 'current_eval_result' not in args: raise ValueError( 'compare_fn (%s) must", "use with `tf.estimator.EvalSpec`. Example of creating a BestExporter for training", "tensorflow.python.estimator import util from tensorflow.python.estimator.canned import metric_keys from tensorflow.python.framework import", "that takes no arguments and returns a `ServingInputReceiver`. event_file_pattern: event", "not be preemption-safe. To bex preemption-safe, event_file_pattern should be specified.", "Absolute pattern of event files. Returns: The best eval result.", "populate the assets.extra directory within the exported SavedModel. Each key", "path._replace(export_version=int(filename)) # pylint: disable=protected-access keep_filter = gc._largest_export_versions(self._exports_to_keep) delete_filter = gc._negation(keep_filter)", "empty or no loss is found in it.') if not", "event_files): \"\"\"Get the best eval result from event files. Args:", "summary_iterator.summary_iterator(event_file): if event.HasField('summary'): event_eval_result = {} for value in event.summary.value:", "self._best_eval_result = None self._exports_to_keep = exports_to_keep self._log = {} if", "if not (len(filename) == 10 and filename.isdigit()): return None return", "not be None.') _verify_compare_fn_args(self._compare_fn) self._saved_model_exporter = _SavedModelExporter( name, serving_input_receiver_fn, assets_extra,", "used for comparison. Args: best_eval_result: best eval metrics. current_eval_result: current", "`tf.estimator.EvalSpec`. Example of creating a BestExporter for training and evluation:", "serving_feature_spec)) exporter = tf.estimator.BestExporter( name=\"best_exporter\", serving_input_receiver_fn=serving_input_receiver_fn, exports_to_keep=5) train_spec = tf.estimator.TrainSpec(...)", "del self._log[p.path] gfile.DeleteRecursively(p.path) except errors_impl.NotFoundError as e: tf_logging.warn('Can not delete", "raise ValueError( 'best_eval_result cannot be empty or no loss is", "input_fn=eval_input_fn, steps=100, exporters=exporter, start_delay_secs=0, throttle_secs=5)] return tf.estimator.DistributedTrainingSpec(estimator, train_spec, eval_spec) ```", "arguments is invalid. \"\"\" self._compare_fn = compare_fn if self._compare_fn is", "self._get_best_eval_result( full_event_file_pattern) if os.path.isfile(os.path.join(export_path, 'export.log')): self._log = {} try: self._log", "estimator, export_path, checkpoint_path, eval_result, is_the_final_export) export_result_path = export_result.decode(\"utf-8\") self._log[export_result_path] =", "= export_result.decode(\"utf-8\") self._log[export_result_path] = {k: float(v) for k, v in", "k, v in eval_result.items()} self._copy_checkpoint(checkpoint_path, export_result_path, eval_result[\"global_step\"]) self._garbage_collect_exports(export_path) with open(os.path.join(export_path,", "a versioned subdirectory. \"\"\" if self._exports_to_keep is None: return def", "import metric_keys from tensorflow.python.framework import errors_impl from tensorflow.python.platform import gfile", "best eval result from event files. Args: event_files: Absolute pattern", "subdirectory. \"\"\" if self._exports_to_keep is None: return def _export_version_parser(path): #", "not in args: raise ValueError( 'compare_fn (%s) must include current_eval_result", "'export.log')): self._log = {} try: self._log = json.load(open(os.path.join(export_path, 'export.log'), 'r'))", "the 2nd one is smaller. Both evaluation results should have", "Set up feature columns. categorial_feature_a = ( tf.feature_column.categorical_column_with_hash_bucket(...)) categorial_feature_a_emb =", "of creating a BestExporter for training and evluation: ```python def", "a function that compares two evaluation results and returns true", "exporter = tf.estimator.BestExporter( name=\"best_exporter\", serving_input_receiver_fn=serving_input_receiver_fn, exports_to_keep=5) train_spec = tf.estimator.TrainSpec(...) eval_spec", "file name pattern relative to model_dir. If None, however, the", "'compare_fn (%s) must include best_eval_result argument.' % compare_fn) if 'current_eval_result'", "it.') if not current_eval_result or default_key not in current_eval_result: raise", "= tf.estimator.DNNClassifier( config=tf.estimator.RunConfig( model_dir='/my_model', save_summary_steps=100), feature_columns=[categorial_feature_a_emb, ...], hidden_units=[1024, 512, 256])", "to be used in the export path. serving_input_receiver_fn: a function", "export(self, estimator, export_path, checkpoint_path, eval_result, is_the_final_export): export_result = None if", "compare_fn=_loss_smaller, assets_extra=None, as_text=False, exports_to_keep=5): \"\"\"Create an `Exporter` to use with", "as fp: text = 'model_checkpoint_path: \"model.ckpt-number\"\\n'.replace('number', str(step)) fp.write(text) fp.close() def", "as_text: whether to write the SavedModel proto in text format.", "pass if len(self._log) == 0: self._best_eval_result = None if self._best_eval_result", "categorical_column=categorial_feature_a, ...) ... # other feature columns estimator = tf.estimator.DNNClassifier(", "metrics. Returns: True if the loss of current_eval_result is smaller;", "is None or self._compare_fn( best_eval_result, event_eval_result): event_count += 1 best_eval_result", "renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. as_text: whether to", "be None.') _verify_compare_fn_args(self._compare_fn) self._saved_model_exporter = _SavedModelExporter( name, serving_input_receiver_fn, assets_extra, as_text)", "positive number') @property def name(self): return self._saved_model_exporter.name def export(self, estimator,", "None: raise ValueError('`compare_fn` must not be None.') _verify_compare_fn_args(self._compare_fn) self._saved_model_exporter =", "event_eval_result): event_count += 1 best_eval_result = event_eval_result if event_count <", "must include current_eval_result argument.' % compare_fn) non_valid_args = list(args -", "and checkpoints of the best models. This class performs a", "give the destination path (including the filename) relative to the", "_garbage_collect_exports(self, export_dir_base): \"\"\"Deletes older exports, retaining only a given number", "'current_eval_result'])) if non_valid_args: raise ValueError('compare_fn (%s) has following not expected", "the evaluation result of current candidate model. * Returns: True", "the assets.extra directory within the exported SavedModel. Each key should", "estimator.model_dir and self._event_file_pattern: # Loads best metric from event files.", "if not current_eval_result or default_key not in current_eval_result: raise ValueError(", "to `False`. exports_to_keep: Number of exports to keep. Older exports", "= ( tf.feature_column.categorical_column_with_hash_bucket(...)) categorial_feature_a_emb = embedding_column( categorical_column=categorial_feature_a, ...) ... #", "\"\"\"Deletes older exports, retaining only a given number of the", "and filename.isdigit()): return None return path._replace(export_version=int(filename)) # pylint: disable=protected-access keep_filter", "self._compare_fn( best_eval_result, event_eval_result): event_count += 1 best_eval_result = event_eval_result if", "(%s) must include best_eval_result argument.' % compare_fn) if 'current_eval_result' not", "if not best_eval_result or default_key not in best_eval_result: raise ValueError(", "def make_train_and_eval_fn(): # Set up feature columns. categorial_feature_a = (", "a simple parser that pulls the export_version from the directory.", "evaluation result of the best model. * `current_eval_result`: This is", "from tensorflow.python.platform import gfile from tensorflow.python.platform import tf_logging from tensorflow.python.summary", "= gc._negation(keep_filter) for p in delete_filter( gc._get_paths(export_dir_base, parser=_export_version_parser)): try: del", "evaluation results and returns true if current evaluation result is", "default_key not in best_eval_result: raise ValueError( 'best_eval_result cannot be empty", "the full path of the source file to be copied.", "provided, must be positive number') @property def name(self): return self._saved_model_exporter.name", "tensorflow.python.estimator import gc from tensorflow.python.estimator import util from tensorflow.python.estimator.canned import", "tf_logging.info('Performing best model export.') self._best_eval_result = eval_result export_result = self._saved_model_exporter.export(", "% (compare_fn, non_valid_args)) def _loss_smaller(best_eval_result, current_eval_result): \"\"\"Compares two evaluation results", "is_the_final_export) export_result_path = export_result.decode(\"utf-8\") self._log[export_result_path] = {k: float(v) for k,", "has following not expected args: %s' % (compare_fn, non_valid_args)) def", "filename = os.path.basename(path.path) if not (len(filename) == 10 and filename.isdigit()):", "eval_result, is_the_final_export) export_result_path = export_result.decode(\"utf-8\") self._log[export_result_path] = {k: float(v) for", "name pattern relative to model_dir. If None, however, the exporter", "and returns true if the 2nd one is smaller. Both", "in glob.glob(checkpoint_pattern + '*'): shutil.copy(file, dest_path) with open(os.path.join(dest_path, 'checkpoint'), 'w')", "%s', p.path, e) # pylint: enable=protected-access def _get_best_eval_result(self, event_files): \"\"\"Get", "the exported SavedModel. Each key should give the destination path", "2nd one is smaller. Both evaluation results should have the", "# create a simple parser that pulls the export_version from", "event_file_pattern: event file name pattern relative to model_dir. If None,", "event in summary_iterator.summary_iterator(event_file): if event.HasField('summary'): event_eval_result = {} for value", "_verify_compare_fn_args(compare_fn): \"\"\"Verifies compare_fn arguments.\"\"\" args = set(util.fn_args(compare_fn)) if 'best_eval_result' not", "files.') self._model_dir = estimator.model_dir full_event_file_pattern = os.path.join(self._model_dir, self._event_file_pattern) self._best_eval_result =", "metric from event files. tf_logging.info('Loading best metric from event files.')", "event_files: return None event_count = 0 best_eval_result = None for", "for comparison. Args: best_eval_result: best eval metrics. current_eval_result: current eval", "current_eval_result=eval_result): tf_logging.info('Performing best model export.') self._best_eval_result = eval_result export_result =", "export_dir_base: the base directory under which each export is in", "p in delete_filter( gc._get_paths(export_dir_base, parser=_export_version_parser)): try: del self._log[p.path] gfile.DeleteRecursively(p.path) except", "retaining only a given number of the most recent. Export", "Follows the signature: * Args: * `best_eval_result`: This is the", "no loss is available. \"\"\" default_key = metric_keys.MetricKeys.LOSS if not", "evaluation result of current candidate model. * Returns: True if", "model export everytime when the new model is better than", "set(util.fn_args(compare_fn)) if 'best_eval_result' not in args: raise ValueError( 'compare_fn (%s)", "and evluation: ```python def make_train_and_eval_fn(): # Set up feature columns.", "is None or no loss is available. \"\"\" default_key =", "the values for MetricKeys.LOSS, which are used for comparison. Args:", "Args: * `best_eval_result`: This is the evaluation result of the", "is better than any exsiting model. \"\"\" def __init__(self, name='best_exporter',", "of current candidate model. * Returns: True if current evaluation", "None if self._model_dir != estimator.model_dir and self._event_file_pattern: # Loads best", "export_path, checkpoint_path, eval_result, is_the_final_export) export_result_path = export_result.decode(\"utf-8\") self._log[export_result_path] = {k:", "to be those with the largest values. Args: export_dir_base: the", "_export_version_parser(path): # create a simple parser that pulls the export_version", "if value.HasField('simple_value'): event_eval_result[value.tag] = value.simple_value if event_eval_result: if best_eval_result is", "as fp: json.dump(self._log, fp) return export_result def _copy_checkpoint(self, checkpoint_pattern, dest_path,", "current_eval_result is smaller; otherwise, False. Raises: ValueError: If input eval", "model. * Returns: True if current evaluation result is better;", "tensorflow.python.framework import errors_impl from tensorflow.python.platform import gfile from tensorflow.python.platform import", "for event_file in gfile.Glob(os.path.join(event_files)): for event in summary_iterator.summary_iterator(event_file): if event.HasField('summary'):", "full_event_file_pattern) if os.path.isfile(os.path.join(export_path, 'export.log')): self._log = {} try: self._log =", "for k, v in eval_result.items()} self._copy_checkpoint(checkpoint_path, export_result_path, eval_result[\"global_step\"]) self._garbage_collect_exports(export_path) with", "with open(os.path.join(export_path, 'export.log'), 'w') as fp: json.dump(self._log, fp) return export_result", "assumed to be named with monotonically increasing integers; the most", "= gc._largest_export_versions(self._exports_to_keep) delete_filter = gc._negation(keep_filter) for p in delete_filter( gc._get_paths(export_dir_base,", "write the SavedModel proto in text format. Defaults to `False`.", "the export_version from the directory. filename = os.path.basename(path.path) if not", "for file in glob.glob(checkpoint_pattern + '*'): shutil.copy(file, dest_path) with open(os.path.join(dest_path,", "tf.estimator.TrainSpec(...) eval_spec = [tf.estimator.EvalSpec( input_fn=eval_input_fn, steps=100, exporters=exporter, start_delay_secs=0, throttle_secs=5)] return", "path (including the filename) relative to the assets.extra directory. The", "`Exporter` to use with `tf.estimator.EvalSpec`. Example of creating a BestExporter", "feature columns. categorial_feature_a = ( tf.feature_column.categorical_column_with_hash_bucket(...)) categorial_feature_a_emb = embedding_column( categorical_column=categorial_feature_a,", "= tf.feature_column.make_parse_example_spec( categorial_feature_a_emb) serving_input_receiver_fn = ( tf.estimator.export.build_parsing_serving_input_receiver_fn( serving_feature_spec)) exporter =", "default_key = metric_keys.MetricKeys.LOSS if not best_eval_result or default_key not in", "the SavedModel proto in text format. Defaults to `False`. exports_to_keep:", "of the best models. This class performs a model export", "* Args: * `best_eval_result`: This is the evaluation result of", "best eval metrics. current_eval_result: current eval metrics. Returns: True if", "+ '*'): shutil.copy(file, dest_path) with open(os.path.join(dest_path, 'checkpoint'), 'w') as fp:", "export is in a versioned subdirectory. \"\"\" if self._exports_to_keep is", "or self._compare_fn( best_eval_result=self._best_eval_result, current_eval_result=eval_result): tf_logging.info('Performing best model export.') self._best_eval_result =", "ValueError: if any arguments is invalid. \"\"\" self._compare_fn = compare_fn", "event files. Returns: The best eval result. \"\"\" if not", "best_eval_result is None or self._compare_fn( best_eval_result, event_eval_result): event_count += 1", "class BestExporter(Exporter): \"\"\"This class exports the serving graph and checkpoints", "BestExporter(Exporter): \"\"\"This class exports the serving graph and checkpoints of", "* `current_eval_result`: This is the evaluation result of current candidate", "compare_fn if self._compare_fn is None: raise ValueError('`compare_fn` must not be", "found in it.') if not current_eval_result or default_key not in", "start_delay_secs=0, throttle_secs=5)] return tf.estimator.DistributedTrainingSpec(estimator, train_spec, eval_spec) ``` Args: name: unique", "best_eval_result, event_eval_result): event_count += 1 best_eval_result = event_eval_result if event_count", "recent. Export subdirectories are assumed to be named with monotonically", "invalid. \"\"\" self._compare_fn = compare_fn if self._compare_fn is None: raise", "how to populate the assets.extra directory within the exported SavedModel.", "must be positive number') @property def name(self): return self._saved_model_exporter.name def", "str(step)) fp.write(text) fp.close() def _garbage_collect_exports(self, export_dir_base): \"\"\"Deletes older exports, retaining", "= 0 best_eval_result = None for event_file in gfile.Glob(os.path.join(event_files)): for", "Args: export_dir_base: the base directory under which each export is", "when the new model is better than any exsiting model.", "not in args: raise ValueError( 'compare_fn (%s) must include best_eval_result", "in gfile.Glob(os.path.join(event_files)): for event in summary_iterator.summary_iterator(event_file): if event.HasField('summary'): event_eval_result =", "args: raise ValueError( 'compare_fn (%s) must include current_eval_result argument.' %", "to disable garbage collection. Raises: ValueError: if any arguments is", "'w') as fp: json.dump(self._log, fp) return export_result def _copy_checkpoint(self, checkpoint_pattern,", "result. \"\"\" if not event_files: return None event_count = 0", "event_eval_result[value.tag] = value.simple_value if event_eval_result: if best_eval_result is None or", "one is smaller. Both evaluation results should have the values", "ValueError( 'best_eval_result cannot be empty or no loss is found", "that pulls the export_version from the directory. filename = os.path.basename(path.path)", "exports_to_keep=5) train_spec = tf.estimator.TrainSpec(...) eval_spec = [tf.estimator.EvalSpec( input_fn=eval_input_fn, steps=100, exporters=exporter,", "json import glob import shutil from tensorflow.python.estimator import gc from", "for event in summary_iterator.summary_iterator(event_file): if event.HasField('summary'): event_eval_result = {} for", "from tensorflow.python.estimator.exporter import Exporter, _SavedModelExporter def _verify_compare_fn_args(compare_fn): \"\"\"Verifies compare_fn arguments.\"\"\"", "None, however, the exporter would not be preemption-safe. To bex", "or no loss is found in it.') return best_eval_result[default_key] >", "is going to be used in the export path. serving_input_receiver_fn:", "of the best model. * `current_eval_result`: This is the evaluation", "smaller; otherwise, False. Raises: ValueError: If input eval result is", "loss of current_eval_result is smaller; otherwise, False. Raises: ValueError: If", "estimator, export_path, checkpoint_path, eval_result, is_the_final_export): export_result = None if self._model_dir", "eval_spec) ``` Args: name: unique name of this `Exporter` that", "is_the_final_export): export_result = None if self._model_dir != estimator.model_dir and self._event_file_pattern:", "name='best_exporter', serving_input_receiver_fn=None, event_file_pattern='eval/*.tfevents.*', compare_fn=_loss_smaller, assets_extra=None, as_text=False, exports_to_keep=5): \"\"\"Create an `Exporter`", "Export subdirectories are assumed to be named with monotonically increasing", "base directory under which each export is in a versioned", "parser that pulls the export_version from the directory. filename =", "metric_keys from tensorflow.python.framework import errors_impl from tensorflow.python.platform import gfile from", "best_eval_result argument.' % compare_fn) if 'current_eval_result' not in args: raise", "= os.path.join(self._model_dir, self._event_file_pattern) self._best_eval_result = self._get_best_eval_result( full_event_file_pattern) if os.path.isfile(os.path.join(export_path, 'export.log')):", "= metric_keys.MetricKeys.LOSS if not best_eval_result or default_key not in best_eval_result:", "in eval_result.items()} self._copy_checkpoint(checkpoint_path, export_result_path, eval_result[\"global_step\"]) self._garbage_collect_exports(export_path) with open(os.path.join(export_path, 'export.log'), 'w')", "not expected args: %s' % (compare_fn, non_valid_args)) def _loss_smaller(best_eval_result, current_eval_result):", "def _get_best_eval_result(self, event_files): \"\"\"Get the best eval result from event", "eval_result.items()} self._copy_checkpoint(checkpoint_path, export_result_path, eval_result[\"global_step\"]) self._garbage_collect_exports(export_path) with open(os.path.join(export_path, 'export.log'), 'w') as", "this `Exporter` that is going to be used in the", "most recent. Export subdirectories are assumed to be named with", "'current_eval_result' not in args: raise ValueError( 'compare_fn (%s) must include", "- set(['best_eval_result', 'current_eval_result'])) if non_valid_args: raise ValueError('compare_fn (%s) has following", "be specified. compare_fn: a function that compares two evaluation results", "True if the loss of current_eval_result is smaller; otherwise, False.", "None self._best_eval_result = None self._exports_to_keep = exports_to_keep self._log = {}", "result is better; otherwise, False. assets_extra: An optional dict specifying", "better; otherwise, False. assets_extra: An optional dict specifying how to", "the directory. filename = os.path.basename(path.path) if not (len(filename) == 10", "tensorflow.python.summary import summary_iterator from tensorflow.python.estimator.exporter import Exporter, _SavedModelExporter def _verify_compare_fn_args(compare_fn):", "two evaluation results and returns true if current evaluation result", "_SavedModelExporter def _verify_compare_fn_args(compare_fn): \"\"\"Verifies compare_fn arguments.\"\"\" args = set(util.fn_args(compare_fn)) if", "gfile.DeleteRecursively(p.path) except errors_impl.NotFoundError as e: tf_logging.warn('Can not delete %s recursively:", "```python def make_train_and_eval_fn(): # Set up feature columns. categorial_feature_a =", "# other feature columns estimator = tf.estimator.DNNClassifier( config=tf.estimator.RunConfig( model_dir='/my_model', save_summary_steps=100),", "export_path, checkpoint_path, eval_result, is_the_final_export): export_result = None if self._model_dir !=", "'compare_fn (%s) must include current_eval_result argument.' % compare_fn) non_valid_args =", "format. Defaults to `False`. exports_to_keep: Number of exports to keep.", "try: self._log = json.load(open(os.path.join(export_path, 'export.log'), 'r')) except json.JSONDecodeError: pass if", "in current_eval_result: raise ValueError( 'current_eval_result cannot be empty or no", "(including the filename) relative to the assets.extra directory. The corresponding", "train_spec, eval_spec) ``` Args: name: unique name of this `Exporter`", "= value.simple_value if event_eval_result: if best_eval_result is None or self._compare_fn(", "None if self._best_eval_result is None or self._compare_fn( best_eval_result=self._best_eval_result, current_eval_result=eval_result): tf_logging.info('Performing", "eval_result[\"global_step\"]) self._garbage_collect_exports(export_path) with open(os.path.join(export_path, 'export.log'), 'w') as fp: json.dump(self._log, fp)", "true if the 2nd one is smaller. Both evaluation results", "os.path.join(self._model_dir, self._event_file_pattern) self._best_eval_result = self._get_best_eval_result( full_event_file_pattern) if os.path.isfile(os.path.join(export_path, 'export.log')): self._log", "ValueError: If input eval result is None or no loss", "try: del self._log[p.path] gfile.DeleteRecursively(p.path) except errors_impl.NotFoundError as e: tf_logging.warn('Can not", "categorial_feature_a_emb = embedding_column( categorical_column=categorial_feature_a, ...) ... # other feature columns", "integers; the most recent are taken to be those with", "= os.path.basename(path.path) if not (len(filename) == 10 and filename.isdigit()): return", "pattern relative to model_dir. If None, however, the exporter would", "shutil from tensorflow.python.estimator import gc from tensorflow.python.estimator import util from", "Args: best_eval_result: best eval metrics. current_eval_result: current eval metrics. Returns:", "None self._exports_to_keep = exports_to_keep self._log = {} if exports_to_keep is", "event.HasField('summary'): event_eval_result = {} for value in event.summary.value: if value.HasField('simple_value'):", "value in event.summary.value: if value.HasField('simple_value'): event_eval_result[value.tag] = value.simple_value if event_eval_result:", "the most recent are taken to be those with the", "model_dir. If None, however, the exporter would not be preemption-safe.", "parser=_export_version_parser)): try: del self._log[p.path] gfile.DeleteRecursively(p.path) except errors_impl.NotFoundError as e: tf_logging.warn('Can", "is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. as_text: whether to write the", "as e: tf_logging.warn('Can not delete %s recursively: %s', p.path, e)", "`False`. exports_to_keep: Number of exports to keep. Older exports will", "'export.log'), 'r')) except json.JSONDecodeError: pass if len(self._log) == 0: self._best_eval_result", "eval result from event files. Args: event_files: Absolute pattern of", "best_eval_result or default_key not in best_eval_result: raise ValueError( 'best_eval_result cannot", "self._saved_model_exporter = _SavedModelExporter( name, serving_input_receiver_fn, assets_extra, as_text) self._event_file_pattern = event_file_pattern", "SavedModel proto in text format. Defaults to `False`. exports_to_keep: Number", "Returns: True if the loss of current_eval_result is smaller; otherwise,", "None event_count = 0 best_eval_result = None for event_file in", "in the export path. serving_input_receiver_fn: a function that takes no", "This is the evaluation result of current candidate model. *", "> current_eval_result[default_key] class BestExporter(Exporter): \"\"\"This class exports the serving graph", "everytime when the new model is better than any exsiting", "export_dir_base): \"\"\"Deletes older exports, retaining only a given number of", "if event_eval_result: if best_eval_result is None or self._compare_fn( best_eval_result, event_eval_result):", "function that compares two evaluation results and returns true if", "{} if exports_to_keep is not None and exports_to_keep <= 0:", "import gfile from tensorflow.python.platform import tf_logging from tensorflow.python.summary import summary_iterator", "number') @property def name(self): return self._saved_model_exporter.name def export(self, estimator, export_path,", "import abc import os import json import glob import shutil", "None for event_file in gfile.Glob(os.path.join(event_files)): for event in summary_iterator.summary_iterator(event_file): if", "= ( tf.estimator.export.build_parsing_serving_input_receiver_fn( serving_feature_spec)) exporter = tf.estimator.BestExporter( name=\"best_exporter\", serving_input_receiver_fn=serving_input_receiver_fn, exports_to_keep=5)", "or default_key not in best_eval_result: raise ValueError( 'best_eval_result cannot be", "is None: raise ValueError('`compare_fn` must not be None.') _verify_compare_fn_args(self._compare_fn) self._saved_model_exporter", "tf_logging.warn('Can not delete %s recursively: %s', p.path, e) # pylint:", "from tensorflow.python.framework import errors_impl from tensorflow.python.platform import gfile from tensorflow.python.platform", "exporter would not be preemption-safe. To bex preemption-safe, event_file_pattern should", "This is the evaluation result of the best model. *", "following not expected args: %s' % (compare_fn, non_valid_args)) def _loss_smaller(best_eval_result,", "current_eval_result argument.' % compare_fn) non_valid_args = list(args - set(['best_eval_result', 'current_eval_result']))", "of this `Exporter` that is going to be used in", "export_version from the directory. filename = os.path.basename(path.path) if not (len(filename)", "0: raise ValueError( '`exports_to_keep`, if provided, must be positive number')", "preemption-safe. To bex preemption-safe, event_file_pattern should be specified. compare_fn: a", "self._saved_model_exporter.name def export(self, estimator, export_path, checkpoint_path, eval_result, is_the_final_export): export_result =", "import shutil from tensorflow.python.estimator import gc from tensorflow.python.estimator import util", "if the loss of current_eval_result is smaller; otherwise, False. Raises:", "= {} for value in event.summary.value: if value.HasField('simple_value'): event_eval_result[value.tag] =", "\"\"\" if not event_files: return None event_count = 0 best_eval_result", "optional dict specifying how to populate the assets.extra directory within", "if current evaluation result is better; otherwise, False. assets_extra: An", "are taken to be those with the largest values. Args:", "include best_eval_result argument.' % compare_fn) if 'current_eval_result' not in args:", "directory under which each export is in a versioned subdirectory.", "are used for comparison. Args: best_eval_result: best eval metrics. current_eval_result:", "be named with monotonically increasing integers; the most recent are", "is better. Follows the signature: * Args: * `best_eval_result`: This", "class performs a model export everytime when the new model", "The best eval result. \"\"\" if not event_files: return None", "...], hidden_units=[1024, 512, 256]) serving_feature_spec = tf.feature_column.make_parse_example_spec( categorial_feature_a_emb) serving_input_receiver_fn =", "def name(self): return self._saved_model_exporter.name def export(self, estimator, export_path, checkpoint_path, eval_result,", "candidate model. * Returns: True if current evaluation result is", "event_eval_result: if best_eval_result is None or self._compare_fn( best_eval_result, event_eval_result): event_count", "\"\"\"Compares two evaluation results and returns true if the 2nd", "no loss is found in it.') if not current_eval_result or", "keep_filter = gc._largest_export_versions(self._exports_to_keep) delete_filter = gc._negation(keep_filter) for p in delete_filter(", "older exports, retaining only a given number of the most", "include current_eval_result argument.' % compare_fn) non_valid_args = list(args - set(['best_eval_result',", "compare_fn arguments.\"\"\" args = set(util.fn_args(compare_fn)) if 'best_eval_result' not in args:", "= [tf.estimator.EvalSpec( input_fn=eval_input_fn, steps=100, exporters=exporter, start_delay_secs=0, throttle_secs=5)] return tf.estimator.DistributedTrainingSpec(estimator, train_spec,", "current_eval_result: raise ValueError( 'current_eval_result cannot be empty or no loss", "% compare_fn) if 'current_eval_result' not in args: raise ValueError( 'compare_fn", "with `tf.estimator.EvalSpec`. Example of creating a BestExporter for training and", "`{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. as_text: whether to write the SavedModel proto in", "* Returns: True if current evaluation result is better; otherwise,", "estimator = tf.estimator.DNNClassifier( config=tf.estimator.RunConfig( model_dir='/my_model', save_summary_steps=100), feature_columns=[categorial_feature_a_emb, ...], hidden_units=[1024, 512,", "non_valid_args = list(args - set(['best_eval_result', 'current_eval_result'])) if non_valid_args: raise ValueError('compare_fn", "models. This class performs a model export everytime when the", "to the assets.extra directory. The corresponding value gives the full", "name of this `Exporter` that is going to be used", "returns true if the 2nd one is smaller. Both evaluation", "results and returns true if the 2nd one is smaller.", "'model_checkpoint_path: \"model.ckpt-number\"\\n'.replace('number', str(step)) fp.write(text) fp.close() def _garbage_collect_exports(self, export_dir_base): \"\"\"Deletes older", "the base directory under which each export is in a", "def _export_version_parser(path): # create a simple parser that pulls the", "a given number of the most recent. Export subdirectories are", "<= 0: raise ValueError( '`exports_to_keep`, if provided, must be positive", "fp.write(text) fp.close() def _garbage_collect_exports(self, export_dir_base): \"\"\"Deletes older exports, retaining only", "value.HasField('simple_value'): event_eval_result[value.tag] = value.simple_value if event_eval_result: if best_eval_result is None", "a function that takes no arguments and returns a `ServingInputReceiver`.", "'*'): shutil.copy(file, dest_path) with open(os.path.join(dest_path, 'checkpoint'), 'w') as fp: text", "not event_files: return None event_count = 0 best_eval_result = None", "exports_to_keep: Number of exports to keep. Older exports will be", "= compare_fn if self._compare_fn is None: raise ValueError('`compare_fn` must not", "\"\"\"Verifies compare_fn arguments.\"\"\" args = set(util.fn_args(compare_fn)) if 'best_eval_result' not in", "import os import json import glob import shutil from tensorflow.python.estimator", "most recent are taken to be those with the largest", "import glob import shutil from tensorflow.python.estimator import gc from tensorflow.python.estimator", "from tensorflow.python.summary import summary_iterator from tensorflow.python.estimator.exporter import Exporter, _SavedModelExporter def", "import util from tensorflow.python.estimator.canned import metric_keys from tensorflow.python.framework import errors_impl", "from the directory. filename = os.path.basename(path.path) if not (len(filename) ==", "in text format. Defaults to `False`. exports_to_keep: Number of exports", "that is going to be used in the export path.", "return self._saved_model_exporter.name def export(self, estimator, export_path, checkpoint_path, eval_result, is_the_final_export): export_result", "result is None or no loss is available. \"\"\" default_key", "should give the destination path (including the filename) relative to", "simple parser that pulls the export_version from the directory. filename", "example, the simple case of copying a single file without", "`best_eval_result`: This is the evaluation result of the best model.", "0: self._best_eval_result = None if self._best_eval_result is None or self._compare_fn(", "not delete %s recursively: %s', p.path, e) # pylint: enable=protected-access", "`None` to disable garbage collection. Raises: ValueError: if any arguments", "= embedding_column( categorical_column=categorial_feature_a, ...) ... # other feature columns estimator", "directory. The corresponding value gives the full path of the", "from tensorflow.python.estimator import gc from tensorflow.python.estimator import util from tensorflow.python.estimator.canned", "full path of the source file to be copied. For", "fp: text = 'model_checkpoint_path: \"model.ckpt-number\"\\n'.replace('number', str(step)) fp.write(text) fp.close() def _garbage_collect_exports(self,", "'checkpoint'), 'w') as fp: text = 'model_checkpoint_path: \"model.ckpt-number\"\\n'.replace('number', str(step)) fp.write(text)", "= None if self._model_dir != estimator.model_dir and self._event_file_pattern: # Loads", "256]) serving_feature_spec = tf.feature_column.make_parse_example_spec( categorial_feature_a_emb) serving_input_receiver_fn = ( tf.estimator.export.build_parsing_serving_input_receiver_fn( serving_feature_spec))" ]
[ "to wrap :param new_type: new node_type \"\"\" sf = object.__setattr__", "__init__(self, restrict, new_type): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to wrap", ":type node_type: string :param node_type: type of this restriction. \"\"\"", "def __init__(self, node_type=None, negate=False): \"\"\" :param node_type: the restriction type", "all derivatives *should* be __slot__ based (lot of instances may", "that always yields a specific boolean\"\"\" __slots__ = (\"type\", \"negate\")", "uses :obj:`partial` to pass a node_type to the wrapped class,", "<<EMAIL> # Copyright: 2006 <NAME> <<EMAIL>> # License: BSD/GPL2 \"\"\"", "**kw): return not self.negate def __iter__(self): return iter(()) def __str__(self):", "% (node_type,) doc = cls.__doc__ result = partial(cls, node_type=node_type) if", "*a, **kw): return not self._restrict.match(*a, **kw) def __str__(self): return \"not", "= False def __init__(self, restrict, new_type): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base`", "to return for the match \"\"\" object.__setattr__(self, \"negate\", negate) object.__setattr__(self,", "( self.__class__.__name__, self.negate, id(self)) def __getstate__(self): return self.negate, self.type def", "restrict: :obj:`pkgcore.restrictions.restriction.base` instance to negate \"\"\" sf = object.__setattr__ sf(self,", "class FakeType(base): \"\"\"wrapper to wrap and fake a node_type\"\"\" __slots__", ":obj:`pkgcore.restrictions.restriction.base` instance to negate \"\"\" sf = object.__setattr__ sf(self, \"type\",", "always yields a specific boolean\"\"\" __slots__ = (\"type\", \"negate\") __inst_caching__", "restriction :param childrestriction: child restriction applied to every value. :type", "# License: BSD/GPL2 \"\"\" base restriction class \"\"\" from functools", "self._restrict.match(*a, **kw) def __str__(self): return \"Faked type(%s): %s\" % (self.type,", "class, and extends the docstring. :param cls: callable (usually a", "False def __init__(self, restrict, new_type): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance", "(lot of instances may wind up in memory). \"\"\" __inst_caching__", "% ( self.__class__.__name__, self.negate, id(self)) def __getstate__(self): return self.negate, self.type", ":param new_type: new node_type \"\"\" sf = object.__setattr__ sf(self, \"type\",", "__getstate__(self): return self.negate, self.type def __setstate__(self, state): negate, node_type =", "False def __init__(self, restrict): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to", "sequence.\"\"\" __slots__ = ('restriction', 'type', 'negate') def __init__(self, childrestriction, node_type,", "\"\"\"wrap and negate a restriction instance\"\"\" __slots__ = (\"type\", \"_restrict\")", "def __str__(self): return \"any: %s match\" % (self.restriction,) def __repr__(self):", "FakeType(base): \"\"\"wrapper to wrap and fake a node_type\"\"\" __slots__ =", "'negate') def __init__(self, childrestriction, node_type, negate=False): \"\"\"Initialize. :type childrestriction: restriction", "\"\"\" sf = object.__setattr__ sf(self, \"type\", new_type) sf(self, \"_restrict\", restrict)", "__iter__(self): return iter(()) def __str__(self): return f\"always '{self.negate}'\" def __repr__(self):", "\"_restrict\") __inst_caching__ = False def __init__(self, restrict, new_type): \"\"\" :param", "= False klass.inject_immutable_instance(locals()) def match(self, *arg, **kwargs): raise NotImplementedError def", "import caching, klass from snakeoil.currying import pretty_docs class base(object, metaclass=caching.WeakInstMeta):", "return for the match \"\"\" object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\",", "Negate(base): \"\"\"wrap and negate a restriction instance\"\"\" __slots__ = (\"type\",", "\"\"\"Initialize. :type childrestriction: restriction :param childrestriction: child restriction applied to", "is wrapped. :param node_type: value passed as node_type. :param extradoc:", "*a, **kw): return not self.negate def __iter__(self): return iter(()) def", "pass a node_type to the wrapped class, and extends the", ":param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to negate \"\"\" sf = object.__setattr__", "1 class AlwaysBool(base): \"\"\"restriction that always yields a specific boolean\"\"\"", "wind up in memory). \"\"\" __inst_caching__ = True # __weakref__", "\"type\", node_type) def match(self, val): for x in val: if", "class Negate(base): \"\"\"wrap and negate a restriction instance\"\"\" __slots__ =", "negate) object.__setattr__(self, \"type\", node_type) class Negate(base): \"\"\"wrap and negate a", ":param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to wrap :param new_type: new node_type", "__str__(self): return \"not (%s)\" % self._restrict class FakeType(base): \"\"\"wrapper to", "match(self, *a, **kw): return not self._restrict.match(*a, **kw) def __str__(self): return", "klass from snakeoil.currying import pretty_docs class base(object, metaclass=caching.WeakInstMeta): \"\"\"base restriction", "__inst_caching__ = False def __init__(self, restrict, new_type): \"\"\" :param restrict:", "childrestriction, node_type, negate=False): \"\"\"Initialize. :type childrestriction: restriction :param childrestriction: child", "else: # do this so indentation on pydoc __doc__ is", "new_type): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to wrap :param new_type:", "**kw): return not self._restrict.match(*a, **kw) def __str__(self): return \"not (%s)\"", "instance should be, typically :obj:`pkgcore.restrictions.packages.package_type` or :obj:`pkgcore.restrictions.values.value_type` :param negate: boolean", "__slots__ = () package_matching = False klass.inject_immutable_instance(locals()) def match(self, *arg,", "__slots__ = (\"type\", \"_restrict\") __inst_caching__ = False def __init__(self, restrict):", "to negate \"\"\" sf = object.__setattr__ sf(self, \"type\", restrict.type) sf(self,", "+ \"\\n\" doc += extradoc return pretty_docs(result, doc) value_type =", "for the match \"\"\" object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\", node_type)", "*arg, **kwargs): return self.match(*arg, **kwargs) def __len__(self): return 1 class", "def curry_node_type(cls, node_type, extradoc=None): \"\"\"Helper function for creating restrictions of", "def match(self, val): for x in val: if self.restriction.match(x): return", "doc += extradoc return pretty_docs(result, doc) value_type = \"values\" package_type", "sf = object.__setattr__ sf(self, \"type\", restrict.type) sf(self, \"_restrict\", restrict) def", "\"_restrict\", restrict) def match(self, *a, **kw): return not self._restrict.match(*a, **kw)", "@%#8x>' % ( self.__class__.__name__, self.restriction, id(self)) def curry_node_type(cls, node_type, extradoc=None):", "this restriction. \"\"\" sf = object.__setattr__ sf(self, \"negate\", negate) sf(self,", "type. This uses :obj:`partial` to pass a node_type to the", "% (self.type, self._restrict) class AnyMatch(base): \"\"\"Apply a nested restriction to", "function for creating restrictions of a certain type. This uses", "state): negate, node_type = state object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\",", "wrap :param new_type: new node_type \"\"\" sf = object.__setattr__ sf(self,", "%s type.\" % (node_type,) doc = cls.__doc__ result = partial(cls,", "self.negate, self.type def __setstate__(self, state): negate, node_type = state object.__setattr__(self,", "based (lot of instances may wind up in memory). \"\"\"", "**kwargs): return self.match(*arg, **kwargs) def __len__(self): return 1 class AlwaysBool(base):", "not self.match(*arg, **kwargs) def force_True(self, *arg, **kwargs): return self.match(*arg, **kwargs)", "for line in doc.split(\"\\n\")) + \"\\n\" doc += extradoc return", "return self._restrict.match(*a, **kw) def __str__(self): return \"Faked type(%s): %s\" %", "\"\"\" from functools import partial from snakeoil import caching, klass", "**kwargs) def __len__(self): return 1 class AlwaysBool(base): \"\"\"restriction that always", "node_type :return: a wrapped callable. \"\"\" if extradoc is None:", "doc = \"\\n\".join(line.lstrip() for line in doc.split(\"\\n\")) + \"\\n\" doc", "self.negate, id(self)) def __getstate__(self): return self.negate, self.type def __setstate__(self, state):", "node_type \"\"\" sf = object.__setattr__ sf(self, \"type\", new_type) sf(self, \"_restrict\",", "doc = '' else: # do this so indentation on", "snakeoil.currying import pretty_docs class base(object, metaclass=caching.WeakInstMeta): \"\"\"base restriction matching object.", "= (\"type\", \"_restrict\") __inst_caching__ = False def __init__(self, restrict, new_type):", "= \"\\n\".join(line.lstrip() for line in doc.split(\"\\n\")) + \"\\n\" doc +=", "'<%s always %r @%#8x>' % ( self.__class__.__name__, self.negate, id(self)) def", "negate) object.__setattr__(self, \"type\", node_type) def match(self, *a, **kw): return self.negate", "def __str__(self): return \"not (%s)\" % self._restrict class FakeType(base): \"\"\"wrapper", "Copyright: 2005-2012 <NAME> <<EMAIL> # Copyright: 2006 <NAME> <<EMAIL>> #", "__str__(self): return \"Faked type(%s): %s\" % (self.type, self._restrict) class AnyMatch(base):", "addition to the docstring. Defaults to \"Automatically set to %s", "negate \"\"\" sf = object.__setattr__ sf(self, \"type\", restrict.type) sf(self, \"_restrict\",", "functools import partial from snakeoil import caching, klass from snakeoil.currying", "to the wrapped class, and extends the docstring. :param cls:", ":param childrestriction: child restriction applied to every value. :type node_type:", "match(self, *arg, **kwargs): raise NotImplementedError def force_False(self, *arg, **kwargs): return", "to wrap and fake a node_type\"\"\" __slots__ = (\"type\", \"_restrict\")", "restriction instance\"\"\" __slots__ = (\"type\", \"_restrict\") __inst_caching__ = False def", "to %s type.\" % (node_type,) doc = cls.__doc__ result =", "metaclass __slots__ = () package_matching = False klass.inject_immutable_instance(locals()) def match(self,", "is None: extradoc = \"Automatically set to %s type.\" %", "\"\"\"Helper function for creating restrictions of a certain type. This", "in memory). \"\"\" __inst_caching__ = True # __weakref__ here is", "= (\"type\", \"negate\") __inst_caching__ = True def __init__(self, node_type=None, negate=False):", "of this restriction. \"\"\" sf = object.__setattr__ sf(self, \"negate\", negate)", "\"negate\") __inst_caching__ = True def __init__(self, node_type=None, negate=False): \"\"\" :param", "return self.negate def force_True(self, *a, **kw): return self.negate def force_False(self,", "return '<%s restriction=%r @%#8x>' % ( self.__class__.__name__, self.restriction, id(self)) def", "return \"any: %s match\" % (self.restriction,) def __repr__(self): return '<%s", "the metaclass __slots__ = () package_matching = False klass.inject_immutable_instance(locals()) def", "__init__(self, childrestriction, node_type, negate=False): \"\"\"Initialize. :type childrestriction: restriction :param childrestriction:", "class base(object, metaclass=caching.WeakInstMeta): \"\"\"base restriction matching object. all derivatives *should*", "from snakeoil import caching, klass from snakeoil.currying import pretty_docs class", "restriction type the instance should be, typically :obj:`pkgcore.restrictions.packages.package_type` or :obj:`pkgcore.restrictions.values.value_type`", "**kwargs) def force_True(self, *arg, **kwargs): return self.match(*arg, **kwargs) def __len__(self):", "__setstate__(self, state): negate, node_type = state object.__setattr__(self, \"negate\", negate) object.__setattr__(self,", "extradoc is None: extradoc = \"Automatically set to %s type.\"", ":param negate: boolean to return for the match \"\"\" object.__setattr__(self,", "(self.type, self._restrict) class AnyMatch(base): \"\"\"Apply a nested restriction to every", "certain type. This uses :obj:`partial` to pass a node_type to", "\"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to negate \"\"\" sf =", "package_matching = False klass.inject_immutable_instance(locals()) def match(self, *arg, **kwargs): raise NotImplementedError", "restriction=%r @%#8x>' % ( self.__class__.__name__, self.restriction, id(self)) def curry_node_type(cls, node_type,", "return self.negate def __str__(self): return \"any: %s match\" % (self.restriction,)", "instances may wind up in memory). \"\"\" __inst_caching__ = True", "the wrapped class, and extends the docstring. :param cls: callable", "def __init__(self, restrict): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to negate", "of instances may wind up in memory). \"\"\" __inst_caching__ =", "childrestriction) sf(self, \"type\", node_type) def match(self, val): for x in", "'<%s restriction=%r @%#8x>' % ( self.__class__.__name__, self.restriction, id(self)) def curry_node_type(cls,", "restriction applied to every value. :type node_type: string :param node_type:", "node_type, negate=False): \"\"\"Initialize. :type childrestriction: restriction :param childrestriction: child restriction", "def __str__(self): return \"Faked type(%s): %s\" % (self.type, self._restrict) class", "is sane doc = \"\\n\".join(line.lstrip() for line in doc.split(\"\\n\")) +", "restriction to every item in a sequence.\"\"\" __slots__ = ('restriction',", "__doc__ is sane doc = \"\\n\".join(line.lstrip() for line in doc.split(\"\\n\"))", "type.\" % (node_type,) doc = cls.__doc__ result = partial(cls, node_type=node_type)", "not self._restrict.match(*a, **kw) def __str__(self): return \"not (%s)\" % self._restrict", "AnyMatch(base): \"\"\"Apply a nested restriction to every item in a", "self.match(*arg, **kwargs) def force_True(self, *arg, **kwargs): return self.match(*arg, **kwargs) def", "object.__setattr__(self, \"type\", node_type) def match(self, *a, **kw): return self.negate def", "val): for x in val: if self.restriction.match(x): return not self.negate", "in doc.split(\"\\n\")) + \"\\n\" doc += extradoc return pretty_docs(result, doc)", "def force_False(self, *a, **kw): return not self.negate def __iter__(self): return", "return not self.negate def __iter__(self): return iter(()) def __str__(self): return", "value. :type node_type: string :param node_type: type of this restriction.", "extradoc = \"Automatically set to %s type.\" % (node_type,) doc", "node_type) def match(self, *a, **kw): return self.negate def force_True(self, *a,", "sf(self, \"restriction\", childrestriction) sf(self, \"type\", node_type) def match(self, val): for", "base(object, metaclass=caching.WeakInstMeta): \"\"\"base restriction matching object. all derivatives *should* be", "% ( self.__class__.__name__, self.restriction, id(self)) def curry_node_type(cls, node_type, extradoc=None): \"\"\"Helper", "% self._restrict class FakeType(base): \"\"\"wrapper to wrap and fake a", "wrapped. :param node_type: value passed as node_type. :param extradoc: addition", "if self.restriction.match(x): return not self.negate return self.negate def __str__(self): return", "self.negate def __str__(self): return \"any: %s match\" % (self.restriction,) def", "for x in val: if self.restriction.match(x): return not self.negate return", "not self.negate def __iter__(self): return iter(()) def __str__(self): return f\"always", "__inst_caching__ = True def __init__(self, node_type=None, negate=False): \"\"\" :param node_type:", "def __init__(self, restrict, new_type): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to", "the docstring. :param cls: callable (usually a class) that is", "restriction class \"\"\" from functools import partial from snakeoil import", "= ('restriction', 'type', 'negate') def __init__(self, childrestriction, node_type, negate=False): \"\"\"Initialize.", "\"\"\" sf = object.__setattr__ sf(self, \"negate\", negate) sf(self, \"restriction\", childrestriction)", "match(self, *a, **kw): return self._restrict.match(*a, **kw) def __str__(self): return \"Faked", "and extends the docstring. :param cls: callable (usually a class)", "\"Automatically set to %s type.\" % (node_type,) doc = cls.__doc__", "\"type\", node_type) def match(self, *a, **kw): return self.negate def force_True(self,", "restrict) def match(self, *a, **kw): return self._restrict.match(*a, **kw) def __str__(self):", "**kw): return self.negate def force_False(self, *a, **kw): return not self.negate", "__str__(self): return f\"always '{self.negate}'\" def __repr__(self): return '<%s always %r", "wrapped callable. \"\"\" if extradoc is None: extradoc = \"Automatically", "License: BSD/GPL2 \"\"\" base restriction class \"\"\" from functools import", "# Copyright: 2006 <NAME> <<EMAIL>> # License: BSD/GPL2 \"\"\" base", "negate a restriction instance\"\"\" __slots__ = (\"type\", \"_restrict\") __inst_caching__ =", "the match \"\"\" object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\", node_type) def", "self._restrict.match(*a, **kw) def __str__(self): return \"not (%s)\" % self._restrict class", "set to %s type.\" % node_type :return: a wrapped callable.", "derivatives *should* be __slot__ based (lot of instances may wind", ":param cls: callable (usually a class) that is wrapped. :param", "type the instance should be, typically :obj:`pkgcore.restrictions.packages.package_type` or :obj:`pkgcore.restrictions.values.value_type` :param", "return not self.negate return self.negate def __str__(self): return \"any: %s", "**kw): return self.negate def force_True(self, *a, **kw): return self.negate def", "self.type def __setstate__(self, state): negate, node_type = state object.__setattr__(self, \"negate\",", "return \"Faked type(%s): %s\" % (self.type, self._restrict) class AnyMatch(base): \"\"\"Apply", "def force_True(self, *a, **kw): return self.negate def force_False(self, *a, **kw):", "def match(self, *a, **kw): return not self._restrict.match(*a, **kw) def __str__(self):", "2006 <NAME> <<EMAIL>> # License: BSD/GPL2 \"\"\" base restriction class", "self.negate def __iter__(self): return iter(()) def __str__(self): return f\"always '{self.negate}'\"", "\"type\", node_type) class Negate(base): \"\"\"wrap and negate a restriction instance\"\"\"", "__len__(self): return 1 class AlwaysBool(base): \"\"\"restriction that always yields a", "%s type.\" % node_type :return: a wrapped callable. \"\"\" if", "node_type, extradoc=None): \"\"\"Helper function for creating restrictions of a certain", "pydoc __doc__ is sane doc = \"\\n\".join(line.lstrip() for line in", "every value. :type node_type: string :param node_type: type of this", ":param node_type: type of this restriction. \"\"\" sf = object.__setattr__", "__weakref__ here is implicit via the metaclass __slots__ = ()", "iter(()) def __str__(self): return f\"always '{self.negate}'\" def __repr__(self): return '<%s", "sf(self, \"negate\", negate) sf(self, \"restriction\", childrestriction) sf(self, \"type\", node_type) def", "\"\"\" object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\", node_type) def match(self, *a,", "def match(self, *a, **kw): return self._restrict.match(*a, **kw) def __str__(self): return", "return self.negate def force_False(self, *a, **kw): return not self.negate def", "boolean to return for the match \"\"\" object.__setattr__(self, \"negate\", negate)", "child restriction applied to every value. :type node_type: string :param", "doc.split(\"\\n\")) + \"\\n\" doc += extradoc return pretty_docs(result, doc) value_type", "class \"\"\" from functools import partial from snakeoil import caching,", "to pass a node_type to the wrapped class, and extends", "matching object. all derivatives *should* be __slot__ based (lot of", "to %s type.\" % node_type :return: a wrapped callable. \"\"\"", "for creating restrictions of a certain type. This uses :obj:`partial`", "__inst_caching__ = True # __weakref__ here is implicit via the", "sf = object.__setattr__ sf(self, \"type\", new_type) sf(self, \"_restrict\", restrict) def", "a wrapped callable. \"\"\" if extradoc is None: extradoc =", "instance to wrap :param new_type: new node_type \"\"\" sf =", "(self.restriction,) def __repr__(self): return '<%s restriction=%r @%#8x>' % ( self.__class__.__name__,", "\"\"\"restriction that always yields a specific boolean\"\"\" __slots__ = (\"type\",", "boolean\"\"\" __slots__ = (\"type\", \"negate\") __inst_caching__ = True def __init__(self,", "caching, klass from snakeoil.currying import pretty_docs class base(object, metaclass=caching.WeakInstMeta): \"\"\"base", "cls.__doc__ result = partial(cls, node_type=node_type) if doc is None: doc", "callable. \"\"\" if extradoc is None: extradoc = \"Automatically set", "self.match(*arg, **kwargs) def __len__(self): return 1 class AlwaysBool(base): \"\"\"restriction that", "def __iter__(self): return iter(()) def __str__(self): return f\"always '{self.negate}'\" def", "object.__setattr__ sf(self, \"type\", new_type) sf(self, \"_restrict\", restrict) def match(self, *a,", "\"\"\" if extradoc is None: extradoc = \"Automatically set to", "partial from snakeoil import caching, klass from snakeoil.currying import pretty_docs", "__slot__ based (lot of instances may wind up in memory).", "def force_True(self, *arg, **kwargs): return self.match(*arg, **kwargs) def __len__(self): return", "= \"Automatically set to %s type.\" % (node_type,) doc =", "and fake a node_type\"\"\" __slots__ = (\"type\", \"_restrict\") __inst_caching__ =", "(\"type\", \"negate\") __inst_caching__ = True def __init__(self, node_type=None, negate=False): \"\"\"", "\"Automatically set to %s type.\" % node_type :return: a wrapped", "(node_type,) doc = cls.__doc__ result = partial(cls, node_type=node_type) if doc", "to the docstring. Defaults to \"Automatically set to %s type.\"", "up in memory). \"\"\" __inst_caching__ = True # __weakref__ here", "def __init__(self, childrestriction, node_type, negate=False): \"\"\"Initialize. :type childrestriction: restriction :param", "item in a sequence.\"\"\" __slots__ = ('restriction', 'type', 'negate') def", "yields a specific boolean\"\"\" __slots__ = (\"type\", \"negate\") __inst_caching__ =", "new_type: new node_type \"\"\" sf = object.__setattr__ sf(self, \"type\", new_type)", "= True def __init__(self, node_type=None, negate=False): \"\"\" :param node_type: the", "% (self.restriction,) def __repr__(self): return '<%s restriction=%r @%#8x>' % (", "extradoc: addition to the docstring. Defaults to \"Automatically set to", "the instance should be, typically :obj:`pkgcore.restrictions.packages.package_type` or :obj:`pkgcore.restrictions.values.value_type` :param negate:", "__init__(self, node_type=None, negate=False): \"\"\" :param node_type: the restriction type the", "on pydoc __doc__ is sane doc = \"\\n\".join(line.lstrip() for line", "extradoc=None): \"\"\"Helper function for creating restrictions of a certain type.", "this so indentation on pydoc __doc__ is sane doc =", "*should* be __slot__ based (lot of instances may wind up", "is implicit via the metaclass __slots__ = () package_matching =", "extends the docstring. :param cls: callable (usually a class) that", "node_type) class Negate(base): \"\"\"wrap and negate a restriction instance\"\"\" __slots__", "'{self.negate}'\" def __repr__(self): return '<%s always %r @%#8x>' % (", "a specific boolean\"\"\" __slots__ = (\"type\", \"negate\") __inst_caching__ = True", "sf(self, \"_restrict\", restrict) def match(self, *a, **kw): return self._restrict.match(*a, **kw)", "f\"always '{self.negate}'\" def __repr__(self): return '<%s always %r @%#8x>' %", "This uses :obj:`partial` to pass a node_type to the wrapped", "callable (usually a class) that is wrapped. :param node_type: value", "force_False(self, *a, **kw): return not self.negate def __iter__(self): return iter(())", "= '' else: # do this so indentation on pydoc", "wrapped class, and extends the docstring. :param cls: callable (usually", "%s\" % (self.type, self._restrict) class AnyMatch(base): \"\"\"Apply a nested restriction", "= object.__setattr__ sf(self, \"type\", restrict.type) sf(self, \"_restrict\", restrict) def match(self,", "\"negate\", negate) sf(self, \"restriction\", childrestriction) sf(self, \"type\", node_type) def match(self,", "Copyright: 2006 <NAME> <<EMAIL>> # License: BSD/GPL2 \"\"\" base restriction", "instance to negate \"\"\" sf = object.__setattr__ sf(self, \"type\", restrict.type)", "= object.__setattr__ sf(self, \"negate\", negate) sf(self, \"restriction\", childrestriction) sf(self, \"type\",", "a node_type\"\"\" __slots__ = (\"type\", \"_restrict\") __inst_caching__ = False def", "self.negate def force_False(self, *a, **kw): return not self.negate def __iter__(self):", "from snakeoil.currying import pretty_docs class base(object, metaclass=caching.WeakInstMeta): \"\"\"base restriction matching", "match\" % (self.restriction,) def __repr__(self): return '<%s restriction=%r @%#8x>' %", "(\"type\", \"_restrict\") __inst_caching__ = False def __init__(self, restrict): \"\"\" :param", "object.__setattr__ sf(self, \"negate\", negate) sf(self, \"restriction\", childrestriction) sf(self, \"type\", node_type)", "cls: callable (usually a class) that is wrapped. :param node_type:", "__slots__ = ('restriction', 'type', 'negate') def __init__(self, childrestriction, node_type, negate=False):", "\"Faked type(%s): %s\" % (self.type, self._restrict) class AnyMatch(base): \"\"\"Apply a", "self._restrict) class AnyMatch(base): \"\"\"Apply a nested restriction to every item", "node_type: the restriction type the instance should be, typically :obj:`pkgcore.restrictions.packages.package_type`", "sf(self, \"type\", new_type) sf(self, \"_restrict\", restrict) def match(self, *a, **kw):", "or :obj:`pkgcore.restrictions.values.value_type` :param negate: boolean to return for the match", "\"\\n\" doc += extradoc return pretty_docs(result, doc) value_type = \"values\"", ":obj:`pkgcore.restrictions.restriction.base` instance to wrap :param new_type: new node_type \"\"\" sf", "def __len__(self): return 1 class AlwaysBool(base): \"\"\"restriction that always yields", "<NAME> <<EMAIL>> # License: BSD/GPL2 \"\"\" base restriction class \"\"\"", "__repr__(self): return '<%s restriction=%r @%#8x>' % ( self.__class__.__name__, self.restriction, id(self))", "# __weakref__ here is implicit via the metaclass __slots__ =", "node_type\"\"\" __slots__ = (\"type\", \"_restrict\") __inst_caching__ = False def __init__(self,", "a certain type. This uses :obj:`partial` to pass a node_type", "node_type. :param extradoc: addition to the docstring. Defaults to \"Automatically", "negate: boolean to return for the match \"\"\" object.__setattr__(self, \"negate\",", "self.restriction.match(x): return not self.negate return self.negate def __str__(self): return \"any:", "typically :obj:`pkgcore.restrictions.packages.package_type` or :obj:`pkgcore.restrictions.values.value_type` :param negate: boolean to return for", "def __getstate__(self): return self.negate, self.type def __setstate__(self, state): negate, node_type", "__inst_caching__ = False def __init__(self, restrict): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base`", "docstring. Defaults to \"Automatically set to %s type.\" % node_type", "of a certain type. This uses :obj:`partial` to pass a", "class AnyMatch(base): \"\"\"Apply a nested restriction to every item in", "= state object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\", node_type) class Negate(base):", "return not self._restrict.match(*a, **kw) def __str__(self): return \"not (%s)\" %", "\"any: %s match\" % (self.restriction,) def __repr__(self): return '<%s restriction=%r", "the docstring. Defaults to \"Automatically set to %s type.\" %", "*arg, **kwargs): return not self.match(*arg, **kwargs) def force_True(self, *arg, **kwargs):", "doc = cls.__doc__ result = partial(cls, node_type=node_type) if doc is", "implicit via the metaclass __slots__ = () package_matching = False", "**kw) def __str__(self): return \"not (%s)\" % self._restrict class FakeType(base):", "x in val: if self.restriction.match(x): return not self.negate return self.negate", "return f\"always '{self.negate}'\" def __repr__(self): return '<%s always %r @%#8x>'", "pretty_docs(result, doc) value_type = \"values\" package_type = \"package\" valid_types =", "object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\", node_type) def match(self, *a, **kw):", "force_True(self, *arg, **kwargs): return self.match(*arg, **kwargs) def __len__(self): return 1", "\"\"\"Apply a nested restriction to every item in a sequence.\"\"\"", "__init__(self, restrict): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to negate \"\"\"", "import pretty_docs class base(object, metaclass=caching.WeakInstMeta): \"\"\"base restriction matching object. all", "**kw) def __str__(self): return \"Faked type(%s): %s\" % (self.type, self._restrict)", "id(self)) def curry_node_type(cls, node_type, extradoc=None): \"\"\"Helper function for creating restrictions", "to \"Automatically set to %s type.\" % node_type :return: a", "every item in a sequence.\"\"\" __slots__ = ('restriction', 'type', 'negate')", "node_type) def match(self, val): for x in val: if self.restriction.match(x):", "\"\"\" __inst_caching__ = True # __weakref__ here is implicit via", "return iter(()) def __str__(self): return f\"always '{self.negate}'\" def __repr__(self): return", "result = partial(cls, node_type=node_type) if doc is None: doc =", "\"restriction\", childrestriction) sf(self, \"type\", node_type) def match(self, val): for x", "\"type\", restrict.type) sf(self, \"_restrict\", restrict) def match(self, *a, **kw): return", "object.__setattr__(self, \"type\", node_type) class Negate(base): \"\"\"wrap and negate a restriction", "extradoc return pretty_docs(result, doc) value_type = \"values\" package_type = \"package\"", "type(%s): %s\" % (self.type, self._restrict) class AnyMatch(base): \"\"\"Apply a nested", "as node_type. :param extradoc: addition to the docstring. Defaults to", ":obj:`pkgcore.restrictions.packages.package_type` or :obj:`pkgcore.restrictions.values.value_type` :param negate: boolean to return for the", "__slots__ = (\"type\", \"negate\") __inst_caching__ = True def __init__(self, node_type=None,", "restrict): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to negate \"\"\" sf", "if doc is None: doc = '' else: # do", "restrict) def match(self, *a, **kw): return not self._restrict.match(*a, **kw) def", "type of this restriction. \"\"\" sf = object.__setattr__ sf(self, \"negate\",", "a sequence.\"\"\" __slots__ = ('restriction', 'type', 'negate') def __init__(self, childrestriction,", "def __str__(self): return f\"always '{self.negate}'\" def __repr__(self): return '<%s always", "\"\"\"wrapper to wrap and fake a node_type\"\"\" __slots__ = (\"type\",", "self.__class__.__name__, self.restriction, id(self)) def curry_node_type(cls, node_type, extradoc=None): \"\"\"Helper function for", "\"\"\"base restriction matching object. all derivatives *should* be __slot__ based", "**kw): return self._restrict.match(*a, **kw) def __str__(self): return \"Faked type(%s): %s\"", ":obj:`partial` to pass a node_type to the wrapped class, and", "self.negate return self.negate def __str__(self): return \"any: %s match\" %", "a node_type to the wrapped class, and extends the docstring.", "nested restriction to every item in a sequence.\"\"\" __slots__ =", "raise NotImplementedError def force_False(self, *arg, **kwargs): return not self.match(*arg, **kwargs)", "# do this so indentation on pydoc __doc__ is sane", "= False def __init__(self, restrict): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance", "(\"type\", \"_restrict\") __inst_caching__ = False def __init__(self, restrict, new_type): \"\"\"", "\"type\", new_type) sf(self, \"_restrict\", restrict) def match(self, *a, **kw): return", "if extradoc is None: extradoc = \"Automatically set to %s", "return pretty_docs(result, doc) value_type = \"values\" package_type = \"package\" valid_types", "\"negate\", negate) object.__setattr__(self, \"type\", node_type) def match(self, *a, **kw): return", "__slots__ = (\"type\", \"_restrict\") __inst_caching__ = False def __init__(self, restrict,", "restrictions of a certain type. This uses :obj:`partial` to pass", "state object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\", node_type) class Negate(base): \"\"\"wrap", "specific boolean\"\"\" __slots__ = (\"type\", \"negate\") __inst_caching__ = True def", "<reponame>mgorny/pkgcore<filename>src/pkgcore/restrictions/restriction.py<gh_stars>0 # Copyright: 2005-2012 <NAME> <<EMAIL> # Copyright: 2006 <NAME>", "should be, typically :obj:`pkgcore.restrictions.packages.package_type` or :obj:`pkgcore.restrictions.values.value_type` :param negate: boolean to", "\"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to wrap :param new_type: new", "*a, **kw): return self.negate def force_True(self, *a, **kw): return self.negate", "\"not (%s)\" % self._restrict class FakeType(base): \"\"\"wrapper to wrap and", "value passed as node_type. :param extradoc: addition to the docstring.", "here is implicit via the metaclass __slots__ = () package_matching", "restrict.type) sf(self, \"_restrict\", restrict) def match(self, *a, **kw): return not", "None: extradoc = \"Automatically set to %s type.\" % (node_type,)", ":obj:`pkgcore.restrictions.values.value_type` :param negate: boolean to return for the match \"\"\"", "sf(self, \"_restrict\", restrict) def match(self, *a, **kw): return not self._restrict.match(*a,", "docstring. :param cls: callable (usually a class) that is wrapped.", ":type childrestriction: restriction :param childrestriction: child restriction applied to every", "restrict, new_type): \"\"\" :param restrict: :obj:`pkgcore.restrictions.restriction.base` instance to wrap :param", "node_type to the wrapped class, and extends the docstring. :param", "Defaults to \"Automatically set to %s type.\" % node_type :return:", "line in doc.split(\"\\n\")) + \"\\n\" doc += extradoc return pretty_docs(result,", "__repr__(self): return '<%s always %r @%#8x>' % ( self.__class__.__name__, self.negate,", "to every item in a sequence.\"\"\" __slots__ = ('restriction', 'type',", "# Copyright: 2005-2012 <NAME> <<EMAIL> # Copyright: 2006 <NAME> <<EMAIL>>", "self.negate def force_True(self, *a, **kw): return self.negate def force_False(self, *a,", "True # __weakref__ here is implicit via the metaclass __slots__", "**kwargs): return not self.match(*arg, **kwargs) def force_True(self, *arg, **kwargs): return", "node_type=node_type) if doc is None: doc = '' else: #", "instance\"\"\" __slots__ = (\"type\", \"_restrict\") __inst_caching__ = False def __init__(self,", "childrestriction: restriction :param childrestriction: child restriction applied to every value.", "node_type: string :param node_type: type of this restriction. \"\"\" sf", "a restriction instance\"\"\" __slots__ = (\"type\", \"_restrict\") __inst_caching__ = False", "import partial from snakeoil import caching, klass from snakeoil.currying import", "= cls.__doc__ result = partial(cls, node_type=node_type) if doc is None:", "applied to every value. :type node_type: string :param node_type: type", "pretty_docs class base(object, metaclass=caching.WeakInstMeta): \"\"\"base restriction matching object. all derivatives", "def force_False(self, *arg, **kwargs): return not self.match(*arg, **kwargs) def force_True(self,", "True def __init__(self, node_type=None, negate=False): \"\"\" :param node_type: the restriction", "% node_type :return: a wrapped callable. \"\"\" if extradoc is", "in a sequence.\"\"\" __slots__ = ('restriction', 'type', 'negate') def __init__(self,", "creating restrictions of a certain type. This uses :obj:`partial` to", "BSD/GPL2 \"\"\" base restriction class \"\"\" from functools import partial", "= object.__setattr__ sf(self, \"type\", new_type) sf(self, \"_restrict\", restrict) def match(self,", "a nested restriction to every item in a sequence.\"\"\" __slots__", "not self.negate return self.negate def __str__(self): return \"any: %s match\"", "to every value. :type node_type: string :param node_type: type of", "a class) that is wrapped. :param node_type: value passed as", "force_False(self, *arg, **kwargs): return not self.match(*arg, **kwargs) def force_True(self, *arg,", "() package_matching = False klass.inject_immutable_instance(locals()) def match(self, *arg, **kwargs): raise", "sane doc = \"\\n\".join(line.lstrip() for line in doc.split(\"\\n\")) + \"\\n\"", "+= extradoc return pretty_docs(result, doc) value_type = \"values\" package_type =", "new node_type \"\"\" sf = object.__setattr__ sf(self, \"type\", new_type) sf(self,", "is None: doc = '' else: # do this so", "__str__(self): return \"any: %s match\" % (self.restriction,) def __repr__(self): return", "(usually a class) that is wrapped. :param node_type: value passed", "memory). \"\"\" __inst_caching__ = True # __weakref__ here is implicit", "return \"not (%s)\" % self._restrict class FakeType(base): \"\"\"wrapper to wrap", "the restriction type the instance should be, typically :obj:`pkgcore.restrictions.packages.package_type` or", "\"negate\", negate) object.__setattr__(self, \"type\", node_type) class Negate(base): \"\"\"wrap and negate", "def match(self, *a, **kw): return self.negate def force_True(self, *a, **kw):", "node_type: value passed as node_type. :param extradoc: addition to the", "False klass.inject_immutable_instance(locals()) def match(self, *arg, **kwargs): raise NotImplementedError def force_False(self,", "do this so indentation on pydoc __doc__ is sane doc", "negate, node_type = state object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\", node_type)", "= () package_matching = False klass.inject_immutable_instance(locals()) def match(self, *arg, **kwargs):", "new_type) sf(self, \"_restrict\", restrict) def match(self, *a, **kw): return self._restrict.match(*a,", "metaclass=caching.WeakInstMeta): \"\"\"base restriction matching object. all derivatives *should* be __slot__", "return not self.match(*arg, **kwargs) def force_True(self, *arg, **kwargs): return self.match(*arg,", "doc) value_type = \"values\" package_type = \"package\" valid_types = (value_type,", "AlwaysBool(base): \"\"\"restriction that always yields a specific boolean\"\"\" __slots__ =", "set to %s type.\" % (node_type,) doc = cls.__doc__ result", "node_type=None, negate=False): \"\"\" :param node_type: the restriction type the instance", "value_type = \"values\" package_type = \"package\" valid_types = (value_type, package_type)", "**kwargs): raise NotImplementedError def force_False(self, *arg, **kwargs): return not self.match(*arg,", "doc is None: doc = '' else: # do this", ":param extradoc: addition to the docstring. Defaults to \"Automatically set", "\"\"\" sf = object.__setattr__ sf(self, \"type\", restrict.type) sf(self, \"_restrict\", restrict)", "node_type = state object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\", node_type) class", "match(self, *a, **kw): return self.negate def force_True(self, *a, **kw): return", "<<EMAIL>> # License: BSD/GPL2 \"\"\" base restriction class \"\"\" from", "\"\"\" base restriction class \"\"\" from functools import partial from", "None: doc = '' else: # do this so indentation", "*a, **kw): return self._restrict.match(*a, **kw) def __str__(self): return \"Faked type(%s):", "match \"\"\" object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\", node_type) def match(self,", "id(self)) def __getstate__(self): return self.negate, self.type def __setstate__(self, state): negate,", "self.restriction, id(self)) def curry_node_type(cls, node_type, extradoc=None): \"\"\"Helper function for creating", "self._restrict class FakeType(base): \"\"\"wrapper to wrap and fake a node_type\"\"\"", "be, typically :obj:`pkgcore.restrictions.packages.package_type` or :obj:`pkgcore.restrictions.values.value_type` :param negate: boolean to return", "base restriction class \"\"\" from functools import partial from snakeoil", "sf(self, \"type\", node_type) def match(self, val): for x in val:", "( self.__class__.__name__, self.restriction, id(self)) def curry_node_type(cls, node_type, extradoc=None): \"\"\"Helper function", "\"\"\" :param node_type: the restriction type the instance should be,", "*arg, **kwargs): raise NotImplementedError def force_False(self, *arg, **kwargs): return not", "negate) sf(self, \"restriction\", childrestriction) sf(self, \"type\", node_type) def match(self, val):", ":return: a wrapped callable. \"\"\" if extradoc is None: extradoc", "object.__setattr__ sf(self, \"type\", restrict.type) sf(self, \"_restrict\", restrict) def match(self, *a,", "%s match\" % (self.restriction,) def __repr__(self): return '<%s restriction=%r @%#8x>'", "def __repr__(self): return '<%s restriction=%r @%#8x>' % ( self.__class__.__name__, self.restriction,", "<NAME> <<EMAIL> # Copyright: 2006 <NAME> <<EMAIL>> # License: BSD/GPL2", "restriction matching object. all derivatives *should* be __slot__ based (lot", "wrap and fake a node_type\"\"\" __slots__ = (\"type\", \"_restrict\") __inst_caching__", "fake a node_type\"\"\" __slots__ = (\"type\", \"_restrict\") __inst_caching__ = False", "return self.negate, self.type def __setstate__(self, state): negate, node_type = state", "and negate a restriction instance\"\"\" __slots__ = (\"type\", \"_restrict\") __inst_caching__", "node_type: type of this restriction. \"\"\" sf = object.__setattr__ sf(self,", "\"_restrict\", restrict) def match(self, *a, **kw): return self._restrict.match(*a, **kw) def", "(%s)\" % self._restrict class FakeType(base): \"\"\"wrapper to wrap and fake", "'' else: # do this so indentation on pydoc __doc__", "via the metaclass __slots__ = () package_matching = False klass.inject_immutable_instance(locals())", "sf(self, \"type\", restrict.type) sf(self, \"_restrict\", restrict) def match(self, *a, **kw):", ":param node_type: value passed as node_type. :param extradoc: addition to", "def __repr__(self): return '<%s always %r @%#8x>' % ( self.__class__.__name__,", "return '<%s always %r @%#8x>' % ( self.__class__.__name__, self.negate, id(self))", "string :param node_type: type of this restriction. \"\"\" sf =", "from functools import partial from snakeoil import caching, klass from", "may wind up in memory). \"\"\" __inst_caching__ = True #", "object.__setattr__(self, \"negate\", negate) object.__setattr__(self, \"type\", node_type) class Negate(base): \"\"\"wrap and", "val: if self.restriction.match(x): return not self.negate return self.negate def __str__(self):", "curry_node_type(cls, node_type, extradoc=None): \"\"\"Helper function for creating restrictions of a", "that is wrapped. :param node_type: value passed as node_type. :param", "@%#8x>' % ( self.__class__.__name__, self.negate, id(self)) def __getstate__(self): return self.negate,", "so indentation on pydoc __doc__ is sane doc = \"\\n\".join(line.lstrip()", "restriction. \"\"\" sf = object.__setattr__ sf(self, \"negate\", negate) sf(self, \"restriction\",", "childrestriction: child restriction applied to every value. :type node_type: string", "object. all derivatives *should* be __slot__ based (lot of instances", "= (\"type\", \"_restrict\") __inst_caching__ = False def __init__(self, restrict): \"\"\"", ":param node_type: the restriction type the instance should be, typically", "'type', 'negate') def __init__(self, childrestriction, node_type, negate=False): \"\"\"Initialize. :type childrestriction:", "= partial(cls, node_type=node_type) if doc is None: doc = ''", "2005-2012 <NAME> <<EMAIL> # Copyright: 2006 <NAME> <<EMAIL>> # License:", "('restriction', 'type', 'negate') def __init__(self, childrestriction, node_type, negate=False): \"\"\"Initialize. :type", "\"\\n\".join(line.lstrip() for line in doc.split(\"\\n\")) + \"\\n\" doc += extradoc", "restrict: :obj:`pkgcore.restrictions.restriction.base` instance to wrap :param new_type: new node_type \"\"\"", "negate=False): \"\"\"Initialize. :type childrestriction: restriction :param childrestriction: child restriction applied", "%r @%#8x>' % ( self.__class__.__name__, self.negate, id(self)) def __getstate__(self): return", "def __setstate__(self, state): negate, node_type = state object.__setattr__(self, \"negate\", negate)", "*a, **kw): return self.negate def force_False(self, *a, **kw): return not", "in val: if self.restriction.match(x): return not self.negate return self.negate def", "return 1 class AlwaysBool(base): \"\"\"restriction that always yields a specific", "indentation on pydoc __doc__ is sane doc = \"\\n\".join(line.lstrip() for", "be __slot__ based (lot of instances may wind up in", "always %r @%#8x>' % ( self.__class__.__name__, self.negate, id(self)) def __getstate__(self):", "passed as node_type. :param extradoc: addition to the docstring. Defaults", "def match(self, *arg, **kwargs): raise NotImplementedError def force_False(self, *arg, **kwargs):", "\"_restrict\") __inst_caching__ = False def __init__(self, restrict): \"\"\" :param restrict:", "klass.inject_immutable_instance(locals()) def match(self, *arg, **kwargs): raise NotImplementedError def force_False(self, *arg,", "class) that is wrapped. :param node_type: value passed as node_type.", "type.\" % node_type :return: a wrapped callable. \"\"\" if extradoc", "force_True(self, *a, **kw): return self.negate def force_False(self, *a, **kw): return", "NotImplementedError def force_False(self, *arg, **kwargs): return not self.match(*arg, **kwargs) def", "match(self, val): for x in val: if self.restriction.match(x): return not", "= True # __weakref__ here is implicit via the metaclass", "self.__class__.__name__, self.negate, id(self)) def __getstate__(self): return self.negate, self.type def __setstate__(self,", "return self.match(*arg, **kwargs) def __len__(self): return 1 class AlwaysBool(base): \"\"\"restriction", "snakeoil import caching, klass from snakeoil.currying import pretty_docs class base(object,", "negate=False): \"\"\" :param node_type: the restriction type the instance should", "partial(cls, node_type=node_type) if doc is None: doc = '' else:", "sf = object.__setattr__ sf(self, \"negate\", negate) sf(self, \"restriction\", childrestriction) sf(self,", "class AlwaysBool(base): \"\"\"restriction that always yields a specific boolean\"\"\" __slots__" ]
[ "= None def upgrade(engine_name): globals()[f\"upgrade_{engine_name}\"]() def downgrade(engine_name): globals()[f\"downgrade_{engine_name}\"]() def upgrade_registrar():", "pass def downgrade_registrar(): pass def upgrade_cloud_verifier(): with op.batch_alter_table(\"verifiermain\") as batch_op:", "revision identifiers, used by Alembic. revision = \"8da20383f6e1\" down_revision =", "alembic import op # revision identifiers, used by Alembic. revision", "= \"8da20383f6e1\" down_revision = \"<KEY>\" branch_labels = None depends_on =", "sqlalchemy as sa from alembic import op # revision identifiers,", "def upgrade_cloud_verifier(): with op.batch_alter_table(\"verifiermain\") as batch_op: batch_op.alter_column( \"ip\", existing_type=sa.String(length=15), type_=sa.String(length=255),", "branch_labels = None depends_on = None def upgrade(engine_name): globals()[f\"upgrade_{engine_name}\"]() def", "Date: 2021-01-14 10:50:56.275257 \"\"\" import sqlalchemy as sa from alembic", "sa from alembic import op # revision identifiers, used by", "as sa from alembic import op # revision identifiers, used", "def upgrade(engine_name): globals()[f\"upgrade_{engine_name}\"]() def downgrade(engine_name): globals()[f\"downgrade_{engine_name}\"]() def upgrade_registrar(): pass def", "from alembic import op # revision identifiers, used by Alembic.", "batch_op: batch_op.alter_column( \"ip\", existing_type=sa.String(length=15), type_=sa.String(length=255), existing_nullable=True ) def downgrade_cloud_verifier(): pass", "used by Alembic. revision = \"8da20383f6e1\" down_revision = \"<KEY>\" branch_labels", "\"\"\"extend_ip_field Revision ID: 8da20383f6e1 Revises: <KEY> Create Date: 2021-01-14 10:50:56.275257", "= None depends_on = None def upgrade(engine_name): globals()[f\"upgrade_{engine_name}\"]() def downgrade(engine_name):", "as batch_op: batch_op.alter_column( \"ip\", existing_type=sa.String(length=15), type_=sa.String(length=255), existing_nullable=True ) def downgrade_cloud_verifier():", "with op.batch_alter_table(\"verifiermain\") as batch_op: batch_op.alter_column( \"ip\", existing_type=sa.String(length=15), type_=sa.String(length=255), existing_nullable=True )", "upgrade(engine_name): globals()[f\"upgrade_{engine_name}\"]() def downgrade(engine_name): globals()[f\"downgrade_{engine_name}\"]() def upgrade_registrar(): pass def downgrade_registrar():", "depends_on = None def upgrade(engine_name): globals()[f\"upgrade_{engine_name}\"]() def downgrade(engine_name): globals()[f\"downgrade_{engine_name}\"]() def", "\"8da20383f6e1\" down_revision = \"<KEY>\" branch_labels = None depends_on = None", "op.batch_alter_table(\"verifiermain\") as batch_op: batch_op.alter_column( \"ip\", existing_type=sa.String(length=15), type_=sa.String(length=255), existing_nullable=True ) def", "ID: 8da20383f6e1 Revises: <KEY> Create Date: 2021-01-14 10:50:56.275257 \"\"\" import", "def downgrade(engine_name): globals()[f\"downgrade_{engine_name}\"]() def upgrade_registrar(): pass def downgrade_registrar(): pass def", "Revision ID: 8da20383f6e1 Revises: <KEY> Create Date: 2021-01-14 10:50:56.275257 \"\"\"", "Alembic. revision = \"8da20383f6e1\" down_revision = \"<KEY>\" branch_labels = None", "globals()[f\"upgrade_{engine_name}\"]() def downgrade(engine_name): globals()[f\"downgrade_{engine_name}\"]() def upgrade_registrar(): pass def downgrade_registrar(): pass", "10:50:56.275257 \"\"\" import sqlalchemy as sa from alembic import op", "revision = \"8da20383f6e1\" down_revision = \"<KEY>\" branch_labels = None depends_on", "Create Date: 2021-01-14 10:50:56.275257 \"\"\" import sqlalchemy as sa from", "2021-01-14 10:50:56.275257 \"\"\" import sqlalchemy as sa from alembic import", "Revises: <KEY> Create Date: 2021-01-14 10:50:56.275257 \"\"\" import sqlalchemy as", "def downgrade_registrar(): pass def upgrade_cloud_verifier(): with op.batch_alter_table(\"verifiermain\") as batch_op: batch_op.alter_column(", "\"<KEY>\" branch_labels = None depends_on = None def upgrade(engine_name): globals()[f\"upgrade_{engine_name}\"]()", "None def upgrade(engine_name): globals()[f\"upgrade_{engine_name}\"]() def downgrade(engine_name): globals()[f\"downgrade_{engine_name}\"]() def upgrade_registrar(): pass", "\"\"\" import sqlalchemy as sa from alembic import op #", "identifiers, used by Alembic. revision = \"8da20383f6e1\" down_revision = \"<KEY>\"", "None depends_on = None def upgrade(engine_name): globals()[f\"upgrade_{engine_name}\"]() def downgrade(engine_name): globals()[f\"downgrade_{engine_name}\"]()", "= \"<KEY>\" branch_labels = None depends_on = None def upgrade(engine_name):", "def upgrade_registrar(): pass def downgrade_registrar(): pass def upgrade_cloud_verifier(): with op.batch_alter_table(\"verifiermain\")", "upgrade_registrar(): pass def downgrade_registrar(): pass def upgrade_cloud_verifier(): with op.batch_alter_table(\"verifiermain\") as", "8da20383f6e1 Revises: <KEY> Create Date: 2021-01-14 10:50:56.275257 \"\"\" import sqlalchemy", "<KEY> Create Date: 2021-01-14 10:50:56.275257 \"\"\" import sqlalchemy as sa", "op # revision identifiers, used by Alembic. revision = \"8da20383f6e1\"", "import op # revision identifiers, used by Alembic. revision =", "pass def upgrade_cloud_verifier(): with op.batch_alter_table(\"verifiermain\") as batch_op: batch_op.alter_column( \"ip\", existing_type=sa.String(length=15),", "upgrade_cloud_verifier(): with op.batch_alter_table(\"verifiermain\") as batch_op: batch_op.alter_column( \"ip\", existing_type=sa.String(length=15), type_=sa.String(length=255), existing_nullable=True", "downgrade(engine_name): globals()[f\"downgrade_{engine_name}\"]() def upgrade_registrar(): pass def downgrade_registrar(): pass def upgrade_cloud_verifier():", "by Alembic. revision = \"8da20383f6e1\" down_revision = \"<KEY>\" branch_labels =", "down_revision = \"<KEY>\" branch_labels = None depends_on = None def", "globals()[f\"downgrade_{engine_name}\"]() def upgrade_registrar(): pass def downgrade_registrar(): pass def upgrade_cloud_verifier(): with", "downgrade_registrar(): pass def upgrade_cloud_verifier(): with op.batch_alter_table(\"verifiermain\") as batch_op: batch_op.alter_column( \"ip\",", "import sqlalchemy as sa from alembic import op # revision", "# revision identifiers, used by Alembic. revision = \"8da20383f6e1\" down_revision" ]
[ "# ola mundo import sys for line in sys.stdin: lexer.input(line)", "mundo import sys for line in sys.stdin: lexer.input(line) for tok", "t_OPERADORES = '[+|*|-]' t_ignore='\\n\\t ' def t_error(t): print(\"Erro\") print(t) lexer", "# 1+2 1-2 1*2 # ola mundo import sys for", "print(t) lexer = lex.lex() # 1+2 1-2 1*2 # ola", "= '\\d+' t_OPERADORES = '[+|*|-]' t_ignore='\\n\\t ' def t_error(t): print(\"Erro\")", "ply.lex as lex tokens =[\"NUM\",\"OPERADORES\"] t_NUM = '\\d+' t_OPERADORES =", "print(\"Erro\") print(t) lexer = lex.lex() # 1+2 1-2 1*2 #", "def t_error(t): print(\"Erro\") print(t) lexer = lex.lex() # 1+2 1-2", "lex.lex() # 1+2 1-2 1*2 # ola mundo import sys", "tokens =[\"NUM\",\"OPERADORES\"] t_NUM = '\\d+' t_OPERADORES = '[+|*|-]' t_ignore='\\n\\t '", "1+2 1-2 1*2 # ola mundo import sys for line", "t_ignore='\\n\\t ' def t_error(t): print(\"Erro\") print(t) lexer = lex.lex() #", "=[\"NUM\",\"OPERADORES\"] t_NUM = '\\d+' t_OPERADORES = '[+|*|-]' t_ignore='\\n\\t ' def", "' def t_error(t): print(\"Erro\") print(t) lexer = lex.lex() # 1+2", "<filename>token_train/quickdemo(1)(1).py import ply.lex as lex tokens =[\"NUM\",\"OPERADORES\"] t_NUM = '\\d+'", "t_error(t): print(\"Erro\") print(t) lexer = lex.lex() # 1+2 1-2 1*2", "sys for line in sys.stdin: lexer.input(line) for tok in lexer:", "as lex tokens =[\"NUM\",\"OPERADORES\"] t_NUM = '\\d+' t_OPERADORES = '[+|*|-]'", "lexer = lex.lex() # 1+2 1-2 1*2 # ola mundo", "for line in sys.stdin: lexer.input(line) for tok in lexer: print(tok)", "'\\d+' t_OPERADORES = '[+|*|-]' t_ignore='\\n\\t ' def t_error(t): print(\"Erro\") print(t)", "t_NUM = '\\d+' t_OPERADORES = '[+|*|-]' t_ignore='\\n\\t ' def t_error(t):", "ola mundo import sys for line in sys.stdin: lexer.input(line) for", "import sys for line in sys.stdin: lexer.input(line) for tok in", "= lex.lex() # 1+2 1-2 1*2 # ola mundo import", "'[+|*|-]' t_ignore='\\n\\t ' def t_error(t): print(\"Erro\") print(t) lexer = lex.lex()", "1-2 1*2 # ola mundo import sys for line in", "lex tokens =[\"NUM\",\"OPERADORES\"] t_NUM = '\\d+' t_OPERADORES = '[+|*|-]' t_ignore='\\n\\t", "1*2 # ola mundo import sys for line in sys.stdin:", "import ply.lex as lex tokens =[\"NUM\",\"OPERADORES\"] t_NUM = '\\d+' t_OPERADORES", "= '[+|*|-]' t_ignore='\\n\\t ' def t_error(t): print(\"Erro\") print(t) lexer =" ]
[ "migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes', field=models.TextField(blank=True, default=None, null=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_east_west',", "('ucsrb', '0012_auto_20180710_1249'), ] operations = [ migrations.AddField( model_name='treatmentscenario', name='landform_type', field=models.BooleanField(default=False),", "-*- coding: utf-8 -*- # Generated by Django 1.11.9 on", "20:40 from __future__ import unicode_literals from django.db import migrations, models", "), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_floor', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_north', field=models.BooleanField(default=True),", "= [ ('ucsrb', '0012_auto_20180710_1249'), ] operations = [ migrations.AddField( model_name='treatmentscenario',", "migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_east_west', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_floor', field=models.BooleanField(default=True), ),", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ucsrb',", "name='landform_type_checkboxes', field=models.TextField(blank=True, default=None, null=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_east_west', field=models.BooleanField(default=True), ),", "Generated by Django 1.11.9 on 2018-07-10 20:40 from __future__ import", "), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_ridgetop', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_south', field=models.BooleanField(default=True),", "model_name='treatmentscenario', name='landform_type_checkboxes_include_ridgetop', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_south', field=models.BooleanField(default=True), ), ]", "field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_ridgetop', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_south',", "default=None, null=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_east_west', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario',", "'0012_auto_20180710_1249'), ] operations = [ migrations.AddField( model_name='treatmentscenario', name='landform_type', field=models.BooleanField(default=False), ),", "model_name='treatmentscenario', name='landform_type_checkboxes_include_east_west', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_floor', field=models.BooleanField(default=True), ), migrations.AddField(", "migrations, models class Migration(migrations.Migration): dependencies = [ ('ucsrb', '0012_auto_20180710_1249'), ]", "model_name='treatmentscenario', name='landform_type_checkboxes_include_north', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_ridgetop', field=models.BooleanField(default=True), ), migrations.AddField(", "migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_ridgetop', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_south', field=models.BooleanField(default=True), ),", "1.11.9 on 2018-07-10 20:40 from __future__ import unicode_literals from django.db", "Migration(migrations.Migration): dependencies = [ ('ucsrb', '0012_auto_20180710_1249'), ] operations = [", "[ ('ucsrb', '0012_auto_20180710_1249'), ] operations = [ migrations.AddField( model_name='treatmentscenario', name='landform_type',", "operations = [ migrations.AddField( model_name='treatmentscenario', name='landform_type', field=models.BooleanField(default=False), ), migrations.AddField( model_name='treatmentscenario',", "# -*- coding: utf-8 -*- # Generated by Django 1.11.9", "unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "name='landform_type_checkboxes_include_north', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_ridgetop', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario',", "models class Migration(migrations.Migration): dependencies = [ ('ucsrb', '0012_auto_20180710_1249'), ] operations", "model_name='treatmentscenario', name='landform_type', field=models.BooleanField(default=False), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes', field=models.TextField(blank=True, default=None, null=True),", "name='landform_type_checkboxes_include_floor', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_north', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario',", "-*- # Generated by Django 1.11.9 on 2018-07-10 20:40 from", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "name='landform_type_checkboxes_include_east_west', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_floor', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario',", "field=models.TextField(blank=True, default=None, null=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_east_west', field=models.BooleanField(default=True), ), migrations.AddField(", "dependencies = [ ('ucsrb', '0012_auto_20180710_1249'), ] operations = [ migrations.AddField(", "utf-8 -*- # Generated by Django 1.11.9 on 2018-07-10 20:40", "migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_north', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_ridgetop', field=models.BooleanField(default=True), ),", "migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_floor', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_north', field=models.BooleanField(default=True), ),", "null=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_east_west', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_floor',", "), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_north', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_ridgetop', field=models.BooleanField(default=True),", "), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes', field=models.TextField(blank=True, default=None, null=True), ), migrations.AddField( model_name='treatmentscenario',", "model_name='treatmentscenario', name='landform_type_checkboxes', field=models.TextField(blank=True, default=None, null=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_east_west', field=models.BooleanField(default=True),", "2018-07-10 20:40 from __future__ import unicode_literals from django.db import migrations,", "import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies", "field=models.BooleanField(default=False), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes', field=models.TextField(blank=True, default=None, null=True), ), migrations.AddField(", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('ucsrb', '0012_auto_20180710_1249'),", "= [ migrations.AddField( model_name='treatmentscenario', name='landform_type', field=models.BooleanField(default=False), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes',", "class Migration(migrations.Migration): dependencies = [ ('ucsrb', '0012_auto_20180710_1249'), ] operations =", "] operations = [ migrations.AddField( model_name='treatmentscenario', name='landform_type', field=models.BooleanField(default=False), ), migrations.AddField(", "), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_east_west', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_floor', field=models.BooleanField(default=True),", "Django 1.11.9 on 2018-07-10 20:40 from __future__ import unicode_literals from", "coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-07-10", "on 2018-07-10 20:40 from __future__ import unicode_literals from django.db import", "__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):", "by Django 1.11.9 on 2018-07-10 20:40 from __future__ import unicode_literals", "from __future__ import unicode_literals from django.db import migrations, models class", "migrations.AddField( model_name='treatmentscenario', name='landform_type', field=models.BooleanField(default=False), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes', field=models.TextField(blank=True, default=None,", "model_name='treatmentscenario', name='landform_type_checkboxes_include_floor', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_north', field=models.BooleanField(default=True), ), migrations.AddField(", "[ migrations.AddField( model_name='treatmentscenario', name='landform_type', field=models.BooleanField(default=False), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes', field=models.TextField(blank=True,", "field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_floor', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_north',", "name='landform_type', field=models.BooleanField(default=False), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes', field=models.TextField(blank=True, default=None, null=True), ),", "# Generated by Django 1.11.9 on 2018-07-10 20:40 from __future__", "field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_north', field=models.BooleanField(default=True), ), migrations.AddField( model_name='treatmentscenario', name='landform_type_checkboxes_include_ridgetop'," ]
[ "new_timestamps=new_timestamps, # old_payload=old_payload, # ) # new_metrics = get_metrics(blocks=new_blocks) #", ") # new_metrics = get_metrics(blocks=new_blocks) # return combine_new_data( # old_payload=old_payload,", "old_payload=old_payload, # ) # new_metrics = get_metrics(blocks=new_blocks) # return combine_new_data(", "None = None, timescale: analytics_spec.TimescaleSpec | None = None, end_time:", "old_payload=old_payload, # ) # new_blocks = get_new_blocks( # new_timestamps=new_timestamps, #", ") return { 'version': '0.1.0', # # time data 'n_samples':", "window_size: str | None = None, interval_size: str | None", ". import metric_crud from . import analytics_spec async def async_create_payload(", "= None, ) -> analytics_spec.AnalyticsPayload: \"\"\"create data payload from scratch\"\"\"", "analytics_spec.AnalyticsPayload: # new_timestamps = get_new_timestamps( # timescale=timescale, # old_payload=old_payload, #", "# old_payload=old_payload, # ) # new_metrics = get_metrics(blocks=new_blocks) # return", "-> analytics_spec.AnalyticsPayload: \"\"\"create data payload from scratch\"\"\" time_data = await", "analytics_spec.AnalyticsPayload, # ) -> analytics_spec.AnalyticsPayload: # new_timestamps = get_new_timestamps( #", "None, timescale: analytics_spec.TimescaleSpec | None = None, end_time: analytics_spec.Timestamp |", "None, window_size: str | None = None, interval_size: str |", "import analytics_spec async def async_create_payload( *, blocks: typing.Sequence[spec.BlockNumberReference] | None", "analytics_spec.AnalyticsPayload: \"\"\"create data payload from scratch\"\"\" time_data = await timestamp_crud.async_get_time_data(", "timescale: analytics_spec.Timescale, # old_payload: analytics_spec.AnalyticsPayload, # ) -> analytics_spec.AnalyticsPayload: #", "# new_metrics = get_metrics(blocks=new_blocks) # return combine_new_data( # old_payload=old_payload, #", "# ) # new_blocks = get_new_blocks( # new_timestamps=new_timestamps, # old_payload=old_payload,", ") -> analytics_spec.AnalyticsPayload: # new_timestamps = get_new_timestamps( # timescale=timescale, #", "analytics_spec.TimescaleSpec | None = None, end_time: analytics_spec.Timestamp | None =", "blocks=blocks, timestamps=timestamps, timescale=timescale, end_time=end_time, window_size=window_size, interval_size=interval_size, provider=provider, ) # get", "async def async_create_payload( *, blocks: typing.Sequence[spec.BlockNumberReference] | None = None,", "end_time: analytics_spec.Timestamp | None = None, window_size: str | None", "None, interval_size: str | None = None, provider: spec.ProviderSpec =", "time_data = await timestamp_crud.async_get_time_data( blocks=blocks, timestamps=timestamps, timescale=timescale, end_time=end_time, window_size=window_size, interval_size=interval_size,", "# new_timestamps=new_timestamps, # old_payload=old_payload, # ) # new_metrics = get_metrics(blocks=new_blocks)", "get data data = await metric_crud.async_get_metrics( blocks=time_data['block_numbers'] ) return {", "= None, timescale: analytics_spec.TimescaleSpec | None = None, end_time: analytics_spec.Timestamp", "'0.1.0', # # time data 'n_samples': time_data['n_samples'], 'window_size': time_data['window_size'], 'interval_size':", "def async_create_payload( *, blocks: typing.Sequence[spec.BlockNumberReference] | None = None, timestamps:", "analytics_spec.Timescale, # old_payload: analytics_spec.AnalyticsPayload, # ) -> analytics_spec.AnalyticsPayload: # new_timestamps", "= get_metrics(blocks=new_blocks) # return combine_new_data( # old_payload=old_payload, # new_metrics=new_metrics, #", "async_create_payload( *, blocks: typing.Sequence[spec.BlockNumberReference] | None = None, timestamps: typing.Sequence[int]", "from scratch\"\"\" time_data = await timestamp_crud.async_get_time_data( blocks=blocks, timestamps=timestamps, timescale=timescale, end_time=end_time,", "def update_payload( # timescale: analytics_spec.Timescale, # old_payload: analytics_spec.AnalyticsPayload, # )", "import timestamp_crud from . import metric_crud from . import analytics_spec", "timescale=timescale, # old_payload=old_payload, # ) # new_blocks = get_new_blocks( #", "typing.Sequence[int] | None = None, timescale: analytics_spec.TimescaleSpec | None =", "time_data['created_at_timestamp'], # # metric data 'data': data, } # def", "provider: spec.ProviderSpec = None, ) -> analytics_spec.AnalyticsPayload: \"\"\"create data payload", "= None, provider: spec.ProviderSpec = None, ) -> analytics_spec.AnalyticsPayload: \"\"\"create", "| None = None, interval_size: str | None = None,", "get_metrics(blocks=new_blocks) # return combine_new_data( # old_payload=old_payload, # new_metrics=new_metrics, # )", "from . import analytics_spec async def async_create_payload( *, blocks: typing.Sequence[spec.BlockNumberReference]", "# metric data 'data': data, } # def update_payload( #", "# new_blocks = get_new_blocks( # new_timestamps=new_timestamps, # old_payload=old_payload, # )", "\"\"\"create data payload from scratch\"\"\" time_data = await timestamp_crud.async_get_time_data( blocks=blocks,", "data data = await metric_crud.async_get_metrics( blocks=time_data['block_numbers'] ) return { 'version':", "return { 'version': '0.1.0', # # time data 'n_samples': time_data['n_samples'],", "data 'data': data, } # def update_payload( # timescale: analytics_spec.Timescale,", "data = await metric_crud.async_get_metrics( blocks=time_data['block_numbers'] ) return { 'version': '0.1.0',", "| None = None, window_size: str | None = None,", "timestamps=timestamps, timescale=timescale, end_time=end_time, window_size=window_size, interval_size=interval_size, provider=provider, ) # get data", "metric_crud.async_get_metrics( blocks=time_data['block_numbers'] ) return { 'version': '0.1.0', # # time", "time_data['block_numbers'], 'created_at_timestamp': time_data['created_at_timestamp'], # # metric data 'data': data, }", "blocks=time_data['block_numbers'] ) return { 'version': '0.1.0', # # time data", "# timescale: analytics_spec.Timescale, # old_payload: analytics_spec.AnalyticsPayload, # ) -> analytics_spec.AnalyticsPayload:", "# time data 'n_samples': time_data['n_samples'], 'window_size': time_data['window_size'], 'interval_size': time_data['interval_size'], 'timestamps':", "from . import timestamp_crud from . import metric_crud from .", "= get_new_blocks( # new_timestamps=new_timestamps, # old_payload=old_payload, # ) # new_metrics", "import annotations import typing from ctc import spec from .", "provider=provider, ) # get data data = await metric_crud.async_get_metrics( blocks=time_data['block_numbers']", "update_payload( # timescale: analytics_spec.Timescale, # old_payload: analytics_spec.AnalyticsPayload, # ) ->", "get_new_timestamps( # timescale=timescale, # old_payload=old_payload, # ) # new_blocks =", "await timestamp_crud.async_get_time_data( blocks=blocks, timestamps=timestamps, timescale=timescale, end_time=end_time, window_size=window_size, interval_size=interval_size, provider=provider, )", "metric_crud from . import analytics_spec async def async_create_payload( *, blocks:", "__future__ import annotations import typing from ctc import spec from", "from ctc import spec from . import timestamp_crud from .", "get_new_blocks( # new_timestamps=new_timestamps, # old_payload=old_payload, # ) # new_metrics =", "import typing from ctc import spec from . import timestamp_crud", "timescale=timescale, end_time=end_time, window_size=window_size, interval_size=interval_size, provider=provider, ) # get data data", "= None, timestamps: typing.Sequence[int] | None = None, timescale: analytics_spec.TimescaleSpec", ") # get data data = await metric_crud.async_get_metrics( blocks=time_data['block_numbers'] )", "analytics_spec.Timestamp | None = None, window_size: str | None =", "None, timestamps: typing.Sequence[int] | None = None, timescale: analytics_spec.TimescaleSpec |", "timescale: analytics_spec.TimescaleSpec | None = None, end_time: analytics_spec.Timestamp | None", "time_data['window_size'], 'interval_size': time_data['interval_size'], 'timestamps': time_data['timestamps'], 'block_numbers': time_data['block_numbers'], 'created_at_timestamp': time_data['created_at_timestamp'], #", "await metric_crud.async_get_metrics( blocks=time_data['block_numbers'] ) return { 'version': '0.1.0', # #", "# # metric data 'data': data, } # def update_payload(", "= None, window_size: str | None = None, interval_size: str", "# get data data = await metric_crud.async_get_metrics( blocks=time_data['block_numbers'] ) return", "time_data['n_samples'], 'window_size': time_data['window_size'], 'interval_size': time_data['interval_size'], 'timestamps': time_data['timestamps'], 'block_numbers': time_data['block_numbers'], 'created_at_timestamp':", "# ) -> analytics_spec.AnalyticsPayload: # new_timestamps = get_new_timestamps( # timescale=timescale,", "{ 'version': '0.1.0', # # time data 'n_samples': time_data['n_samples'], 'window_size':", "'n_samples': time_data['n_samples'], 'window_size': time_data['window_size'], 'interval_size': time_data['interval_size'], 'timestamps': time_data['timestamps'], 'block_numbers': time_data['block_numbers'],", "*, blocks: typing.Sequence[spec.BlockNumberReference] | None = None, timestamps: typing.Sequence[int] |", "= None, interval_size: str | None = None, provider: spec.ProviderSpec", "interval_size: str | None = None, provider: spec.ProviderSpec = None,", "# timescale=timescale, # old_payload=old_payload, # ) # new_blocks = get_new_blocks(", "timestamps: typing.Sequence[int] | None = None, timescale: analytics_spec.TimescaleSpec | None", "scratch\"\"\" time_data = await timestamp_crud.async_get_time_data( blocks=blocks, timestamps=timestamps, timescale=timescale, end_time=end_time, window_size=window_size,", ") # new_blocks = get_new_blocks( # new_timestamps=new_timestamps, # old_payload=old_payload, #", "'interval_size': time_data['interval_size'], 'timestamps': time_data['timestamps'], 'block_numbers': time_data['block_numbers'], 'created_at_timestamp': time_data['created_at_timestamp'], # #", "None = None, window_size: str | None = None, interval_size:", "str | None = None, interval_size: str | None =", "| None = None, end_time: analytics_spec.Timestamp | None = None,", "timestamp_crud from . import metric_crud from . import analytics_spec async", "new_timestamps = get_new_timestamps( # timescale=timescale, # old_payload=old_payload, # ) #", "metric data 'data': data, } # def update_payload( # timescale:", "# old_payload: analytics_spec.AnalyticsPayload, # ) -> analytics_spec.AnalyticsPayload: # new_timestamps =", "'created_at_timestamp': time_data['created_at_timestamp'], # # metric data 'data': data, } #", "str | None = None, provider: spec.ProviderSpec = None, )", ". import analytics_spec async def async_create_payload( *, blocks: typing.Sequence[spec.BlockNumberReference] |", "} # def update_payload( # timescale: analytics_spec.Timescale, # old_payload: analytics_spec.AnalyticsPayload,", "typing from ctc import spec from . import timestamp_crud from", "spec.ProviderSpec = None, ) -> analytics_spec.AnalyticsPayload: \"\"\"create data payload from", "new_blocks = get_new_blocks( # new_timestamps=new_timestamps, # old_payload=old_payload, # ) #", "interval_size=interval_size, provider=provider, ) # get data data = await metric_crud.async_get_metrics(", "= await timestamp_crud.async_get_time_data( blocks=blocks, timestamps=timestamps, timescale=timescale, end_time=end_time, window_size=window_size, interval_size=interval_size, provider=provider,", "new_metrics = get_metrics(blocks=new_blocks) # return combine_new_data( # old_payload=old_payload, # new_metrics=new_metrics,", "None, end_time: analytics_spec.Timestamp | None = None, window_size: str |", "from __future__ import annotations import typing from ctc import spec", "| None = None, timestamps: typing.Sequence[int] | None = None,", "ctc import spec from . import timestamp_crud from . import", "| None = None, timescale: analytics_spec.TimescaleSpec | None = None,", "import spec from . import timestamp_crud from . import metric_crud", "# # time data 'n_samples': time_data['n_samples'], 'window_size': time_data['window_size'], 'interval_size': time_data['interval_size'],", "= None, end_time: analytics_spec.Timestamp | None = None, window_size: str", "data, } # def update_payload( # timescale: analytics_spec.Timescale, # old_payload:", "typing.Sequence[spec.BlockNumberReference] | None = None, timestamps: typing.Sequence[int] | None =", "None = None, timestamps: typing.Sequence[int] | None = None, timescale:", "'block_numbers': time_data['block_numbers'], 'created_at_timestamp': time_data['created_at_timestamp'], # # metric data 'data': data,", "timestamp_crud.async_get_time_data( blocks=blocks, timestamps=timestamps, timescale=timescale, end_time=end_time, window_size=window_size, interval_size=interval_size, provider=provider, ) #", "'version': '0.1.0', # # time data 'n_samples': time_data['n_samples'], 'window_size': time_data['window_size'],", "blocks: typing.Sequence[spec.BlockNumberReference] | None = None, timestamps: typing.Sequence[int] | None", "window_size=window_size, interval_size=interval_size, provider=provider, ) # get data data = await", "# def update_payload( # timescale: analytics_spec.Timescale, # old_payload: analytics_spec.AnalyticsPayload, #", "# ) # new_metrics = get_metrics(blocks=new_blocks) # return combine_new_data( #", ". import timestamp_crud from . import metric_crud from . import", "end_time=end_time, window_size=window_size, interval_size=interval_size, provider=provider, ) # get data data =", ") -> analytics_spec.AnalyticsPayload: \"\"\"create data payload from scratch\"\"\" time_data =", "-> analytics_spec.AnalyticsPayload: # new_timestamps = get_new_timestamps( # timescale=timescale, # old_payload=old_payload,", "None, ) -> analytics_spec.AnalyticsPayload: \"\"\"create data payload from scratch\"\"\" time_data", "None = None, interval_size: str | None = None, provider:", "'window_size': time_data['window_size'], 'interval_size': time_data['interval_size'], 'timestamps': time_data['timestamps'], 'block_numbers': time_data['block_numbers'], 'created_at_timestamp': time_data['created_at_timestamp'],", "data 'n_samples': time_data['n_samples'], 'window_size': time_data['window_size'], 'interval_size': time_data['interval_size'], 'timestamps': time_data['timestamps'], 'block_numbers':", "from . import metric_crud from . import analytics_spec async def", "'timestamps': time_data['timestamps'], 'block_numbers': time_data['block_numbers'], 'created_at_timestamp': time_data['created_at_timestamp'], # # metric data", "# old_payload=old_payload, # ) # new_blocks = get_new_blocks( # new_timestamps=new_timestamps,", "time_data['interval_size'], 'timestamps': time_data['timestamps'], 'block_numbers': time_data['block_numbers'], 'created_at_timestamp': time_data['created_at_timestamp'], # # metric", "None = None, provider: spec.ProviderSpec = None, ) -> analytics_spec.AnalyticsPayload:", "'data': data, } # def update_payload( # timescale: analytics_spec.Timescale, #", "import metric_crud from . import analytics_spec async def async_create_payload( *,", "old_payload: analytics_spec.AnalyticsPayload, # ) -> analytics_spec.AnalyticsPayload: # new_timestamps = get_new_timestamps(", "data payload from scratch\"\"\" time_data = await timestamp_crud.async_get_time_data( blocks=blocks, timestamps=timestamps,", "annotations import typing from ctc import spec from . import", "None, provider: spec.ProviderSpec = None, ) -> analytics_spec.AnalyticsPayload: \"\"\"create data", "# new_timestamps = get_new_timestamps( # timescale=timescale, # old_payload=old_payload, # )", "spec from . import timestamp_crud from . import metric_crud from", "payload from scratch\"\"\" time_data = await timestamp_crud.async_get_time_data( blocks=blocks, timestamps=timestamps, timescale=timescale,", "analytics_spec async def async_create_payload( *, blocks: typing.Sequence[spec.BlockNumberReference] | None =", "time_data['timestamps'], 'block_numbers': time_data['block_numbers'], 'created_at_timestamp': time_data['created_at_timestamp'], # # metric data 'data':", "None = None, end_time: analytics_spec.Timestamp | None = None, window_size:", "| None = None, provider: spec.ProviderSpec = None, ) ->", "time data 'n_samples': time_data['n_samples'], 'window_size': time_data['window_size'], 'interval_size': time_data['interval_size'], 'timestamps': time_data['timestamps'],", "= get_new_timestamps( # timescale=timescale, # old_payload=old_payload, # ) # new_blocks", "= await metric_crud.async_get_metrics( blocks=time_data['block_numbers'] ) return { 'version': '0.1.0', #" ]
[ "is on, a different latent for every timestep would be", "color channel dimension as the batch dimension since the same", "num_masks=10, stp=False, cdna=True, dna=False, context_frames=2): \"\"\"Build convolutional lstm video predictor", "tf_layers.layer_norm(hidden2, scope='layer_norm3') enc1 = slim.layers.conv2d( hidden2, hidden2.get_shape()[3], [3, 3], stride=2,", "gaussian N(mu,exp(log_sigma)) and N(0,1). Args: mu: mu parameter of the", "2.0 (the \"License\"); # you may not use this file", "image become unoccluded. transformed = [tf.nn.sigmoid(enc7)] if stp: stp_input0 =", "lower bounding tensors RELU_SHIFT = 1e-12 # kernel size for", "FLAGS.inference_time: latent = tf.cond(iter_num < FLAGS.num_iterations_1st_stage, lambda: tf.identity(latent), lambda: latent_mean", "tf.nn.depthwise_conv2d(prev_image, cdna_kerns, [1, 1, 1, 1], 'SAME') # Transpose the", "one mask is supported for DNA model.') transformed = [dna_transformation(prev_image,", "stride=2, activation_fn=None, scope='latent_mean', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm_mean'}) latent_std = slim.conv2d( latent_enc3,", "FLAGS.inference_time: # No latent tower at inference time, just standard", "= lstm_func( hidden3, lstm_state4, lstm_size[3], scope='state4') hidden4 = tf_layers.layer_norm(hidden4, scope='layer_norm5')", "current_state]) enc0 = slim.layers.conv2d( prev_image, 32, [5, 5], stride=2, scope='scale1_conv1',", "dna: # Only one mask is supported (more should be", "= None, None, None, None lstm_state5, lstm_state6, lstm_state7 = None,", "import layers as tf_layers from lstm_ops import basic_conv_lstm_cell FLAGS =", "predicting untied conv kernels. enc7 = slim.layers.conv2d_transpose( enc6, DNA_KERN_SIZE**2, 1,", "scope='latent_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm1'}) latent_enc2 = slim.conv2d( latent_enc1, 64, [3,", "own prediction. use_state: True to include state and action in", "str(i), activation_fn=None) + identity_params transformed.append(transformer(prev_image, params)) return transformed def cdna_transformation(prev_image,", "normalizer_params={'scope': 'latent_norm_mean'}) latent_std = slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3], stride=2,", "# Transpose the dimensions to where they belong. transformed =", "basic_conv_lstm_cell FLAGS = flags.FLAGS # Amount to use when lower", "enc3, lstm_state5, lstm_size[4], scope='state5') # last 8x8 hidden5 = tf_layers.layer_norm(hidden5,", "scope='state7') # 32x32 hidden7 = tf_layers.layer_norm(hidden7, scope='layer_norm8') # Skip connection.", "# Latent tower latent_loss = 0.0 if FLAGS.stochastic_model: latent_tower_outputs =", "FLAGS.multi_latent: latent = samples[timestep] if not FLAGS.inference_time: latent = tf.cond(iter_num", "if stp: stp_input0 = tf.reshape(hidden5, [int(batch_size), -1]) stp_input1 = slim.layers.fully_connected(", "[int(batch_size), -1]) transformed += cdna_transformation(prev_image, cdna_input, num_masks, int(color_channels)) elif dna:", "Feed in generated image. prev_image = gen_images[-1] elif done_warm_start: #", "num_masks, int(color_channels)) elif dna: # Only one mask is supported", "tf.gather(idx, tf.range(num_ground_truth, int(batch_size))) ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx) generated_examps = tf.gather(generated_x,", "to the main tower as an extra variable to be", "parameters. \"\"\" # Only import spatial transformer if needed. from", "= tf.concat(images, 3) latent_enc1 = slim.conv2d( stacked_images, 32, [3, 3],", "be used for computing CDNA kernels. num_masks: the number of", "image, action in zip(images[:-1], actions[:-1]): # Reuse variables after the", "the channel dimension so that # depthwise_conv2d can apply a", "+= FLAGS.latent_std_min divergence = kl_divergence(latent_mean, latent_std) latent_loss = tf.reduce_mean(divergence) if", "inference time, the tower is disabled and only returns latents", "5], stride=2, scope='scale1_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm1'}) hidden1, lstm_state1 = lstm_func(", "len(gen_images) > context_frames - 1 with slim.arg_scope( [lstm_func, slim.layers.conv2d, slim.layers.fully_connected,", "[-1, image_height, image_width, -1]), [3])) inputs = tf.concat(axis=3, values=inputs) #", "normalize. cdna_kerns = tf.reshape( cdna_kerns, [batch_size, DNA_KERN_SIZE, DNA_KERN_SIZE, 1, num_masks])", "video. This latent variable will be fed to the main", "num_masks: the number of different pixel motion predictions (and the", "License for the specific language governing permissions and # limitations", "* inputs, [3], keep_dims=False) def scheduled_sample(ground_truth_x, generated_x, batch_size, num_ground_truth): \"\"\"Sample", "idx = tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth)) generated_idx = tf.gather(idx,", "and states. lstm_size = np.int32(np.array([32, 32, 64, 64, 128, 64,", "Reserved. # # Licensed under the Apache License, Version 2.0", "lstm_size[3], scope='state4') hidden4 = tf_layers.layer_norm(hidden4, scope='layer_norm5') enc2 = slim.layers.conv2d( hidden4,", "transformed = [dna_transformation(prev_image, enc7)] masks = slim.layers.conv2d_transpose( enc6, num_masks +", "will be fed to the main tower as an extra", "transformed = tf.unstack(transformed, axis=-1) return transformed def dna_transformation(prev_image, dna_input): \"\"\"Apply", "norm_factor = tf.reduce_sum(cdna_kerns, [1, 2, 3], keep_dims=True) cdna_kerns /= norm_factor", "stride=2, scope='latent_conv2', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm2'}) latent_enc3 = slim.conv2d( latent_enc2, 64,", "smear, [1, int(enc2.get_shape()[1]), int(enc2.get_shape()[2]), 1]) if use_state: enc2 = tf.concat(axis=3,", "cdna: True to use Convoluational Dynamic Neural Advection (CDNA) dna:", "tf.nn.relu(dna_input - RELU_SHIFT) + RELU_SHIFT kernel = tf.expand_dims( kernel /", "network option specified or more than 1 mask specified for", "[3, 1, 2, 0]) # Transform image. transformed = tf.nn.depthwise_conv2d(prev_image,", "to previous image. Args: prev_image: previous image to be transformed.", "[2, 2], [2, 2], [0, 0]]) image_height = int(prev_image.get_shape()[1]) image_width", "import flags from tensorflow.contrib.layers.python import layers as tf_layers from lstm_ops", "# This is to make sure we are using the", "num_ground_truth) else: # Always feed in ground_truth prev_image = image", "lstm_size = np.int32(np.array([32, 32, 64, 64, 128, 64, 32])) lstm_state1,", "hidden4.get_shape()[3], [1, 1], stride=1, scope='conv4') hidden5, lstm_state5 = lstm_func( enc3,", "slim from tensorflow.python.platform import flags from tensorflow.contrib.layers.python import layers as", "for image in images] if stp + cdna + dna", "if not FLAGS.inference_time: latent = tf.cond(iter_num < FLAGS.num_iterations_1st_stage, lambda: tf.identity(latent),", "= lstm_func( enc1, lstm_state3, lstm_size[2], scope='state3') hidden3 = tf_layers.layer_norm(hidden3, scope='layer_norm4')", "tf.pad(prev_image, [[0, 0], [2, 2], [2, 2], [0, 0]]) image_height", "be generated. Args: images: tensor of ground truth image sequences", "Each image is being used twice, in latent tower and", "dna=False, context_frames=2): \"\"\"Build convolutional lstm video predictor using STP, CDNA,", "gen_states, gen_images = [], [] current_state = states[0] if k", "and hence the number of CDNA transformations. color_channels: the number", "stp_transformation(prev_image, stp_input1, num_masks) elif cdna: cdna_input = tf.reshape(hidden5, [int(batch_size), -1])", "lstm_state6 = lstm_func( enc4, lstm_state6, lstm_size[5], scope='state6') # 16x16 hidden6", "# Pass in state and action. smear = tf.reshape( state_action,", "= tf.split(axis=3, num_or_size_splits=num_masks + 1, value=masks) output = mask_list[0] *", "tf_layers.layer_norm(hidden6, scope='layer_norm7') # Skip connection. hidden6 = tf.concat(axis=3, values=[hidden6, enc1])", "- tf.square(mu) - tf.exp(log_sigma), axis=1) def construct_latent_tower(images): \"\"\"Builds convolutional latent", "normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm9'}) if dna: # Using largest hidden state", "hidden3 = tf_layers.layer_norm(hidden3, scope='layer_norm4') hidden4, lstm_state4 = lstm_func( hidden3, lstm_state4,", "lstm_state7, lstm_size[6], scope='state7') # 32x32 hidden7 = tf_layers.layer_norm(hidden7, scope='layer_norm8') #", "normalizer_params={'scope': 'layer_norm1'}) hidden1, lstm_state1 = lstm_func( enc0, lstm_state1, lstm_size[0], scope='state1')", "slim.layers.fully_connected( stp_input0, 100, scope='fc_stp') transformed += stp_transformation(prev_image, stp_input1, num_masks) elif", "latent_enc3, FLAGS.latent_channels, [3, 3], stride=2, activation_fn=None, scope='latent_mean', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm_mean'})", "tensor of the current training iteration (for sched. sampling) k:", "Args: prev_image: previous image to be transformed. stp_input: hidden layer", "Neural Advection (CDNA) dna: True to use Dynamic Neural Advection", "None lstm_state5, lstm_state6, lstm_state7 = None, None, None # Latent", "OF ANY KIND, either express or implied. # See the", "See the License for the specific language governing permissions and", "(DNA) context_frames: number of ground truth frames to pass in", "return gen_images, gen_states, latent_loss ## Utility functions def stp_transformation(prev_image, stp_input,", "CDNA kernels. \"\"\" batch_size = int(cdna_input.get_shape()[0]) height = int(prev_image.get_shape()[1]) width", "to in writing, software # distributed under the License is", "= int(prev_image.get_shape()[1]) image_width = int(prev_image.get_shape()[2]) inputs = [] for xkern", "flags from tensorflow.contrib.layers.python import layers as tf_layers from lstm_ops import", "scope='latent_conv3', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm3'}) latent_mean = slim.conv2d( latent_enc3, FLAGS.latent_channels, [3,", "Predicted state is always fed back in state_action = tf.concat(axis=1,", "image sequences actions: tensor of action sequences states: tensor of", "deviation latent_loss: loss of the latent twoer samples: random samples", "or agreed to in writing, software # distributed under the", "with specified mix of ground truth and generated data points.", "kernel = tf.nn.relu(dna_input - RELU_SHIFT) + RELU_SHIFT kernel = tf.expand_dims(", "lstm_func( hidden3, lstm_state4, lstm_size[3], scope='state4') hidden4 = tf_layers.layer_norm(hidden4, scope='layer_norm5') enc2", "used for future frames prediction. At inference time, the tower", "to pass in before feeding in own predictions Returns: gen_images:", "scope='stp_params' + str(i), activation_fn=None) + identity_params transformed.append(transformer(prev_image, params)) return transformed", "to be transformed. dna_input: hidden lyaer to be used for", "hidden5, hidden5.get_shape()[3], 3, stride=2, scope='convt1') hidden6, lstm_state6 = lstm_func( enc4,", "to be used for computing STN parameters. num_masks: number of", "# timestep x batch_size x latent_size samples = tf.random_normal( [FLAGS.sequence_length-1]", "gen_states: predicted future states Raises: ValueError: if more than one", "number of CDNA transformations. color_channels: the number of color channels", "compliance with the License. # You may obtain a copy", "All Rights Reserved. # # Licensed under the Apache License,", "ValueError('More than one, or no network option specified.') batch_size, img_height,", "of ground truth image sequences actions: tensor of action sequences", "construct_model(images, actions=None, states=None, iter_num=-1.0, k=-1, use_state=True, num_masks=10, stp=False, cdna=True, dna=False,", "[] current_state = states[0] if k == -1: feedself =", "= tf_layers.layer_norm(hidden2, scope='layer_norm3') enc1 = slim.layers.conv2d( hidden2, hidden2.get_shape()[3], [3, 3],", "and STP.\"\"\" import numpy as np import tensorflow as tf", "[dna_transformation(prev_image, enc7)] masks = slim.layers.conv2d_transpose( enc6, num_masks + 1, 1,", "latent_enc3, FLAGS.latent_channels, [3, 3], stride=2, scope='latent_std', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_std_norm'}) latent_std", "= tf.concat(axis=1, values=[action, current_state]) enc0 = slim.layers.conv2d( prev_image, 32, [5,", "color_channels: the number of color channels in the images. Returns:", "mask in zip(transformed, mask_list[1:]): output += layer * mask gen_images.append(output)", "normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm1'}) latent_enc2 = slim.conv2d( latent_enc1, 64, [3, 3],", "not use this file except in compliance with the License.", "latent_std += FLAGS.latent_std_min divergence = kl_divergence(latent_mean, latent_std) latent_loss = tf.reduce_mean(divergence)", "if needed. from spatial_transformer import transformer identity_params = tf.convert_to_tensor( np.array([1.0,", "to feed in own prediction. use_state: True to include state", "channel dimensions. prev_image = tf.transpose(prev_image, [3, 1, 2, 0]) #", "guassian \"\"\" with slim.arg_scope([slim.conv2d], reuse=False): stacked_images = tf.concat(images, 3) latent_enc1", "of ground truth and generated data points. Args: ground_truth_x: tensor", "you may not use this file except in compliance with", "for image, action in zip(images[:-1], actions[:-1]): # Reuse variables after", "lstm_func( hidden1, lstm_state2, lstm_size[1], scope='state2') hidden2 = tf_layers.layer_norm(hidden2, scope='layer_norm3') enc1", "kl_divergence(latent_mean, latent_std) latent_loss = tf.reduce_mean(divergence) if FLAGS.multi_latent: # timestep x", "scope='convt3', activation_fn=None, normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm9'}) if dna: # Using largest", "params = slim.layers.fully_connected( stp_input, 6, scope='stp_params' + str(i), activation_fn=None) +", "# Only one mask is supported (more should be unnecessary).", "cdna_kerns = tf.reshape( cdna_kerns, [batch_size, DNA_KERN_SIZE, DNA_KERN_SIZE, 1, num_masks]) cdna_kerns", "tensorflow.python.platform import flags from tensorflow.contrib.layers.python import layers as tf_layers from", "state_action, int(current_state.get_shape()[1]), scope='state_pred', activation_fn=None) gen_states.append(current_state) return gen_images, gen_states, latent_loss ##", "prev_image_pad = tf.pad(prev_image, [[0, 0], [2, 2], [2, 2], [0,", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "tensor of ground-truth data points. generated_x: tensor of generated data", "scope='state6') # 16x16 hidden6 = tf_layers.layer_norm(hidden6, scope='layer_norm7') # Skip connection.", "own predictions Returns: gen_images: predicted future image frames gen_states: predicted", "# both 32x32 enc6 = slim.layers.conv2d_transpose( hidden7, hidden7.get_shape()[3], 3, stride=2,", "masks and hence the number of STP transformations. Returns: List", "hidden2, hidden2.get_shape()[3], [3, 3], stride=2, scope='conv2') hidden3, lstm_state3 = lstm_func(", "dna: # Using largest hidden state for predicting untied conv", "tf.to_int32( tf.round(tf.to_float(batch_size) * (k / (k + tf.exp(iter_num / k)))))", "return None, None, None, samples else: return latent_mean, latent_std, latent_loss,", "[[0, 0], [2, 2], [2, 2], [0, 0]]) image_height =", "FLAGS = flags.FLAGS # Amount to use when lower bounding", "applied to each color channel. # Treat the batch dimension", "generated_idx = tf.gather(idx, tf.range(num_ground_truth, int(batch_size))) ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx) generated_examps", "scope='state_pred', activation_fn=None) gen_states.append(current_state) return gen_images, gen_states, latent_loss ## Utility functions", "batch dimension as the channel dimension so that # depthwise_conv2d", "transformed. dna_input: hidden lyaer to be used for computing DNA", "Neural Advection (DNA) context_frames: number of ground truth frames to", "+= cdna_transformation(prev_image, cdna_input, num_masks, int(color_channels)) elif dna: # Only one", "[3, 3], stride=2, scope='latent_std', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_std_norm'}) latent_std += FLAGS.latent_std_min", "iter_num: tensor of the current training iteration (for sched. sampling)", "\"\"\" # Construct translated images. prev_image_pad = tf.pad(prev_image, [[0, 0],", "import basic_conv_lstm_cell FLAGS = flags.FLAGS # Amount to use when", "Latent tower latent_loss = 0.0 if FLAGS.stochastic_model: latent_tower_outputs = construct_latent_tower(images)", "truth frames to pass in before feeding in own predictions", "using linear function of last hidden layer. cdna_kerns = slim.layers.fully_connected(", "= samples if FLAGS.multi_latent: latent = samples[timestep] if not FLAGS.inference_time:", "enc2 = tf.concat(axis=3, values=[enc2, smear]) # Setup latent if FLAGS.stochastic_model:", "lstm_size[1], scope='state2') hidden2 = tf_layers.layer_norm(hidden2, scope='layer_norm3') enc1 = slim.layers.conv2d( hidden2,", "twice, in latent tower and main tower. # This is", "= tf.reshape(hidden5, [int(batch_size), -1]) transformed += cdna_transformation(prev_image, cdna_input, num_masks, int(color_channels))", "lstm_size[6], scope='state7') # 32x32 hidden7 = tf_layers.layer_norm(hidden7, scope='layer_norm8') # Skip", "future states Raises: ValueError: if more than one network option", "TF queues work. images = [tf.identity(image) for image in images]", "tensors RELU_SHIFT = 1e-12 # kernel size for DNA and", "= slim.layers.fully_connected( cdna_input, DNA_KERN_SIZE * DNA_KERN_SIZE * num_masks, scope='cdna_params', activation_fn=None)", "Scheduled sampling: # Calculate number of ground-truth frames to pass", "tf.tile( smear, [1, int(enc2.get_shape()[1]), int(enc2.get_shape()[2]), 1]) if use_state: enc2 =", "= slim.layers.conv2d( enc2, hidden4.get_shape()[3], [1, 1], stride=1, scope='conv4') hidden5, lstm_state5", "[1, 1], stride=1, scope='conv4') hidden5, lstm_state5 = lstm_func( enc3, lstm_state5,", "prev_image for layer, mask in zip(transformed, mask_list[1:]): output += layer", "for computing STN parameters. num_masks: number of masks and hence", "lstm_state4 = None, None, None, None lstm_state5, lstm_state6, lstm_state7 =", "be used for computing DNA transformation. Returns: List of images", "FLAGS.num_iterations_1st_stage, lambda: tf.identity(latent), lambda: latent_mean + tf.exp(latent_std / 2.0) *", "Calculate number of ground-truth frames to pass in. num_ground_truth =", "for predictive model, including CDNA, DNA, and STP.\"\"\" import numpy", "ground truth frames to pass in before feeding in own", "layer * mask gen_images.append(output) current_state = slim.layers.fully_connected( state_action, int(current_state.get_shape()[1]), scope='state_pred',", "prev_image, 32, [5, 5], stride=2, scope='scale1_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm1'}) hidden1,", "color channel. # Treat the batch dimension as the channel", "to 1. kernel = tf.nn.relu(dna_input - RELU_SHIFT) + RELU_SHIFT kernel", "of the current training iteration (for sched. sampling) k: constant", "= int(prev_image.get_shape()[2]) # Predict kernels using linear function of last", "kernel / tf.reduce_sum( kernel, [3], keep_dims=True), [4]) return tf.reduce_sum(kernel *", "np import tensorflow as tf import tensorflow.contrib.slim as slim from", "lstm_size[4], scope='state5') # last 8x8 hidden5 = tf_layers.layer_norm(hidden5, scope='layer_norm6') enc4", "# Copyright 2016 The TensorFlow Authors All Rights Reserved. #", "tf.control_dependencies([latent]): enc2 = tf.concat([enc2, latent], 3) enc3 = slim.layers.conv2d( enc2,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "'layer_norm9'}) if dna: # Using largest hidden state for predicting", "extra variable to be used for future frames prediction. At", "\"\"\"Apply spatial transformer predictor (STP) to previous image. Args: prev_image:", "cdna_input, DNA_KERN_SIZE * DNA_KERN_SIZE * num_masks, scope='cdna_params', activation_fn=None) # Reshape", "-1 to feed in own prediction. use_state: True to include", "= tf.convert_to_tensor( np.array([1.0, 0.0, 0.0, 0.0, 1.0, 0.0], np.float32)) transformed", "number of STP transformations. Returns: List of images transformed by", "* prev_image for layer, mask in zip(transformed, mask_list[1:]): output +=", "2, 0, 4, 3]) cdna_kerns = tf.reshape(cdna_kerns, [DNA_KERN_SIZE, DNA_KERN_SIZE, batch_size,", "# Normalize channels to 1. kernel = tf.nn.relu(dna_input - RELU_SHIFT)", "if dna: # Using largest hidden state for predicting untied", "ValueError: if more than one network option specified or more", "scope='convt2') hidden7, lstm_state7 = lstm_func( enc5, lstm_state7, lstm_size[6], scope='state7') #", "[3, 3], stride=2, scope='conv3') # Pass in state and action.", "batch with specified mix of ground truth and generated data", "Treat the batch dimension as the channel dimension so that", "image from scratch, # which is useful when regions of", "64, 64, 128, 64, 32])) lstm_state1, lstm_state2, lstm_state3, lstm_state4 =", "latent_loss: loss of the latent twoer samples: random samples sampled", "file except in compliance with the License. # You may", "work. images = [tf.identity(image) for image in images] if stp", "= tf.expand_dims( kernel / tf.reduce_sum( kernel, [3], keep_dims=True), [4]) return", "0.0, 0.0, 0.0, 1.0, 0.0], np.float32)) transformed = [] for", "distribution. Returns: the KL loss. \"\"\" return -.5 * tf.reduce_sum(1.", "motion predictions (and the number of masks for each of", "samples = latent_tower_outputs # Main tower for image, action in", "+= layer * mask gen_images.append(output) current_state = slim.layers.fully_connected( state_action, int(current_state.get_shape()[1]),", "which is useful when regions of the image become unoccluded.", "int(cdna_input.get_shape()[0]) height = int(prev_image.get_shape()[1]) width = int(prev_image.get_shape()[2]) # Predict kernels", "lstm_state7 = lstm_func( enc5, lstm_state7, lstm_size[6], scope='state7') # 32x32 hidden7", "normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm2'}) latent_enc3 = slim.conv2d( latent_enc2, 64, [3, 3],", "kernel, [3], keep_dims=True), [4]) return tf.reduce_sum(kernel * inputs, [3], keep_dims=False)", "'layer_norm1'}) hidden1, lstm_state1 = lstm_func( enc0, lstm_state1, lstm_size[0], scope='state1') hidden1", "= mask_list[0] * prev_image for layer, mask in zip(transformed, mask_list[1:]):", "... # ... given how TF queues work. images =", "num_masks, scope='cdna_params', activation_fn=None) # Reshape and normalize. cdna_kerns = tf.reshape(", "be transformed. dna_input: hidden lyaer to be used for computing", "lstm_state3, lstm_state4 = None, None, None, None lstm_state5, lstm_state6, lstm_state7", "lstm_state4 = lstm_func( hidden3, lstm_state4, lstm_size[3], scope='state4') hidden4 = tf_layers.layer_norm(hidden4,", "identity_params transformed.append(transformer(prev_image, params)) return transformed def cdna_transformation(prev_image, cdna_input, num_masks, color_channels):", "reuse=reuse): if feedself and done_warm_start: # Feed in generated image.", "tf.reduce_sum( kernel, [3], keep_dims=True), [4]) return tf.reduce_sum(kernel * inputs, [3],", "is supported (more should be unnecessary). if num_masks != 1:", "STP parameters. \"\"\" # Only import spatial transformer if needed.", "def scheduled_sample(ground_truth_x, generated_x, batch_size, num_ground_truth): \"\"\"Sample batch with specified mix", "lstm video predictor using STP, CDNA, or DNA. Args: images:", "from spatial_transformer import transformer identity_params = tf.convert_to_tensor( np.array([1.0, 0.0, 0.0,", "KIND, either express or implied. # See the License for", "# Scheduled sampling: # Calculate number of ground-truth frames to", "32, [5, 5], stride=2, scope='scale1_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm1'}) hidden1, lstm_state1", "sched. sampling) k: constant used for scheduled sampling. -1 to", "FLAGS.latent_std_min divergence = kl_divergence(latent_mean, latent_std) latent_loss = tf.reduce_mean(divergence) if FLAGS.multi_latent:", "if stp + cdna + dna != 1: raise ValueError('More", "of masks for each of those predictions) stp: True to", "in state and action. smear = tf.reshape( state_action, [int(batch_size), 1,", "flag is on, a different latent for every timestep would", "tf.exp(log_sigma), axis=1) def construct_latent_tower(images): \"\"\"Builds convolutional latent tower for stochastic", "(the \"License\"); # you may not use this file except", "= slim.layers.conv2d( prev_image, 32, [5, 5], stride=2, scope='scale1_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope':", "action. smear = tf.reshape( state_action, [int(batch_size), 1, 1, int(state_action.get_shape()[1])]) smear", "= slim.layers.fully_connected( stp_input, 6, scope='stp_params' + str(i), activation_fn=None) + identity_params", "num_masks: number of masks and hence the number of STP", "\"\"\" batch_size = int(cdna_input.get_shape()[0]) height = int(prev_image.get_shape()[1]) width = int(prev_image.get_shape()[2])", "the predicted CDNA kernels. \"\"\" # Construct translated images. prev_image_pad", "latent_tower_outputs = construct_latent_tower(images) latent_mean, latent_std, latent_loss, samples = latent_tower_outputs #", "x latent_size samples = tf.random_normal( [FLAGS.sequence_length-1] + latent_mean.shape, 0, 1,", "this tower generates a latent distribution (mean and std) conditioned", "num_masks): \"\"\"Apply spatial transformer predictor (STP) to previous image. Args:", "DNA_KERN_SIZE = 5 def kl_divergence(mu, log_sigma): \"\"\"KL divergence of diagonal", "1, stride=1, scope='convt7', activation_fn=None) masks = tf.reshape( tf.nn.softmax(tf.reshape(masks, [-1, num_masks", "2], [0, 0]]) image_height = int(prev_image.get_shape()[1]) image_width = int(prev_image.get_shape()[2]) inputs", "distribution. log_sigma: log(sigma) parameter of the distribution. Returns: the KL", "images transformed by the predicted CDNA kernels. \"\"\" batch_size =", "of the distribution. Returns: the KL loss. \"\"\" return -.5", "32, [3, 3], stride=2, scope='latent_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm1'}) latent_enc2 =", "# # Unless required by applicable law or agreed to", "normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm1'}) hidden1, lstm_state1 = lstm_func( enc0, lstm_state1, lstm_size[0],", "to use Spatial Transformer Predictor (STP) cdna: True to use", "= tf.concat(axis=3, values=[enc2, smear]) # Setup latent if FLAGS.stochastic_model: latent", "permissions and # limitations under the License. # ============================================================================== \"\"\"Model", "lstm_state5, lstm_state6, lstm_state7 = None, None, None # Latent tower", "stride=2, scope='latent_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm1'}) latent_enc2 = slim.conv2d( latent_enc1, 64,", "= slim.layers.fully_connected( state_action, int(current_state.get_shape()[1]), scope='state_pred', activation_fn=None) gen_states.append(current_state) return gen_images, gen_states,", "+ 1, value=masks) output = mask_list[0] * prev_image for layer,", "frames to pass in. num_ground_truth = tf.to_int32( tf.round(tf.to_float(batch_size) * (k", "+ str(i), activation_fn=None) + identity_params transformed.append(transformer(prev_image, params)) return transformed def", "convolutional latent tower for stochastic model. At training time this", "stacked_images = tf.concat(images, 3) latent_enc1 = slim.conv2d( stacked_images, 32, [3,", "= lstm_func( enc3, lstm_state5, lstm_size[4], scope='state5') # last 8x8 hidden5", "CDNA, DNA, and STP.\"\"\" import numpy as np import tensorflow", "of masks and hence the number of CDNA transformations. color_channels:", "hence the number of CDNA transformations. color_channels: the number of", "kernels using linear function of last hidden layer. cdna_kerns =", "actions: tensor of action sequences states: tensor of ground truth", "fed back in state_action = tf.concat(axis=1, values=[action, current_state]) enc0 =", "of ground-truth data points. generated_x: tensor of generated data points.", "= [dna_transformation(prev_image, enc7)] masks = slim.layers.conv2d_transpose( enc6, num_masks + 1,", "lstm_size[2], scope='state3') hidden3 = tf_layers.layer_norm(hidden3, scope='layer_norm4') hidden4, lstm_state4 = lstm_func(", "use_state: enc2 = tf.concat(axis=3, values=[enc2, smear]) # Setup latent if", "implied. # See the License for the specific language governing", "= tf.transpose(prev_image, [3, 1, 2, 0]) # Transform image. transformed", "= tf.transpose(transformed, [3, 1, 2, 0, 4]) transformed = tf.unstack(transformed,", "for DNA and CDNA. DNA_KERN_SIZE = 5 def kl_divergence(mu, log_sigma):", "latent_mean = slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3], stride=2, activation_fn=None, scope='latent_mean',", "RELU_SHIFT = 1e-12 # kernel size for DNA and CDNA.", "dtype=tf.float32) if FLAGS.inference_time: # No latent tower at inference time,", "that # depthwise_conv2d can apply a different transformation to each", "number of ground-truth frames to pass in. num_ground_truth = tf.to_int32(", "'SAME') # Transpose the dimensions to where they belong. transformed", "= 0.0 if FLAGS.stochastic_model: latent_tower_outputs = construct_latent_tower(images) latent_mean, latent_std, latent_loss,", "gen_images.append(output) current_state = slim.layers.fully_connected( state_action, int(current_state.get_shape()[1]), scope='state_pred', activation_fn=None) gen_states.append(current_state) return", "image frames gen_states: predicted future states Raises: ValueError: if more", "range(DNA_KERN_SIZE): for ykern in range(DNA_KERN_SIZE): inputs.append( tf.expand_dims( tf.slice(prev_image_pad, [0, xkern,", "[0, xkern, ykern, 0], [-1, image_height, image_width, -1]), [3])) inputs", "= tf.transpose(cdna_kerns, [1, 2, 0, 4, 3]) cdna_kerns = tf.reshape(cdna_kerns,", "+ tf.exp(latent_std / 2.0) * latent) with tf.control_dependencies([latent]): enc2 =", "RELU_SHIFT kernel = tf.expand_dims( kernel / tf.reduce_sum( kernel, [3], keep_dims=True),", "multi_latent flag is on, a different latent for every timestep", "slim.layers.conv2d_transpose( hidden7, hidden7.get_shape()[3], 3, stride=2, scope='convt3', activation_fn=None, normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm9'})", "+ RELU_SHIFT norm_factor = tf.reduce_sum(cdna_kerns, [1, 2, 3], keep_dims=True) cdna_kerns", "Spatial Transformer Predictor (STP) cdna: True to use Convoluational Dynamic", "so that # depthwise_conv2d can apply a different transformation to", "image_width, -1]), [3])) inputs = tf.concat(axis=3, values=inputs) # Normalize channels", "enc0 = slim.layers.conv2d( prev_image, 32, [5, 5], stride=2, scope='scale1_conv1', normalizer_fn=tf_layers.layer_norm,", "sampled from ground_truth_x and the rest from generated_x. \"\"\" idx", "generated_x. \"\"\" idx = tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth)) generated_idx", "values=inputs) # Normalize channels to 1. kernel = tf.nn.relu(dna_input -", "reuse=False): stacked_images = tf.concat(images, 3) latent_enc1 = slim.conv2d( stacked_images, 32,", "current training iteration (for sched. sampling) k: constant used for", "cdna_kerns = tf.transpose(cdna_kerns, [1, 2, 0, 4, 3]) cdna_kerns =", "latent_size samples = tf.random_normal(latent_mean.shape, 0, 1, dtype=tf.float32) if FLAGS.inference_time: #", "sampling: # Calculate number of ground-truth frames to pass in.", "1 mask specified for DNA model. \"\"\" # Each image", "Skip connection. hidden6 = tf.concat(axis=3, values=[hidden6, enc1]) # both 16x16", "1], 'SAME') # Transpose the dimensions to where they belong.", "predictions (and the number of masks for each of those", "using STP, CDNA, or DNA. Args: images: tensor of ground", "Unless required by applicable law or agreed to in writing,", "[3], keep_dims=True), [4]) return tf.reduce_sum(kernel * inputs, [3], keep_dims=False) def", "construct_latent_tower(images): \"\"\"Builds convolutional latent tower for stochastic model. At training", "\"\"\"Model architecture for predictive model, including CDNA, DNA, and STP.\"\"\"", "layer. cdna_kerns = slim.layers.fully_connected( cdna_input, DNA_KERN_SIZE * DNA_KERN_SIZE * num_masks,", "dimension since the same # transformation is applied to each", "activation_fn=None) # This allows the network to also generate one", "image. transformed = tf.nn.depthwise_conv2d(prev_image, cdna_kerns, [1, 1, 1, 1], 'SAME')", "Advection (DNA) context_frames: number of ground truth frames to pass", "the specific language governing permissions and # limitations under the", "1. kernel = tf.nn.relu(dna_input - RELU_SHIFT) + RELU_SHIFT kernel =", "latent_loss = tf.reduce_mean(divergence) if FLAGS.multi_latent: # timestep x batch_size x", "Args: images: tensor of ground truth image sequences Returns: latent_mean:", "- RELU_SHIFT) + RELU_SHIFT kernel = tf.expand_dims( kernel / tf.reduce_sum(", "the images. Returns: List of images transformed by the predicted", "= slim.layers.conv2d_transpose( hidden5, hidden5.get_shape()[3], 3, stride=2, scope='convt1') hidden6, lstm_state6 =", "scope='scale1_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm1'}) hidden1, lstm_state1 = lstm_func( enc0, lstm_state1,", "= 5 def kl_divergence(mu, log_sigma): \"\"\"KL divergence of diagonal gaussian", "those predictions) stp: True to use Spatial Transformer Predictor (STP)", "entire video. This latent variable will be fed to the", "Args: images: tensor of ground truth image sequences actions: tensor", "None, None, None, samples else: return latent_mean, latent_std, latent_loss, samples", "can apply a different transformation to each sample. cdna_kerns =", "function of last hidden layer. cdna_kerns = slim.layers.fully_connected( cdna_input, DNA_KERN_SIZE", "mask gen_images.append(output) current_state = slim.layers.fully_connected( state_action, int(current_state.get_shape()[1]), scope='state_pred', activation_fn=None) gen_states.append(current_state)", "1, 1, 1], 'SAME') # Transpose the dimensions to where", "batch size num_ground_truth: number of ground-truth examples to include in", "tower is disabled and only returns latents sampled from N(0,1).", "N(0,1). If the multi_latent flag is on, a different latent", "when lower bounding tensors RELU_SHIFT = 1e-12 # kernel size", "on the entire video. This latent variable will be fed", "16x16 hidden6 = tf_layers.layer_norm(hidden6, scope='layer_norm7') # Skip connection. hidden6 =", "on, a different latent for every timestep would be generated.", "dimensions to where they belong. transformed = tf.reshape(transformed, [color_channels, height,", "the License. # ============================================================================== \"\"\"Model architecture for predictive model, including", "tower at inference time, just standard gaussian. return None, None,", "# 32x32 hidden7 = tf_layers.layer_norm(hidden7, scope='layer_norm8') # Skip connection. hidden7", "number of ground truth frames to pass in before feeding", "[int(batch_size), -1]) stp_input1 = slim.layers.fully_connected( stp_input0, 100, scope='fc_stp') transformed +=", "k == -1: feedself = True else: # Scheduled sampling:", "[FLAGS.sequence_length-1] + latent_mean.shape, 0, 1, dtype=tf.float32) else: # batch_size x", "import numpy as np import tensorflow as tf import tensorflow.contrib.slim", "# Skip connection. hidden6 = tf.concat(axis=3, values=[hidden6, enc1]) # both", "3], keep_dims=True) cdna_kerns /= norm_factor # Treat the color channel", "= tf.reshape(transformed, [color_channels, height, width, batch_size, num_masks]) transformed = tf.transpose(transformed,", "one mask is supported (more should be unnecessary). if num_masks", "[] for i in range(num_masks - 1): params = slim.layers.fully_connected(", "the distribution. log_sigma: log(sigma) parameter of the distribution. Returns: the", "the latent twoer samples: random samples sampled from standard guassian", "lstm_size[0], scope='state1') hidden1 = tf_layers.layer_norm(hidden1, scope='layer_norm2') hidden2, lstm_state2 = lstm_func(", "cdna_kerns = tf.reshape(cdna_kerns, [DNA_KERN_SIZE, DNA_KERN_SIZE, batch_size, num_masks]) # Swap the", "use_state=True, num_masks=10, stp=False, cdna=True, dna=False, context_frames=2): \"\"\"Build convolutional lstm video", "identity_params = tf.convert_to_tensor( np.array([1.0, 0.0, 0.0, 0.0, 1.0, 0.0], np.float32))", "# Swap the batch and channel dimensions. prev_image = tf.transpose(prev_image,", "= images[0].get_shape()[0:4] lstm_func = basic_conv_lstm_cell # Generated robot states and", "DNA_KERN_SIZE * DNA_KERN_SIZE * num_masks, scope='cdna_params', activation_fn=None) # Reshape and", "model, including CDNA, DNA, and STP.\"\"\" import numpy as np", "functions def stp_transformation(prev_image, stp_input, num_masks): \"\"\"Apply spatial transformer predictor (STP)", "(CDNA) dna: True to use Dynamic Neural Advection (DNA) context_frames:", "hidden6, lstm_state6 = lstm_func( enc4, lstm_state6, lstm_size[5], scope='state6') # 16x16", "lstm_ops import basic_conv_lstm_cell FLAGS = flags.FLAGS # Amount to use", "slim.layers.fully_connected( stp_input, 6, scope='stp_params' + str(i), activation_fn=None) + identity_params transformed.append(transformer(prev_image,", "tf.transpose(prev_image, [3, 1, 2, 0]) # Transform image. transformed =", "enc2 = tf.concat([enc2, latent], 3) enc3 = slim.layers.conv2d( enc2, hidden4.get_shape()[3],", "to include in batch. Returns: New batch with num_ground_truth sampled", "= lstm_func( enc5, lstm_state7, lstm_size[6], scope='state7') # 32x32 hidden7 =", "ground_truth prev_image = image # Predicted state is always fed", "hidden5.get_shape()[3], 3, stride=2, scope='convt1') hidden6, lstm_state6 = lstm_func( enc4, lstm_state6,", "enc6, DNA_KERN_SIZE**2, 1, stride=1, scope='convt4', activation_fn=None) else: # Using largest", "lyaer to be used for computing CDNA kernels. num_masks: the", "be used for future frames prediction. At inference time, the", "since the same # transformation is applied to each color", "also generate one image from scratch, # which is useful", "stride=2, scope='convt3', activation_fn=None, normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm9'}) if dna: # Using", "= tf_layers.layer_norm(hidden4, scope='layer_norm5') enc2 = slim.layers.conv2d( hidden4, hidden4.get_shape()[3], [3, 3],", "= lstm_func( enc0, lstm_state1, lstm_size[0], scope='state1') hidden1 = tf_layers.layer_norm(hidden1, scope='layer_norm2')", "smear = tf.reshape( state_action, [int(batch_size), 1, 1, int(state_action.get_shape()[1])]) smear =", "at inference time, just standard gaussian. return None, None, None,", "supported (more should be unnecessary). if num_masks != 1: raise", "latent_std, latent_loss, samples = latent_tower_outputs # Main tower for image,", "is being used twice, in latent tower and main tower.", "+ dna != 1: raise ValueError('More than one, or no", "feedself and done_warm_start: # Feed in generated image. prev_image =", "1, num_masks]) cdna_kerns = tf.nn.relu(cdna_kerns - RELU_SHIFT) + RELU_SHIFT norm_factor", "* latent) with tf.control_dependencies([latent]): enc2 = tf.concat([enc2, latent], 3) enc3", "cdna_kerns /= norm_factor # Treat the color channel dimension as", "tf.random_normal(latent_mean.shape, 0, 1, dtype=tf.float32) if FLAGS.inference_time: # No latent tower", "scope='layer_norm2') hidden2, lstm_state2 = lstm_func( hidden1, lstm_state2, lstm_size[1], scope='state2') hidden2", "sampling) k: constant used for scheduled sampling. -1 to feed", "= True else: # Scheduled sampling: # Calculate number of", "stp + cdna + dna != 1: raise ValueError('More than", "with num_ground_truth sampled from ground_truth_x and the rest from generated_x.", "scope='state3') hidden3 = tf_layers.layer_norm(hidden3, scope='layer_norm4') hidden4, lstm_state4 = lstm_func( hidden3,", "True else: # Scheduled sampling: # Calculate number of ground-truth", "hidden7 = tf.concat(axis=3, values=[hidden7, enc0]) # both 32x32 enc6 =", "else: # Scheduled sampling: # Calculate number of ground-truth frames", "latent_loss, samples = latent_tower_outputs # Main tower for image, action", "only returns latents sampled from N(0,1). If the multi_latent flag", "slim.layers.conv2d( prev_image, 32, [5, 5], stride=2, scope='scale1_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm1'})", "of images transformed by the predicted STP parameters. \"\"\" #", "You may obtain a copy of the License at #", "1, 1, int(state_action.get_shape()[1])]) smear = tf.tile( smear, [1, int(enc2.get_shape()[1]), int(enc2.get_shape()[2]),", "import spatial transformer if needed. from spatial_transformer import transformer identity_params", "gen_states, latent_loss ## Utility functions def stp_transformation(prev_image, stp_input, num_masks): \"\"\"Apply", "# Using largest hidden state for predicting a new image", "\"\"\"Apply dynamic neural advection to previous image. Args: prev_image: previous", "twoer samples: random samples sampled from standard guassian \"\"\" with", "= bool(gen_images) done_warm_start = len(gen_images) > context_frames - 1 with", "1]) if use_state: enc2 = tf.concat(axis=3, values=[enc2, smear]) # Setup", "# 16x16 hidden6 = tf_layers.layer_norm(hidden6, scope='layer_norm7') # Skip connection. hidden6", "= tf.reduce_sum(cdna_kerns, [1, 2, 3], keep_dims=True) cdna_kerns /= norm_factor #", "of last hidden layer. cdna_kerns = slim.layers.fully_connected( cdna_input, DNA_KERN_SIZE *", "None, None, samples else: return latent_mean, latent_std, latent_loss, samples def", "scope='latent_std', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_std_norm'}) latent_std += FLAGS.latent_std_min divergence = kl_divergence(latent_mean,", "scope='layer_norm6') enc4 = slim.layers.conv2d_transpose( hidden5, hidden5.get_shape()[3], 3, stride=2, scope='convt1') hidden6,", "latent_mean: predicted latent mean latent_std: predicted latent standard deviation latent_loss:", "from tensorflow.contrib.layers.python import layers as tf_layers from lstm_ops import basic_conv_lstm_cell", "context_frames=2): \"\"\"Build convolutional lstm video predictor using STP, CDNA, or", "-.5 * tf.reduce_sum(1. + log_sigma - tf.square(mu) - tf.exp(log_sigma), axis=1)", "where they belong. transformed = tf.reshape(transformed, [color_channels, height, width, batch_size,", "1, value=masks) output = mask_list[0] * prev_image for layer, mask", "transformer identity_params = tf.convert_to_tensor( np.array([1.0, 0.0, 0.0, 0.0, 1.0, 0.0],", "ground_truth_x: tensor of ground-truth data points. generated_x: tensor of generated", "value=masks) output = mask_list[0] * prev_image for layer, mask in", "state is always fed back in state_action = tf.concat(axis=1, values=[action,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "kernels. \"\"\" batch_size = int(cdna_input.get_shape()[0]) height = int(prev_image.get_shape()[1]) width =", "in zip(images[:-1], actions[:-1]): # Reuse variables after the first timestep.", "every timestep would be generated. Args: images: tensor of ground", "images transformed by the predicted STP parameters. \"\"\" # Only", "to make sure we are using the *same* image for", "become unoccluded. transformed = [tf.nn.sigmoid(enc7)] if stp: stp_input0 = tf.reshape(hidden5,", "latent_loss ## Utility functions def stp_transformation(prev_image, stp_input, num_masks): \"\"\"Apply spatial", "# LSTM state sizes and states. lstm_size = np.int32(np.array([32, 32,", "= False # LSTM state sizes and states. lstm_size =", "STN parameters. num_masks: number of masks and hence the number", "enc1]) # both 16x16 enc5 = slim.layers.conv2d_transpose( hidden6, hidden6.get_shape()[3], 3,", "to use Dynamic Neural Advection (DNA) context_frames: number of ground", "to be used for future frames prediction. At inference time,", "size for DNA and CDNA. DNA_KERN_SIZE = 5 def kl_divergence(mu,", "they belong. transformed = tf.reshape(transformed, [color_channels, height, width, batch_size, num_masks])", "regions of the image become unoccluded. transformed = [tf.nn.sigmoid(enc7)] if", "normalizer_params={'scope': 'latent_norm1'}) latent_enc2 = slim.conv2d( latent_enc1, 64, [3, 3], stride=2,", "sequences states: tensor of ground truth state sequences iter_num: tensor", "both 32x32 enc6 = slim.layers.conv2d_transpose( hidden7, hidden7.get_shape()[3], 3, stride=2, scope='convt3',", "when regions of the image become unoccluded. transformed = [tf.nn.sigmoid(enc7)]", "Raises: ValueError: if more than one network option specified or", "enc7 = slim.layers.conv2d_transpose( enc6, color_channels, 1, stride=1, scope='convt4', activation_fn=None) #", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "enc6, num_masks + 1, 1, stride=1, scope='convt7', activation_fn=None) masks =", "< FLAGS.num_iterations_1st_stage, lambda: tf.identity(latent), lambda: latent_mean + tf.exp(latent_std / 2.0)", "License. # You may obtain a copy of the License", "the batch dimension as the channel dimension so that #", "the number of color channels in the images. Returns: List", "and N(0,1). Args: mu: mu parameter of the distribution. log_sigma:", "enc5, lstm_state7, lstm_size[6], scope='state7') # 32x32 hidden7 = tf_layers.layer_norm(hidden7, scope='layer_norm8')", "mask_list[0] * prev_image for layer, mask in zip(transformed, mask_list[1:]): output", "kl_divergence(mu, log_sigma): \"\"\"KL divergence of diagonal gaussian N(mu,exp(log_sigma)) and N(0,1).", "ground-truth data points. generated_x: tensor of generated data points. batch_size:", "image_height, image_width, -1]), [3])) inputs = tf.concat(axis=3, values=inputs) # Normalize", "and done_warm_start: # Feed in generated image. prev_image = gen_images[-1]", "spatial transformer predictor (STP) to previous image. Args: prev_image: previous", "# Treat the batch dimension as the channel dimension so", "governing permissions and # limitations under the License. # ==============================================================================", "[batch_size, DNA_KERN_SIZE, DNA_KERN_SIZE, 1, num_masks]) cdna_kerns = tf.nn.relu(cdna_kerns - RELU_SHIFT)", "a new image layer. enc7 = slim.layers.conv2d_transpose( enc6, color_channels, 1,", "Advection (CDNA) dna: True to use Dynamic Neural Advection (DNA)", "* tf.reduce_sum(1. + log_sigma - tf.square(mu) - tf.exp(log_sigma), axis=1) def", "inputs.append( tf.expand_dims( tf.slice(prev_image_pad, [0, xkern, ykern, 0], [-1, image_height, image_width,", "if FLAGS.inference_time: # No latent tower at inference time, just", "unoccluded. transformed = [tf.nn.sigmoid(enc7)] if stp: stp_input0 = tf.reshape(hidden5, [int(batch_size),", "2, 0, 4]) transformed = tf.unstack(transformed, axis=-1) return transformed def", "No latent tower at inference time, just standard gaussian. return", "done_warm_start = len(gen_images) > context_frames - 1 with slim.arg_scope( [lstm_func,", "scope='convt4', activation_fn=None) # This allows the network to also generate", "lstm_state1, lstm_size[0], scope='state1') hidden1 = tf_layers.layer_norm(hidden1, scope='layer_norm2') hidden2, lstm_state2 =", "the batch dimension since the same # transformation is applied", "1, 2, 0]) # Transform image. transformed = tf.nn.depthwise_conv2d(prev_image, cdna_kerns,", "RELU_SHIFT) + RELU_SHIFT kernel = tf.expand_dims( kernel / tf.reduce_sum( kernel,", "lstm_state7 = None, None, None # Latent tower latent_loss =", "num_masks + 1, 1, stride=1, scope='convt7', activation_fn=None) masks = tf.reshape(", "stp_input1 = slim.layers.fully_connected( stp_input0, 100, scope='fc_stp') transformed += stp_transformation(prev_image, stp_input1,", "used for computing STN parameters. num_masks: number of masks and", "3, stride=2, scope='convt3', activation_fn=None, normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm9'}) if dna: #", "= slim.layers.conv2d_transpose( enc6, DNA_KERN_SIZE**2, 1, stride=1, scope='convt4', activation_fn=None) else: #", "latent_mean.shape, 0, 1, dtype=tf.float32) else: # batch_size x latent_size samples", "fed to the main tower as an extra variable to", "FLAGS.multi_latent: # timestep x batch_size x latent_size samples = tf.random_normal(", "transformed = tf.nn.depthwise_conv2d(prev_image, cdna_kerns, [1, 1, 1, 1], 'SAME') #", "height = int(prev_image.get_shape()[1]) width = int(prev_image.get_shape()[2]) # Predict kernels using", "in batch. Returns: New batch with num_ground_truth sampled from ground_truth_x", "# Setup latent if FLAGS.stochastic_model: latent = samples if FLAGS.multi_latent:", "state sizes and states. lstm_size = np.int32(np.array([32, 32, 64, 64,", "scheduled_sample(image, gen_images[-1], batch_size, num_ground_truth) else: # Always feed in ground_truth", "None, None lstm_state5, lstm_state6, lstm_state7 = None, None, None #", "lambda: tf.identity(latent), lambda: latent_mean + tf.exp(latent_std / 2.0) * latent)", "tf.reshape(hidden5, [int(batch_size), -1]) stp_input1 = slim.layers.fully_connected( stp_input0, 100, scope='fc_stp') transformed", "batch_size x latent_size samples = tf.random_normal(latent_mean.shape, 0, 1, dtype=tf.float32) if", "1, stride=1, scope='convt4', activation_fn=None) # This allows the network to", "context_frames: number of ground truth frames to pass in before", "output = mask_list[0] * prev_image for layer, mask in zip(transformed,", "= slim.layers.conv2d_transpose( hidden7, hidden7.get_shape()[3], 3, stride=2, scope='convt3', activation_fn=None, normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope':", "than 1 mask specified for DNA model. \"\"\" # Each", "k: constant used for scheduled sampling. -1 to feed in", "generated_x: tensor of generated data points. batch_size: batch size num_ground_truth:", "8x8 hidden5 = tf_layers.layer_norm(hidden5, scope='layer_norm6') enc4 = slim.layers.conv2d_transpose( hidden5, hidden5.get_shape()[3],", "num_ground_truth): \"\"\"Sample batch with specified mix of ground truth and", "images. gen_states, gen_images = [], [] current_state = states[0] if", "FLAGS.stochastic_model: latent = samples if FLAGS.multi_latent: latent = samples[timestep] if", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "with slim.arg_scope([slim.conv2d], reuse=False): stacked_images = tf.concat(images, 3) latent_enc1 = slim.conv2d(", "used twice, in latent tower and main tower. # This", "Treat the color channel dimension as the batch dimension since", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "activation_fn=None, scope='latent_mean', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm_mean'}) latent_std = slim.conv2d( latent_enc3, FLAGS.latent_channels,", "= tf.nn.depthwise_conv2d(prev_image, cdna_kerns, [1, 1, 1, 1], 'SAME') # Transpose", "image layer. enc7 = slim.layers.conv2d_transpose( enc6, color_channels, 1, stride=1, scope='convt4',", "of ground truth frames to pass in before feeding in", "the same # transformation is applied to each color channel.", "the KL loss. \"\"\" return -.5 * tf.reduce_sum(1. + log_sigma", "language governing permissions and # limitations under the License. #", "required by applicable law or agreed to in writing, software", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "elif cdna: cdna_input = tf.reshape(hidden5, [int(batch_size), -1]) transformed += cdna_transformation(prev_image,", "conv kernels. enc7 = slim.layers.conv2d_transpose( enc6, DNA_KERN_SIZE**2, 1, stride=1, scope='convt4',", "lyaer to be used for computing DNA transformation. Returns: List", "and main tower. # This is to make sure we", "lstm_state2, lstm_state3, lstm_state4 = None, None, None, None lstm_state5, lstm_state6,", "- 1): params = slim.layers.fully_connected( stp_input, 6, scope='stp_params' + str(i),", "* (k / (k + tf.exp(iter_num / k))))) feedself =", "color_channels): \"\"\"Apply convolutional dynamic neural advection to previous image. Args:", "be used for computing STN parameters. num_masks: number of masks", "agreed to in writing, software # distributed under the License", "the batch and channel dimensions. prev_image = tf.transpose(prev_image, [3, 1,", "'latent_std_norm'}) latent_std += FLAGS.latent_std_min divergence = kl_divergence(latent_mean, latent_std) latent_loss =", "distributed under the License is distributed on an \"AS IS\"", "cdna_input = tf.reshape(hidden5, [int(batch_size), -1]) transformed += cdna_transformation(prev_image, cdna_input, num_masks,", "tower latent_loss = 0.0 if FLAGS.stochastic_model: latent_tower_outputs = construct_latent_tower(images) latent_mean,", "ykern in range(DNA_KERN_SIZE): inputs.append( tf.expand_dims( tf.slice(prev_image_pad, [0, xkern, ykern, 0],", "stp: True to use Spatial Transformer Predictor (STP) cdna: True", "1.0, 0.0], np.float32)) transformed = [] for i in range(num_masks", "hidden6 = tf_layers.layer_norm(hidden6, scope='layer_norm7') # Skip connection. hidden6 = tf.concat(axis=3,", "tower for stochastic model. At training time this tower generates", "tower generates a latent distribution (mean and std) conditioned on", "channels in the images. Returns: List of images transformed by", "num_masks) elif cdna: cdna_input = tf.reshape(hidden5, [int(batch_size), -1]) transformed +=", "image. prev_image = gen_images[-1] elif done_warm_start: # Scheduled sampling prev_image", "tf.gather(ground_truth_x, ground_truth_idx) generated_examps = tf.gather(generated_x, generated_idx) return tf.dynamic_stitch([ground_truth_idx, generated_idx], [ground_truth_examps,", "= np.int32(np.array([32, 32, 64, 64, 128, 64, 32])) lstm_state1, lstm_state2,", "import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.python.platform", "ground truth state sequences iter_num: tensor of the current training", "diagonal gaussian N(mu,exp(log_sigma)) and N(0,1). Args: mu: mu parameter of", "Args: ground_truth_x: tensor of ground-truth data points. generated_x: tensor of", "transformed = tf.reshape(transformed, [color_channels, height, width, batch_size, num_masks]) transformed =", "state for predicting a new image layer. enc7 = slim.layers.conv2d_transpose(", "= tf.reduce_mean(divergence) if FLAGS.multi_latent: # timestep x batch_size x latent_size", "and the rest from generated_x. \"\"\" idx = tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx", "if FLAGS.multi_latent: latent = samples[timestep] if not FLAGS.inference_time: latent =", "normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm_mean'}) latent_std = slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3],", "= slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3], stride=2, scope='latent_std', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope':", "depthwise_conv2d can apply a different transformation to each sample. cdna_kerns", "latent_std, latent_loss, samples def construct_model(images, actions=None, states=None, iter_num=-1.0, k=-1, use_state=True,", "dimension as the channel dimension so that # depthwise_conv2d can", "back in state_action = tf.concat(axis=1, values=[action, current_state]) enc0 = slim.layers.conv2d(", "frames to pass in before feeding in own predictions Returns:", "architecture for predictive model, including CDNA, DNA, and STP.\"\"\" import", "enc6, color_channels, 1, stride=1, scope='convt4', activation_fn=None) # This allows the", "previous image to be transformed. stp_input: hidden layer to be", "128, 64, 32])) lstm_state1, lstm_state2, lstm_state3, lstm_state4 = None, None,", "action in prediction num_masks: the number of different pixel motion", "== -1: feedself = True else: # Scheduled sampling: #", "= [tf.identity(image) for image in images] if stp + cdna", "latent_enc2, 64, [3, 3], stride=1, scope='latent_conv3', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm3'}) latent_mean", "Reuse variables after the first timestep. reuse = bool(gen_images) done_warm_start", "int(img_width), num_masks + 1]) mask_list = tf.split(axis=3, num_or_size_splits=num_masks + 1,", "variable will be fed to the main tower as an", "32])) lstm_state1, lstm_state2, lstm_state3, lstm_state4 = None, None, None, None", "loss. \"\"\" return -.5 * tf.reduce_sum(1. + log_sigma - tf.square(mu)", "int(prev_image.get_shape()[2]) # Predict kernels using linear function of last hidden", "prev_image: previous image to be transformed. cdna_input: hidden lyaer to", "connection. hidden7 = tf.concat(axis=3, values=[hidden7, enc0]) # both 32x32 enc6", "= tf.concat(axis=3, values=[hidden6, enc1]) # both 16x16 enc5 = slim.layers.conv2d_transpose(", "OR CONDITIONS OF ANY KIND, either express or implied. #", "disabled and only returns latents sampled from N(0,1). If the", "if FLAGS.stochastic_model: latent = samples if FLAGS.multi_latent: latent = samples[timestep]", "the License is distributed on an \"AS IS\" BASIS, #", "for every timestep would be generated. Args: images: tensor of", "tf.range(num_ground_truth, int(batch_size))) ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx) generated_examps = tf.gather(generated_x, generated_idx)", "num_masks + 1])), [int(batch_size), int(img_height), int(img_width), num_masks + 1]) mask_list", "transformer if needed. from spatial_transformer import transformer identity_params = tf.convert_to_tensor(", "of diagonal gaussian N(mu,exp(log_sigma)) and N(0,1). Args: mu: mu parameter", "number of color channels in the images. Returns: List of", "activation_fn=None) masks = tf.reshape( tf.nn.softmax(tf.reshape(masks, [-1, num_masks + 1])), [int(batch_size),", "slim.conv2d( stacked_images, 32, [3, 3], stride=2, scope='latent_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm1'})", "scope='convt7', activation_fn=None) masks = tf.reshape( tf.nn.softmax(tf.reshape(masks, [-1, num_masks + 1])),", "latent_enc2 = slim.conv2d( latent_enc1, 64, [3, 3], stride=2, scope='latent_conv2', normalizer_fn=tf_layers.layer_norm,", "= tf.cond(iter_num < FLAGS.num_iterations_1st_stage, lambda: tf.identity(latent), lambda: latent_mean + tf.exp(latent_std", "3], stride=2, scope='conv2') hidden3, lstm_state3 = lstm_func( enc1, lstm_state3, lstm_size[2],", "raise ValueError('Only one mask is supported for DNA model.') transformed", "as slim from tensorflow.python.platform import flags from tensorflow.contrib.layers.python import layers", "law or agreed to in writing, software # distributed under", "# Only import spatial transformer if needed. from spatial_transformer import", "lstm_state6, lstm_state7 = None, None, None # Latent tower latent_loss", "tf.concat(axis=3, values=[enc2, smear]) # Setup latent if FLAGS.stochastic_model: latent =", "None, None, None, None lstm_state5, lstm_state6, lstm_state7 = None, None,", "= tf.reshape(hidden5, [int(batch_size), -1]) stp_input1 = slim.layers.fully_connected( stp_input0, 100, scope='fc_stp')", "enc3 = slim.layers.conv2d( enc2, hidden4.get_shape()[3], [1, 1], stride=1, scope='conv4') hidden5,", "dimensions. prev_image = tf.transpose(prev_image, [3, 1, 2, 0]) # Transform", "the tower is disabled and only returns latents sampled from", "DNA_KERN_SIZE, DNA_KERN_SIZE, 1, num_masks]) cdna_kerns = tf.nn.relu(cdna_kerns - RELU_SHIFT) +", "lstm_func( enc1, lstm_state3, lstm_size[2], scope='state3') hidden3 = tf_layers.layer_norm(hidden3, scope='layer_norm4') hidden4,", "latent twoer samples: random samples sampled from standard guassian \"\"\"", "may obtain a copy of the License at # #", "cdna_input, num_masks, int(color_channels)) elif dna: # Only one mask is", "previous image to be transformed. dna_input: hidden lyaer to be", "= tf_layers.layer_norm(hidden5, scope='layer_norm6') enc4 = slim.layers.conv2d_transpose( hidden5, hidden5.get_shape()[3], 3, stride=2,", "latent mean latent_std: predicted latent standard deviation latent_loss: loss of", "Returns: New batch with num_ground_truth sampled from ground_truth_x and the", "may not use this file except in compliance with the", "/ tf.reduce_sum( kernel, [3], keep_dims=True), [4]) return tf.reduce_sum(kernel * inputs,", "tf.transpose(transformed, [3, 1, 2, 0, 4]) transformed = tf.unstack(transformed, axis=-1)", "number of different pixel motion predictions (and the number of", "4]) transformed = tf.unstack(transformed, axis=-1) return transformed def dna_transformation(prev_image, dna_input):", "this file except in compliance with the License. # You", "would be generated. Args: images: tensor of ground truth image", "in the images. Returns: List of images transformed by the", "useful when regions of the image become unoccluded. transformed =", "tf.random_normal( [FLAGS.sequence_length-1] + latent_mean.shape, 0, 1, dtype=tf.float32) else: # batch_size", "gen_images[-1], batch_size, num_ground_truth) else: # Always feed in ground_truth prev_image", "-1]) stp_input1 = slim.layers.fully_connected( stp_input0, 100, scope='fc_stp') transformed += stp_transformation(prev_image,", "# Using largest hidden state for predicting untied conv kernels.", "parameter of the distribution. log_sigma: log(sigma) parameter of the distribution.", "100, scope='fc_stp') transformed += stp_transformation(prev_image, stp_input1, num_masks) elif cdna: cdna_input", "# # Licensed under the Apache License, Version 2.0 (the", "/ (k + tf.exp(iter_num / k))))) feedself = False #", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "numpy as np import tensorflow as tf import tensorflow.contrib.slim as", "distribution (mean and std) conditioned on the entire video. This", "# Treat the color channel dimension as the batch dimension", "= basic_conv_lstm_cell # Generated robot states and images. gen_states, gen_images", "of action sequences states: tensor of ground truth state sequences", "log_sigma): \"\"\"KL divergence of diagonal gaussian N(mu,exp(log_sigma)) and N(0,1). Args:", "= [] for xkern in range(DNA_KERN_SIZE): for ykern in range(DNA_KERN_SIZE):", "KL loss. \"\"\" return -.5 * tf.reduce_sum(1. + log_sigma -", "# transformation is applied to each color channel. # Treat", "to include state and action in prediction num_masks: the number", "hidden1 = tf_layers.layer_norm(hidden1, scope='layer_norm2') hidden2, lstm_state2 = lstm_func( hidden1, lstm_state2,", "(k + tf.exp(iter_num / k))))) feedself = False # LSTM", "to be used for computing DNA transformation. Returns: List of", "Pass in state and action. smear = tf.reshape( state_action, [int(batch_size),", "from generated_x. \"\"\" idx = tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth))", "after the first timestep. reuse = bool(gen_images) done_warm_start = len(gen_images)", "predicted future states Raises: ValueError: if more than one network", "slim.layers.conv2d_transpose( enc6, num_masks + 1, 1, stride=1, scope='convt7', activation_fn=None) masks", "kernels. num_masks: the number of masks and hence the number", "future image frames gen_states: predicted future states Raises: ValueError: if", "int(prev_image.get_shape()[1]) image_width = int(prev_image.get_shape()[2]) inputs = [] for xkern in", "# Construct translated images. prev_image_pad = tf.pad(prev_image, [[0, 0], [2,", "1], stride=1, scope='conv4') hidden5, lstm_state5 = lstm_func( enc3, lstm_state5, lstm_size[4],", "cdna_input, num_masks, color_channels): \"\"\"Apply convolutional dynamic neural advection to previous", "predictive model, including CDNA, DNA, and STP.\"\"\" import numpy as", "tf_layers.layer_norm(hidden7, scope='layer_norm8') # Skip connection. hidden7 = tf.concat(axis=3, values=[hidden7, enc0])", "= slim.layers.fully_connected( stp_input0, 100, scope='fc_stp') transformed += stp_transformation(prev_image, stp_input1, num_masks)", "-1]) transformed += cdna_transformation(prev_image, cdna_input, num_masks, int(color_channels)) elif dna: #", "scope='conv3') # Pass in state and action. smear = tf.reshape(", "TensorFlow Authors All Rights Reserved. # # Licensed under the", "states: tensor of ground truth state sequences iter_num: tensor of", "return latent_mean, latent_std, latent_loss, samples def construct_model(images, actions=None, states=None, iter_num=-1.0,", "hidden6, hidden6.get_shape()[3], 3, stride=2, scope='convt2') hidden7, lstm_state7 = lstm_func( enc5,", "= slim.layers.conv2d( hidden4, hidden4.get_shape()[3], [3, 3], stride=2, scope='conv3') # Pass", "for computing CDNA kernels. num_masks: the number of masks and", "the predicted CDNA kernels. \"\"\" batch_size = int(cdna_input.get_shape()[0]) height =", "Args: prev_image: previous image to be transformed. cdna_input: hidden lyaer", "Returns: latent_mean: predicted latent mean latent_std: predicted latent standard deviation", "(mean and std) conditioned on the entire video. This latent", "dynamic neural advection to previous image. Args: prev_image: previous image", "truth and generated data points. Args: ground_truth_x: tensor of ground-truth", "or implied. # See the License for the specific language", "tf.square(mu) - tf.exp(log_sigma), axis=1) def construct_latent_tower(images): \"\"\"Builds convolutional latent tower", "tf.split(axis=3, num_or_size_splits=num_masks + 1, value=masks) output = mask_list[0] * prev_image", "DNA transformation. Returns: List of images transformed by the predicted", "specified mix of ground truth and generated data points. Args:", "3) latent_enc1 = slim.conv2d( stacked_images, 32, [3, 3], stride=2, scope='latent_conv1',", "DNA_KERN_SIZE * num_masks, scope='cdna_params', activation_fn=None) # Reshape and normalize. cdna_kerns", "prediction num_masks: the number of different pixel motion predictions (and", "= gen_images[-1] elif done_warm_start: # Scheduled sampling prev_image = scheduled_sample(image,", "latent tower at inference time, just standard gaussian. return None,", "activation_fn=None) else: # Using largest hidden state for predicting a", "feeding in own predictions Returns: gen_images: predicted future image frames", "latent = samples[timestep] if not FLAGS.inference_time: latent = tf.cond(iter_num <", "if more than one network option specified or more than", "values=[hidden7, enc0]) # both 32x32 enc6 = slim.layers.conv2d_transpose( hidden7, hidden7.get_shape()[3],", "zip(transformed, mask_list[1:]): output += layer * mask gen_images.append(output) current_state =", "FLAGS.stochastic_model: latent_tower_outputs = construct_latent_tower(images) latent_mean, latent_std, latent_loss, samples = latent_tower_outputs", "Skip connection. hidden7 = tf.concat(axis=3, values=[hidden7, enc0]) # both 32x32", "Returns: List of images transformed by the predicted CDNA kernels.", "[3], keep_dims=False) def scheduled_sample(ground_truth_x, generated_x, batch_size, num_ground_truth): \"\"\"Sample batch with", "loss of the latent twoer samples: random samples sampled from", "tf.reshape( state_action, [int(batch_size), 1, 1, int(state_action.get_shape()[1])]) smear = tf.tile( smear,", "= tf.tile( smear, [1, int(enc2.get_shape()[1]), int(enc2.get_shape()[2]), 1]) if use_state: enc2", "Using largest hidden state for predicting untied conv kernels. enc7", "rest from generated_x. \"\"\" idx = tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx = tf.gather(idx,", "\"\"\"Sample batch with specified mix of ground truth and generated", "use Spatial Transformer Predictor (STP) cdna: True to use Convoluational", "64, [3, 3], stride=2, scope='latent_conv2', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm2'}) latent_enc3 =", "both, ... # ... given how TF queues work. images", "[tf.identity(image) for image in images] if stp + cdna +", "from standard guassian \"\"\" with slim.arg_scope([slim.conv2d], reuse=False): stacked_images = tf.concat(images,", "latent if FLAGS.stochastic_model: latent = samples if FLAGS.multi_latent: latent =", "image in images] if stp + cdna + dna !=", "# Scheduled sampling prev_image = scheduled_sample(image, gen_images[-1], batch_size, num_ground_truth) else:", "[1, 2, 3], keep_dims=True) cdna_kerns /= norm_factor # Treat the", "prev_image = image # Predicted state is always fed back", "and CDNA. DNA_KERN_SIZE = 5 def kl_divergence(mu, log_sigma): \"\"\"KL divergence", "inputs, [3], keep_dims=False) def scheduled_sample(ground_truth_x, generated_x, batch_size, num_ground_truth): \"\"\"Sample batch", "scope='conv2') hidden3, lstm_state3 = lstm_func( enc1, lstm_state3, lstm_size[2], scope='state3') hidden3", "(and the number of masks for each of those predictions)", "batch_size, img_height, img_width, color_channels = images[0].get_shape()[0:4] lstm_func = basic_conv_lstm_cell #", "prev_image = scheduled_sample(image, gen_images[-1], batch_size, num_ground_truth) else: # Always feed", "\"\"\"Builds convolutional latent tower for stochastic model. At training time", "\"\"\" # Each image is being used twice, in latent", "if feedself and done_warm_start: # Feed in generated image. prev_image", "ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth)) generated_idx = tf.gather(idx, tf.range(num_ground_truth, int(batch_size))) ground_truth_examps", "the first timestep. reuse = bool(gen_images) done_warm_start = len(gen_images) >", "batch and channel dimensions. prev_image = tf.transpose(prev_image, [3, 1, 2,", "kernel size for DNA and CDNA. DNA_KERN_SIZE = 5 def", "xkern in range(DNA_KERN_SIZE): for ykern in range(DNA_KERN_SIZE): inputs.append( tf.expand_dims( tf.slice(prev_image_pad,", "to use Convoluational Dynamic Neural Advection (CDNA) dna: True to", "DNA and CDNA. DNA_KERN_SIZE = 5 def kl_divergence(mu, log_sigma): \"\"\"KL", "images. Returns: List of images transformed by the predicted CDNA", "option specified or more than 1 mask specified for DNA", "transformer predictor (STP) to previous image. Args: prev_image: previous image", "tf.reshape(hidden5, [int(batch_size), -1]) transformed += cdna_transformation(prev_image, cdna_input, num_masks, int(color_channels)) elif", "generated. Args: images: tensor of ground truth image sequences Returns:", "enc1, lstm_state3, lstm_size[2], scope='state3') hidden3 = tf_layers.layer_norm(hidden3, scope='layer_norm4') hidden4, lstm_state4", "prev_image = gen_images[-1] elif done_warm_start: # Scheduled sampling prev_image =", "each of those predictions) stp: True to use Spatial Transformer", "samples sampled from standard guassian \"\"\" with slim.arg_scope([slim.conv2d], reuse=False): stacked_images", "'latent_norm3'}) latent_mean = slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3], stride=2, activation_fn=None,", "in state_action = tf.concat(axis=1, values=[action, current_state]) enc0 = slim.layers.conv2d( prev_image,", "being used twice, in latent tower and main tower. #", "scope='convt1') hidden6, lstm_state6 = lstm_func( enc4, lstm_state6, lstm_size[5], scope='state6') #", "data points. Args: ground_truth_x: tensor of ground-truth data points. generated_x:", "tf_layers.layer_norm, slim.layers.conv2d_transpose], reuse=reuse): if feedself and done_warm_start: # Feed in", "Returns: List of images transformed by the predicted STP parameters.", "tf.reduce_sum(cdna_kerns, [1, 2, 3], keep_dims=True) cdna_kerns /= norm_factor # Treat", "Swap the batch and channel dimensions. prev_image = tf.transpose(prev_image, [3,", "tf.gather(idx, tf.range(num_ground_truth)) generated_idx = tf.gather(idx, tf.range(num_ground_truth, int(batch_size))) ground_truth_examps = tf.gather(ground_truth_x,", "DNA. Args: images: tensor of ground truth image sequences actions:", "latent tower and main tower. # This is to make", "(k / (k + tf.exp(iter_num / k))))) feedself = False", "num_ground_truth = tf.to_int32( tf.round(tf.to_float(batch_size) * (k / (k + tf.exp(iter_num", "time, the tower is disabled and only returns latents sampled", "latent = tf.cond(iter_num < FLAGS.num_iterations_1st_stage, lambda: tf.identity(latent), lambda: latent_mean +", "Args: mu: mu parameter of the distribution. log_sigma: log(sigma) parameter", "hidden lyaer to be used for computing CDNA kernels. num_masks:", "points. batch_size: batch size num_ground_truth: number of ground-truth examples to", "sure we are using the *same* image for both, ...", "# Main tower for image, action in zip(images[:-1], actions[:-1]): #", "returns latents sampled from N(0,1). If the multi_latent flag is", "with slim.arg_scope( [lstm_func, slim.layers.conv2d, slim.layers.fully_connected, tf_layers.layer_norm, slim.layers.conv2d_transpose], reuse=reuse): if feedself", "pass in. num_ground_truth = tf.to_int32( tf.round(tf.to_float(batch_size) * (k / (k", "is disabled and only returns latents sampled from N(0,1). If", "images. prev_image_pad = tf.pad(prev_image, [[0, 0], [2, 2], [2, 2],", "else: return latent_mean, latent_std, latent_loss, samples def construct_model(images, actions=None, states=None,", "in writing, software # distributed under the License is distributed", "points. generated_x: tensor of generated data points. batch_size: batch size", "ground-truth frames to pass in. num_ground_truth = tf.to_int32( tf.round(tf.to_float(batch_size) *", "int(enc2.get_shape()[1]), int(enc2.get_shape()[2]), 1]) if use_state: enc2 = tf.concat(axis=3, values=[enc2, smear])", "image. Args: prev_image: previous image to be transformed. cdna_input: hidden", "latent standard deviation latent_loss: loss of the latent twoer samples:", "+= stp_transformation(prev_image, stp_input1, num_masks) elif cdna: cdna_input = tf.reshape(hidden5, [int(batch_size),", "stride=2, scope='convt2') hidden7, lstm_state7 = lstm_func( enc5, lstm_state7, lstm_size[6], scope='state7')", "transformed by the predicted CDNA kernels. \"\"\" # Construct translated", "than one network option specified or more than 1 mask", "# Always feed in ground_truth prev_image = image # Predicted", "from scratch, # which is useful when regions of the", "N(mu,exp(log_sigma)) and N(0,1). Args: mu: mu parameter of the distribution.", "range(DNA_KERN_SIZE): inputs.append( tf.expand_dims( tf.slice(prev_image_pad, [0, xkern, ykern, 0], [-1, image_height,", "\"\"\" return -.5 * tf.reduce_sum(1. + log_sigma - tf.square(mu) -", "0.0 if FLAGS.stochastic_model: latent_tower_outputs = construct_latent_tower(images) latent_mean, latent_std, latent_loss, samples", "as tf_layers from lstm_ops import basic_conv_lstm_cell FLAGS = flags.FLAGS #", "k=-1, use_state=True, num_masks=10, stp=False, cdna=True, dna=False, context_frames=2): \"\"\"Build convolutional lstm", "= slim.layers.conv2d_transpose( hidden6, hidden6.get_shape()[3], 3, stride=2, scope='convt2') hidden7, lstm_state7 =", "transformations. color_channels: the number of color channels in the images.", "3) enc3 = slim.layers.conv2d( enc2, hidden4.get_shape()[3], [1, 1], stride=1, scope='conv4')", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "lstm_state5 = lstm_func( enc3, lstm_state5, lstm_size[4], scope='state5') # last 8x8", "masks = tf.reshape( tf.nn.softmax(tf.reshape(masks, [-1, num_masks + 1])), [int(batch_size), int(img_height),", "* DNA_KERN_SIZE * num_masks, scope='cdna_params', activation_fn=None) # Reshape and normalize.", "3, stride=2, scope='convt2') hidden7, lstm_state7 = lstm_func( enc5, lstm_state7, lstm_size[6],", "transformed def dna_transformation(prev_image, dna_input): \"\"\"Apply dynamic neural advection to previous", "slim.conv2d( latent_enc2, 64, [3, 3], stride=1, scope='latent_conv3', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm3'})", "= tf.reshape( state_action, [int(batch_size), 1, 1, int(state_action.get_shape()[1])]) smear = tf.tile(", "scope='layer_norm4') hidden4, lstm_state4 = lstm_func( hidden3, lstm_state4, lstm_size[3], scope='state4') hidden4", "tf.reshape(cdna_kerns, [DNA_KERN_SIZE, DNA_KERN_SIZE, batch_size, num_masks]) # Swap the batch and", "-1]), [3])) inputs = tf.concat(axis=3, values=inputs) # Normalize channels to", "[5, 5], stride=2, scope='scale1_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm1'}) hidden1, lstm_state1 =", "keep_dims=False) def scheduled_sample(ground_truth_x, generated_x, batch_size, num_ground_truth): \"\"\"Sample batch with specified", "scope='latent_mean', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm_mean'}) latent_std = slim.conv2d( latent_enc3, FLAGS.latent_channels, [3,", "slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3], stride=2, activation_fn=None, scope='latent_mean', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope':", "latent_enc1 = slim.conv2d( stacked_images, 32, [3, 3], stride=2, scope='latent_conv1', normalizer_fn=tf_layers.layer_norm,", "divergence = kl_divergence(latent_mean, latent_std) latent_loss = tf.reduce_mean(divergence) if FLAGS.multi_latent: #", "latent = samples if FLAGS.multi_latent: latent = samples[timestep] if not", "channel. # Treat the batch dimension as the channel dimension", "3], stride=2, activation_fn=None, scope='latent_mean', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm_mean'}) latent_std = slim.conv2d(", "of ground truth image sequences Returns: latent_mean: predicted latent mean", "the License for the specific language governing permissions and #", "# Amount to use when lower bounding tensors RELU_SHIFT =", "def kl_divergence(mu, log_sigma): \"\"\"KL divergence of diagonal gaussian N(mu,exp(log_sigma)) and", "stride=1, scope='conv4') hidden5, lstm_state5 = lstm_func( enc3, lstm_state5, lstm_size[4], scope='state5')", "Utility functions def stp_transformation(prev_image, stp_input, num_masks): \"\"\"Apply spatial transformer predictor", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "basic_conv_lstm_cell # Generated robot states and images. gen_states, gen_images =", "3], stride=1, scope='latent_conv3', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm3'}) latent_mean = slim.conv2d( latent_enc3,", "state and action. smear = tf.reshape( state_action, [int(batch_size), 1, 1,", "pass in before feeding in own predictions Returns: gen_images: predicted", "= tf.unstack(transformed, axis=-1) return transformed def dna_transformation(prev_image, dna_input): \"\"\"Apply dynamic", "predicting a new image layer. enc7 = slim.layers.conv2d_transpose( enc6, color_channels,", "True to use Dynamic Neural Advection (DNA) context_frames: number of", "sample. cdna_kerns = tf.transpose(cdna_kerns, [1, 2, 0, 4, 3]) cdna_kerns", "# last 8x8 hidden5 = tf_layers.layer_norm(hidden5, scope='layer_norm6') enc4 = slim.layers.conv2d_transpose(", "= tf.reshape( cdna_kerns, [batch_size, DNA_KERN_SIZE, DNA_KERN_SIZE, 1, num_masks]) cdna_kerns =", "int(prev_image.get_shape()[2]) inputs = [] for xkern in range(DNA_KERN_SIZE): for ykern", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "6, scope='stp_params' + str(i), activation_fn=None) + identity_params transformed.append(transformer(prev_image, params)) return", "3], stride=2, scope='latent_std', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_std_norm'}) latent_std += FLAGS.latent_std_min divergence", "largest hidden state for predicting a new image layer. enc7", "[1, 2, 0, 4, 3]) cdna_kerns = tf.reshape(cdna_kerns, [DNA_KERN_SIZE, DNA_KERN_SIZE,", "feed in ground_truth prev_image = image # Predicted state is", "channel dimension so that # depthwise_conv2d can apply a different", "samples = tf.random_normal(latent_mean.shape, 0, 1, dtype=tf.float32) if FLAGS.inference_time: # No", "ground_truth_x and the rest from generated_x. \"\"\" idx = tf.random_shuffle(tf.range(int(batch_size)))", "conditioned on the entire video. This latent variable will be", "+ identity_params transformed.append(transformer(prev_image, params)) return transformed def cdna_transformation(prev_image, cdna_input, num_masks,", "RELU_SHIFT norm_factor = tf.reduce_sum(cdna_kerns, [1, 2, 3], keep_dims=True) cdna_kerns /=", "one image from scratch, # which is useful when regions", "latent], 3) enc3 = slim.layers.conv2d( enc2, hidden4.get_shape()[3], [1, 1], stride=1,", "latent_loss = 0.0 if FLAGS.stochastic_model: latent_tower_outputs = construct_latent_tower(images) latent_mean, latent_std,", "= slim.conv2d( latent_enc2, 64, [3, 3], stride=1, scope='latent_conv3', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope':", "for i in range(num_masks - 1): params = slim.layers.fully_connected( stp_input,", "slim.layers.conv2d_transpose( enc6, DNA_KERN_SIZE**2, 1, stride=1, scope='convt4', activation_fn=None) else: # Using", "# distributed under the License is distributed on an \"AS", "states Raises: ValueError: if more than one network option specified", "1, stride=1, scope='convt4', activation_fn=None) else: # Using largest hidden state", "# Unless required by applicable law or agreed to in", "convolutional dynamic neural advection to previous image. Args: prev_image: previous", "# Predict kernels using linear function of last hidden layer.", "cdna + dna != 1: raise ValueError('More than one, or", "0]) # Transform image. transformed = tf.nn.depthwise_conv2d(prev_image, cdna_kerns, [1, 1,", "# which is useful when regions of the image become", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "lstm_state5, lstm_size[4], scope='state5') # last 8x8 hidden5 = tf_layers.layer_norm(hidden5, scope='layer_norm6')", "transformations. Returns: List of images transformed by the predicted STP", "Main tower for image, action in zip(images[:-1], actions[:-1]): # Reuse", "number of masks and hence the number of STP transformations.", "# This allows the network to also generate one image", "tf_layers.layer_norm(hidden4, scope='layer_norm5') enc2 = slim.layers.conv2d( hidden4, hidden4.get_shape()[3], [3, 3], stride=2,", "# Reuse variables after the first timestep. reuse = bool(gen_images)", "predictions) stp: True to use Spatial Transformer Predictor (STP) cdna:", "latent variable will be fed to the main tower as", "transformed = [tf.nn.sigmoid(enc7)] if stp: stp_input0 = tf.reshape(hidden5, [int(batch_size), -1])", "lstm_state4, lstm_size[3], scope='state4') hidden4 = tf_layers.layer_norm(hidden4, scope='layer_norm5') enc2 = slim.layers.conv2d(", "2016 The TensorFlow Authors All Rights Reserved. # # Licensed", "slim.layers.fully_connected( state_action, int(current_state.get_shape()[1]), scope='state_pred', activation_fn=None) gen_states.append(current_state) return gen_images, gen_states, latent_loss", "\"\"\"Build convolutional lstm video predictor using STP, CDNA, or DNA.", "the Apache License, Version 2.0 (the \"License\"); # you may", "This is to make sure we are using the *same*", "[3, 3], stride=2, scope='conv2') hidden3, lstm_state3 = lstm_func( enc1, lstm_state3,", "always fed back in state_action = tf.concat(axis=1, values=[action, current_state]) enc0", "tf import tensorflow.contrib.slim as slim from tensorflow.python.platform import flags from", "image # Predicted state is always fed back in state_action", "divergence of diagonal gaussian N(mu,exp(log_sigma)) and N(0,1). Args: mu: mu", "standard guassian \"\"\" with slim.arg_scope([slim.conv2d], reuse=False): stacked_images = tf.concat(images, 3)", "computing DNA transformation. Returns: List of images transformed by the", "smear = tf.tile( smear, [1, int(enc2.get_shape()[1]), int(enc2.get_shape()[2]), 1]) if use_state:", "slim.layers.conv2d_transpose( hidden5, hidden5.get_shape()[3], 3, stride=2, scope='convt1') hidden6, lstm_state6 = lstm_func(", "limitations under the License. # ============================================================================== \"\"\"Model architecture for predictive", "if FLAGS.multi_latent: # timestep x batch_size x latent_size samples =", "elif done_warm_start: # Scheduled sampling prev_image = scheduled_sample(image, gen_images[-1], batch_size,", "3], stride=2, scope='conv3') # Pass in state and action. smear", "[1, int(enc2.get_shape()[1]), int(enc2.get_shape()[2]), 1]) if use_state: enc2 = tf.concat(axis=3, values=[enc2,", "gen_images = [], [] current_state = states[0] if k ==", "return transformed def dna_transformation(prev_image, dna_input): \"\"\"Apply dynamic neural advection to", "a latent distribution (mean and std) conditioned on the entire", "of ground-truth frames to pass in. num_ground_truth = tf.to_int32( tf.round(tf.to_float(batch_size)", "Transpose the dimensions to where they belong. transformed = tf.reshape(transformed,", "state_action, [int(batch_size), 1, 1, int(state_action.get_shape()[1])]) smear = tf.tile( smear, [1,", "# Reshape and normalize. cdna_kerns = tf.reshape( cdna_kerns, [batch_size, DNA_KERN_SIZE,", "the network to also generate one image from scratch, #", "+ 1]) mask_list = tf.split(axis=3, num_or_size_splits=num_masks + 1, value=masks) output", "in own predictions Returns: gen_images: predicted future image frames gen_states:", "of STP transformations. Returns: List of images transformed by the", "ground_truth_idx) generated_examps = tf.gather(generated_x, generated_idx) return tf.dynamic_stitch([ground_truth_idx, generated_idx], [ground_truth_examps, generated_examps])", "2], [2, 2], [0, 0]]) image_height = int(prev_image.get_shape()[1]) image_width =", "= [], [] current_state = states[0] if k == -1:", "convolutional lstm video predictor using STP, CDNA, or DNA. Args:", "slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3], stride=2, scope='latent_std', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_std_norm'})", "- 1 with slim.arg_scope( [lstm_func, slim.layers.conv2d, slim.layers.fully_connected, tf_layers.layer_norm, slim.layers.conv2d_transpose], reuse=reuse):", "include in batch. Returns: New batch with num_ground_truth sampled from", "batch dimension since the same # transformation is applied to", "for layer, mask in zip(transformed, mask_list[1:]): output += layer *", "slim.layers.conv2d( hidden4, hidden4.get_shape()[3], [3, 3], stride=2, scope='conv3') # Pass in", "dna: True to use Dynamic Neural Advection (DNA) context_frames: number", "lstm_func( enc5, lstm_state7, lstm_size[6], scope='state7') # 32x32 hidden7 = tf_layers.layer_norm(hidden7,", "under the License is distributed on an \"AS IS\" BASIS,", "stp_input, 6, scope='stp_params' + str(i), activation_fn=None) + identity_params transformed.append(transformer(prev_image, params))", "the multi_latent flag is on, a different latent for every", "# Each image is being used twice, in latent tower", "stochastic model. At training time this tower generates a latent", "just standard gaussian. return None, None, None, samples else: return", "enc0]) # both 32x32 enc6 = slim.layers.conv2d_transpose( hidden7, hidden7.get_shape()[3], 3,", "kernels. \"\"\" # Construct translated images. prev_image_pad = tf.pad(prev_image, [[0,", "model. \"\"\" # Each image is being used twice, in", "data points. generated_x: tensor of generated data points. batch_size: batch", "timestep. reuse = bool(gen_images) done_warm_start = len(gen_images) > context_frames -", "the current training iteration (for sched. sampling) k: constant used", "At inference time, the tower is disabled and only returns", "hidden6.get_shape()[3], 3, stride=2, scope='convt2') hidden7, lstm_state7 = lstm_func( enc5, lstm_state7,", "!= 1: raise ValueError('More than one, or no network option", "predictor using STP, CDNA, or DNA. Args: images: tensor of", "num_masks]) # Swap the batch and channel dimensions. prev_image =", "= latent_tower_outputs # Main tower for image, action in zip(images[:-1],", "32x32 enc6 = slim.layers.conv2d_transpose( hidden7, hidden7.get_shape()[3], 3, stride=2, scope='convt3', activation_fn=None,", "64, 32])) lstm_state1, lstm_state2, lstm_state3, lstm_state4 = None, None, None,", "np.int32(np.array([32, 32, 64, 64, 128, 64, 32])) lstm_state1, lstm_state2, lstm_state3,", "LSTM state sizes and states. lstm_size = np.int32(np.array([32, 32, 64,", "gaussian. return None, None, None, samples else: return latent_mean, latent_std,", "lstm_size[5], scope='state6') # 16x16 hidden6 = tf_layers.layer_norm(hidden6, scope='layer_norm7') # Skip", "stride=1, scope='convt7', activation_fn=None) masks = tf.reshape( tf.nn.softmax(tf.reshape(masks, [-1, num_masks +", "samples else: return latent_mean, latent_std, latent_loss, samples def construct_model(images, actions=None,", "of those predictions) stp: True to use Spatial Transformer Predictor", "and action. smear = tf.reshape( state_action, [int(batch_size), 1, 1, int(state_action.get_shape()[1])])", "1 with slim.arg_scope( [lstm_func, slim.layers.conv2d, slim.layers.fully_connected, tf_layers.layer_norm, slim.layers.conv2d_transpose], reuse=reuse): if", "= tf_layers.layer_norm(hidden3, scope='layer_norm4') hidden4, lstm_state4 = lstm_func( hidden3, lstm_state4, lstm_size[3],", "feedself = False # LSTM state sizes and states. lstm_size", "- tf.exp(log_sigma), axis=1) def construct_latent_tower(images): \"\"\"Builds convolutional latent tower for", "for DNA model.') transformed = [dna_transformation(prev_image, enc7)] masks = slim.layers.conv2d_transpose(", "specified.') batch_size, img_height, img_width, color_channels = images[0].get_shape()[0:4] lstm_func = basic_conv_lstm_cell", "0], [-1, image_height, image_width, -1]), [3])) inputs = tf.concat(axis=3, values=inputs)", "3]) cdna_kerns = tf.reshape(cdna_kerns, [DNA_KERN_SIZE, DNA_KERN_SIZE, batch_size, num_masks]) # Swap", "= tf.gather(ground_truth_x, ground_truth_idx) generated_examps = tf.gather(generated_x, generated_idx) return tf.dynamic_stitch([ground_truth_idx, generated_idx],", "# ... given how TF queues work. images = [tf.identity(image)", "ANY KIND, either express or implied. # See the License", "image to be transformed. dna_input: hidden lyaer to be used", "scope='layer_norm3') enc1 = slim.layers.conv2d( hidden2, hidden2.get_shape()[3], [3, 3], stride=2, scope='conv2')", "the License. # You may obtain a copy of the", "tf_layers from lstm_ops import basic_conv_lstm_cell FLAGS = flags.FLAGS # Amount", "generates a latent distribution (mean and std) conditioned on the", "else: # Using largest hidden state for predicting a new", "# See the License for the specific language governing permissions", "0, 4, 3]) cdna_kerns = tf.reshape(cdna_kerns, [DNA_KERN_SIZE, DNA_KERN_SIZE, batch_size, num_masks])", "log_sigma - tf.square(mu) - tf.exp(log_sigma), axis=1) def construct_latent_tower(images): \"\"\"Builds convolutional", "gen_states.append(current_state) return gen_images, gen_states, latent_loss ## Utility functions def stp_transformation(prev_image,", "main tower. # This is to make sure we are", "image for both, ... # ... given how TF queues", "of the latent twoer samples: random samples sampled from standard", "transformed by the predicted STP parameters. \"\"\" # Only import", "flags.FLAGS # Amount to use when lower bounding tensors RELU_SHIFT", "main tower as an extra variable to be used for", "both 16x16 enc5 = slim.layers.conv2d_transpose( hidden6, hidden6.get_shape()[3], 3, stride=2, scope='convt2')", "3], stride=2, scope='latent_conv2', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm2'}) latent_enc3 = slim.conv2d( latent_enc2,", "batch_size x latent_size samples = tf.random_normal( [FLAGS.sequence_length-1] + latent_mean.shape, 0,", "in range(DNA_KERN_SIZE): inputs.append( tf.expand_dims( tf.slice(prev_image_pad, [0, xkern, ykern, 0], [-1,", "more than one network option specified or more than 1", "hidden3, lstm_state4, lstm_size[3], scope='state4') hidden4 = tf_layers.layer_norm(hidden4, scope='layer_norm5') enc2 =", "spatial transformer if needed. from spatial_transformer import transformer identity_params =", "transformed. stp_input: hidden layer to be used for computing STN", "latent) with tf.control_dependencies([latent]): enc2 = tf.concat([enc2, latent], 3) enc3 =", "DNA model. \"\"\" # Each image is being used twice,", "CDNA transformations. color_channels: the number of color channels in the", "lstm_state2 = lstm_func( hidden1, lstm_state2, lstm_size[1], scope='state2') hidden2 = tf_layers.layer_norm(hidden2,", "activation_fn=None) + identity_params transformed.append(transformer(prev_image, params)) return transformed def cdna_transformation(prev_image, cdna_input,", "enc2 = slim.layers.conv2d( hidden4, hidden4.get_shape()[3], [3, 3], stride=2, scope='conv3') #", "to where they belong. transformed = tf.reshape(transformed, [color_channels, height, width,", "batch_size, num_masks]) # Swap the batch and channel dimensions. prev_image", "range(num_masks - 1): params = slim.layers.fully_connected( stp_input, 6, scope='stp_params' +", "= flags.FLAGS # Amount to use when lower bounding tensors", "samples def construct_model(images, actions=None, states=None, iter_num=-1.0, k=-1, use_state=True, num_masks=10, stp=False,", "mask is supported (more should be unnecessary). if num_masks !=", "latent_mean, latent_std, latent_loss, samples = latent_tower_outputs # Main tower for", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "(more should be unnecessary). if num_masks != 1: raise ValueError('Only", "stride=1, scope='convt4', activation_fn=None) else: # Using largest hidden state for", "in images] if stp + cdna + dna != 1:", "tensor of ground truth image sequences actions: tensor of action", "masks for each of those predictions) stp: True to use", "writing, software # distributed under the License is distributed on", "[3, 3], stride=2, scope='latent_conv2', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm2'}) latent_enc3 = slim.conv2d(", "parameters. num_masks: number of masks and hence the number of", "is always fed back in state_action = tf.concat(axis=1, values=[action, current_state])", "Returns: gen_images: predicted future image frames gen_states: predicted future states", "enc4 = slim.layers.conv2d_transpose( hidden5, hidden5.get_shape()[3], 3, stride=2, scope='convt1') hidden6, lstm_state6", "[0, 0]]) image_height = int(prev_image.get_shape()[1]) image_width = int(prev_image.get_shape()[2]) inputs =", "previous image. Args: prev_image: previous image to be transformed. dna_input:", "cdna_kerns = slim.layers.fully_connected( cdna_input, DNA_KERN_SIZE * DNA_KERN_SIZE * num_masks, scope='cdna_params',", "predictor (STP) to previous image. Args: prev_image: previous image to", "lstm_func = basic_conv_lstm_cell # Generated robot states and images. gen_states,", "hidden2, lstm_state2 = lstm_func( hidden1, lstm_state2, lstm_size[1], scope='state2') hidden2 =", "keep_dims=True) cdna_kerns /= norm_factor # Treat the color channel dimension", "the dimensions to where they belong. transformed = tf.reshape(transformed, [color_channels,", "current_state = states[0] if k == -1: feedself = True", "- RELU_SHIFT) + RELU_SHIFT norm_factor = tf.reduce_sum(cdna_kerns, [1, 2, 3],", "for scheduled sampling. -1 to feed in own prediction. use_state:", "activation_fn=None, normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm9'}) if dna: # Using largest hidden", "advection to previous image. Args: prev_image: previous image to be", "and std) conditioned on the entire video. This latent variable", "= [] for i in range(num_masks - 1): params =", "stp_transformation(prev_image, stp_input, num_masks): \"\"\"Apply spatial transformer predictor (STP) to previous", "# No latent tower at inference time, just standard gaussian.", "1, 1], 'SAME') # Transpose the dimensions to where they", "tf.exp(latent_std / 2.0) * latent) with tf.control_dependencies([latent]): enc2 = tf.concat([enc2,", "stacked_images, 32, [3, 3], stride=2, scope='latent_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm1'}) latent_enc2", "a different transformation to each sample. cdna_kerns = tf.transpose(cdna_kerns, [1,", "different transformation to each sample. cdna_kerns = tf.transpose(cdna_kerns, [1, 2,", "hidden lyaer to be used for computing DNA transformation. Returns:", "int(enc2.get_shape()[2]), 1]) if use_state: enc2 = tf.concat(axis=3, values=[enc2, smear]) #", "layer. enc7 = slim.layers.conv2d_transpose( enc6, color_channels, 1, stride=1, scope='convt4', activation_fn=None)", "slim.conv2d( latent_enc1, 64, [3, 3], stride=2, scope='latent_conv2', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm2'})", "slim.layers.conv2d( hidden2, hidden2.get_shape()[3], [3, 3], stride=2, scope='conv2') hidden3, lstm_state3 =", "the number of masks for each of those predictions) stp:", "be transformed. cdna_input: hidden lyaer to be used for computing", "sampling. -1 to feed in own prediction. use_state: True to", "samples: random samples sampled from standard guassian \"\"\" with slim.arg_scope([slim.conv2d],", "None, None # Latent tower latent_loss = 0.0 if FLAGS.stochastic_model:", "robot states and images. gen_states, gen_images = [], [] current_state", "how TF queues work. images = [tf.identity(image) for image in", "tf.identity(latent), lambda: latent_mean + tf.exp(latent_std / 2.0) * latent) with", "the distribution. Returns: the KL loss. \"\"\" return -.5 *", "# both 16x16 enc5 = slim.layers.conv2d_transpose( hidden6, hidden6.get_shape()[3], 3, stride=2,", "untied conv kernels. enc7 = slim.layers.conv2d_transpose( enc6, DNA_KERN_SIZE**2, 1, stride=1,", "iteration (for sched. sampling) k: constant used for scheduled sampling.", "latent_mean, latent_std, latent_loss, samples def construct_model(images, actions=None, states=None, iter_num=-1.0, k=-1,", "std) conditioned on the entire video. This latent variable will", "num_masks + 1]) mask_list = tf.split(axis=3, num_or_size_splits=num_masks + 1, value=masks)", "= construct_latent_tower(images) latent_mean, latent_std, latent_loss, samples = latent_tower_outputs # Main", "image. Args: prev_image: previous image to be transformed. stp_input: hidden", "used for scheduled sampling. -1 to feed in own prediction.", "+ RELU_SHIFT kernel = tf.expand_dims( kernel / tf.reduce_sum( kernel, [3],", "mu: mu parameter of the distribution. log_sigma: log(sigma) parameter of", "num_masks != 1: raise ValueError('Only one mask is supported for", "gen_images[-1] elif done_warm_start: # Scheduled sampling prev_image = scheduled_sample(image, gen_images[-1],", "img_height, img_width, color_channels = images[0].get_shape()[0:4] lstm_func = basic_conv_lstm_cell # Generated", "standard gaussian. return None, None, None, samples else: return latent_mean,", "latent_size samples = tf.random_normal( [FLAGS.sequence_length-1] + latent_mean.shape, 0, 1, dtype=tf.float32)", "should be unnecessary). if num_masks != 1: raise ValueError('Only one", "def construct_latent_tower(images): \"\"\"Builds convolutional latent tower for stochastic model. At", "lstm_state1, lstm_state2, lstm_state3, lstm_state4 = None, None, None, None lstm_state5,", "= lstm_func( hidden1, lstm_state2, lstm_size[1], scope='state2') hidden2 = tf_layers.layer_norm(hidden2, scope='layer_norm3')", "def dna_transformation(prev_image, dna_input): \"\"\"Apply dynamic neural advection to previous image.", "============================================================================== \"\"\"Model architecture for predictive model, including CDNA, DNA, and", "mean latent_std: predicted latent standard deviation latent_loss: loss of the", "the *same* image for both, ... # ... given how", "for both, ... # ... given how TF queues work.", "or more than 1 mask specified for DNA model. \"\"\"", "List of images transformed by the predicted STP parameters. \"\"\"", "\"\"\" idx = tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth)) generated_idx =", "tf_layers.layer_norm(hidden5, scope='layer_norm6') enc4 = slim.layers.conv2d_transpose( hidden5, hidden5.get_shape()[3], 3, stride=2, scope='convt1')", "* mask gen_images.append(output) current_state = slim.layers.fully_connected( state_action, int(current_state.get_shape()[1]), scope='state_pred', activation_fn=None)", "of ground-truth examples to include in batch. Returns: New batch", "reuse = bool(gen_images) done_warm_start = len(gen_images) > context_frames - 1", "hidden7, lstm_state7 = lstm_func( enc5, lstm_state7, lstm_size[6], scope='state7') # 32x32", "lstm_state1 = lstm_func( enc0, lstm_state1, lstm_size[0], scope='state1') hidden1 = tf_layers.layer_norm(hidden1,", "one, or no network option specified.') batch_size, img_height, img_width, color_channels", "num_masks]) cdna_kerns = tf.nn.relu(cdna_kerns - RELU_SHIFT) + RELU_SHIFT norm_factor =", "values=[action, current_state]) enc0 = slim.layers.conv2d( prev_image, 32, [5, 5], stride=2,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "else: # Always feed in ground_truth prev_image = image #", "scope='fc_stp') transformed += stp_transformation(prev_image, stp_input1, num_masks) elif cdna: cdna_input =", "transformed += cdna_transformation(prev_image, cdna_input, num_masks, int(color_channels)) elif dna: # Only", "predicted future image frames gen_states: predicted future states Raises: ValueError:", "as the batch dimension since the same # transformation is", "time, just standard gaussian. return None, None, None, samples else:", "largest hidden state for predicting untied conv kernels. enc7 =", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "prev_image = tf.transpose(prev_image, [3, 1, 2, 0]) # Transform image.", "tf_layers.layer_norm(hidden3, scope='layer_norm4') hidden4, lstm_state4 = lstm_func( hidden3, lstm_state4, lstm_size[3], scope='state4')", "= tf.gather(idx, tf.range(num_ground_truth, int(batch_size))) ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx) generated_examps =", "Always feed in ground_truth prev_image = image # Predicted state", "= kl_divergence(latent_mean, latent_std) latent_loss = tf.reduce_mean(divergence) if FLAGS.multi_latent: # timestep", "lstm_func( enc3, lstm_state5, lstm_size[4], scope='state5') # last 8x8 hidden5 =", "random samples sampled from standard guassian \"\"\" with slim.arg_scope([slim.conv2d], reuse=False):", "given how TF queues work. images = [tf.identity(image) for image", "sequences iter_num: tensor of the current training iteration (for sched.", "False # LSTM state sizes and states. lstm_size = np.int32(np.array([32,", "previous image to be transformed. cdna_input: hidden lyaer to be", "int(current_state.get_shape()[1]), scope='state_pred', activation_fn=None) gen_states.append(current_state) return gen_images, gen_states, latent_loss ## Utility", "lstm_func( enc4, lstm_state6, lstm_size[5], scope='state6') # 16x16 hidden6 = tf_layers.layer_norm(hidden6,", "transformation is applied to each color channel. # Treat the", "each sample. cdna_kerns = tf.transpose(cdna_kerns, [1, 2, 0, 4, 3])", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "layer, mask in zip(transformed, mask_list[1:]): output += layer * mask", "# ============================================================================== \"\"\"Model architecture for predictive model, including CDNA, DNA,", "with tf.control_dependencies([latent]): enc2 = tf.concat([enc2, latent], 3) enc3 = slim.layers.conv2d(", "batch. Returns: New batch with num_ground_truth sampled from ground_truth_x and", "## Utility functions def stp_transformation(prev_image, stp_input, num_masks): \"\"\"Apply spatial transformer", "width = int(prev_image.get_shape()[2]) # Predict kernels using linear function of", "state sequences iter_num: tensor of the current training iteration (for", "'latent_norm1'}) latent_enc2 = slim.conv2d( latent_enc1, 64, [3, 3], stride=2, scope='latent_conv2',", "Transformer Predictor (STP) cdna: True to use Convoluational Dynamic Neural", "spatial_transformer import transformer identity_params = tf.convert_to_tensor( np.array([1.0, 0.0, 0.0, 0.0,", "# depthwise_conv2d can apply a different transformation to each sample.", "(STP) cdna: True to use Convoluational Dynamic Neural Advection (CDNA)", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "ykern, 0], [-1, image_height, image_width, -1]), [3])) inputs = tf.concat(axis=3,", "of images transformed by the predicted CDNA kernels. \"\"\" batch_size", "Predictor (STP) cdna: True to use Convoluational Dynamic Neural Advection", "Rights Reserved. # # Licensed under the Apache License, Version", "+ tf.exp(iter_num / k))))) feedself = False # LSTM state", "This allows the network to also generate one image from", "enc7)] masks = slim.layers.conv2d_transpose( enc6, num_masks + 1, 1, stride=1,", "specific language governing permissions and # limitations under the License.", "the number of masks and hence the number of CDNA", "int(color_channels)) elif dna: # Only one mask is supported (more", "scope='latent_conv2', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm2'}) latent_enc3 = slim.conv2d( latent_enc2, 64, [3,", "if num_masks != 1: raise ValueError('Only one mask is supported", "0, 1, dtype=tf.float32) else: # batch_size x latent_size samples =", "truth image sequences Returns: latent_mean: predicted latent mean latent_std: predicted", "hidden layer to be used for computing STN parameters. num_masks:", "= 1e-12 # kernel size for DNA and CDNA. DNA_KERN_SIZE", "height, width, batch_size, num_masks]) transformed = tf.transpose(transformed, [3, 1, 2,", "# Transform image. transformed = tf.nn.depthwise_conv2d(prev_image, cdna_kerns, [1, 1, 1,", "transformed by the predicted CDNA kernels. \"\"\" batch_size = int(cdna_input.get_shape()[0])", "batch_size, num_ground_truth) else: # Always feed in ground_truth prev_image =", "transformed += stp_transformation(prev_image, stp_input1, num_masks) elif cdna: cdna_input = tf.reshape(hidden5,", "[1, 1, 1, 1], 'SAME') # Transpose the dimensions to", "# you may not use this file except in compliance", "[4]) return tf.reduce_sum(kernel * inputs, [3], keep_dims=False) def scheduled_sample(ground_truth_x, generated_x,", "and # limitations under the License. # ============================================================================== \"\"\"Model architecture", "an extra variable to be used for future frames prediction.", "hidden2 = tf_layers.layer_norm(hidden2, scope='layer_norm3') enc1 = slim.layers.conv2d( hidden2, hidden2.get_shape()[3], [3,", "log(sigma) parameter of the distribution. Returns: the KL loss. \"\"\"", "DNA_KERN_SIZE, batch_size, num_masks]) # Swap the batch and channel dimensions.", "scheduled sampling. -1 to feed in own prediction. use_state: True", "generated image. prev_image = gen_images[-1] elif done_warm_start: # Scheduled sampling", "in prediction num_masks: the number of different pixel motion predictions", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "normalizer_params={'scope': 'latent_std_norm'}) latent_std += FLAGS.latent_std_min divergence = kl_divergence(latent_mean, latent_std) latent_loss", "/ 2.0) * latent) with tf.control_dependencies([latent]): enc2 = tf.concat([enc2, latent],", "!= 1: raise ValueError('Only one mask is supported for DNA", "in zip(transformed, mask_list[1:]): output += layer * mask gen_images.append(output) current_state", "sequences Returns: latent_mean: predicted latent mean latent_std: predicted latent standard", "color channels in the images. Returns: List of images transformed", "stride=2, scope='conv2') hidden3, lstm_state3 = lstm_func( enc1, lstm_state3, lstm_size[2], scope='state3')", "N(0,1). Args: mu: mu parameter of the distribution. log_sigma: log(sigma)", "enc1 = slim.layers.conv2d( hidden2, hidden2.get_shape()[3], [3, 3], stride=2, scope='conv2') hidden3,", "last 8x8 hidden5 = tf_layers.layer_norm(hidden5, scope='layer_norm6') enc4 = slim.layers.conv2d_transpose( hidden5,", "in own prediction. use_state: True to include state and action", "int(state_action.get_shape()[1])]) smear = tf.tile( smear, [1, int(enc2.get_shape()[1]), int(enc2.get_shape()[2]), 1]) if", "DNA_KERN_SIZE**2, 1, stride=1, scope='convt4', activation_fn=None) else: # Using largest hidden", "are using the *same* image for both, ... # ...", "masks = slim.layers.conv2d_transpose( enc6, num_masks + 1, 1, stride=1, scope='convt7',", "samples = tf.random_normal( [FLAGS.sequence_length-1] + latent_mean.shape, 0, 1, dtype=tf.float32) else:", "generate one image from scratch, # which is useful when", "images: tensor of ground truth image sequences actions: tensor of", "predicted latent standard deviation latent_loss: loss of the latent twoer", "computing STN parameters. num_masks: number of masks and hence the", "under the Apache License, Version 2.0 (the \"License\"); # you", "transformation to each sample. cdna_kerns = tf.transpose(cdna_kerns, [1, 2, 0,", "to use when lower bounding tensors RELU_SHIFT = 1e-12 #", "1): params = slim.layers.fully_connected( stp_input, 6, scope='stp_params' + str(i), activation_fn=None)", "slim.layers.fully_connected, tf_layers.layer_norm, slim.layers.conv2d_transpose], reuse=reuse): if feedself and done_warm_start: # Feed", "image to be transformed. stp_input: hidden layer to be used", "prev_image: previous image to be transformed. stp_input: hidden layer to", "enc4, lstm_state6, lstm_size[5], scope='state6') # 16x16 hidden6 = tf_layers.layer_norm(hidden6, scope='layer_norm7')", "slim.arg_scope([slim.conv2d], reuse=False): stacked_images = tf.concat(images, 3) latent_enc1 = slim.conv2d( stacked_images,", "new image layer. enc7 = slim.layers.conv2d_transpose( enc6, color_channels, 1, stride=1,", "1, int(state_action.get_shape()[1])]) smear = tf.tile( smear, [1, int(enc2.get_shape()[1]), int(enc2.get_shape()[2]), 1])", "scope='state4') hidden4 = tf_layers.layer_norm(hidden4, scope='layer_norm5') enc2 = slim.layers.conv2d( hidden4, hidden4.get_shape()[3],", "state for predicting untied conv kernels. enc7 = slim.layers.conv2d_transpose( enc6,", "is useful when regions of the image become unoccluded. transformed", "tf_layers.layer_norm(hidden1, scope='layer_norm2') hidden2, lstm_state2 = lstm_func( hidden1, lstm_state2, lstm_size[1], scope='state2')", "hidden layer. cdna_kerns = slim.layers.fully_connected( cdna_input, DNA_KERN_SIZE * DNA_KERN_SIZE *", "variables after the first timestep. reuse = bool(gen_images) done_warm_start =", "sequences actions: tensor of action sequences states: tensor of ground", "mask specified for DNA model. \"\"\" # Each image is", "by the predicted STP parameters. \"\"\" # Only import spatial", "from N(0,1). If the multi_latent flag is on, a different", "int(prev_image.get_shape()[1]) width = int(prev_image.get_shape()[2]) # Predict kernels using linear function", "Copyright 2016 The TensorFlow Authors All Rights Reserved. # #", "tf.reduce_sum(kernel * inputs, [3], keep_dims=False) def scheduled_sample(ground_truth_x, generated_x, batch_size, num_ground_truth):", "of CDNA transformations. color_channels: the number of color channels in", "num_or_size_splits=num_masks + 1, value=masks) output = mask_list[0] * prev_image for", "= slim.conv2d( latent_enc1, 64, [3, 3], stride=2, scope='latent_conv2', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope':", "Predict kernels using linear function of last hidden layer. cdna_kerns", "Only one mask is supported (more should be unnecessary). if", "\"\"\"KL divergence of diagonal gaussian N(mu,exp(log_sigma)) and N(0,1). Args: mu:", "[3])) inputs = tf.concat(axis=3, values=inputs) # Normalize channels to 1.", "to also generate one image from scratch, # which is", "hidden4.get_shape()[3], [3, 3], stride=2, scope='conv3') # Pass in state and", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "Amount to use when lower bounding tensors RELU_SHIFT = 1e-12", "supported for DNA model.') transformed = [dna_transformation(prev_image, enc7)] masks =", "kernel = tf.expand_dims( kernel / tf.reduce_sum( kernel, [3], keep_dims=True), [4])", "*same* image for both, ... # ... given how TF", "slim.layers.conv2d_transpose( hidden6, hidden6.get_shape()[3], 3, stride=2, scope='convt2') hidden7, lstm_state7 = lstm_func(", "tf.concat(axis=3, values=inputs) # Normalize channels to 1. kernel = tf.nn.relu(dna_input", "= states[0] if k == -1: feedself = True else:", "for predicting untied conv kernels. enc7 = slim.layers.conv2d_transpose( enc6, DNA_KERN_SIZE**2,", "sizes and states. lstm_size = np.int32(np.array([32, 32, 64, 64, 128,", "lstm_state3 = lstm_func( enc1, lstm_state3, lstm_size[2], scope='state3') hidden3 = tf_layers.layer_norm(hidden3,", "context_frames - 1 with slim.arg_scope( [lstm_func, slim.layers.conv2d, slim.layers.fully_connected, tf_layers.layer_norm, slim.layers.conv2d_transpose],", "enc5 = slim.layers.conv2d_transpose( hidden6, hidden6.get_shape()[3], 3, stride=2, scope='convt2') hidden7, lstm_state7", "slim.layers.conv2d_transpose], reuse=reuse): if feedself and done_warm_start: # Feed in generated", "latent for every timestep would be generated. Args: images: tensor", "samples[timestep] if not FLAGS.inference_time: latent = tf.cond(iter_num < FLAGS.num_iterations_1st_stage, lambda:", "New batch with num_ground_truth sampled from ground_truth_x and the rest", "output += layer * mask gen_images.append(output) current_state = slim.layers.fully_connected( state_action,", "+ 1])), [int(batch_size), int(img_height), int(img_width), num_masks + 1]) mask_list =", "cdna_kerns, [1, 1, 1, 1], 'SAME') # Transpose the dimensions", "linear function of last hidden layer. cdna_kerns = slim.layers.fully_connected( cdna_input,", "predicted CDNA kernels. \"\"\" batch_size = int(cdna_input.get_shape()[0]) height = int(prev_image.get_shape()[1])", "Reshape and normalize. cdna_kerns = tf.reshape( cdna_kerns, [batch_size, DNA_KERN_SIZE, DNA_KERN_SIZE,", "RELU_SHIFT) + RELU_SHIFT norm_factor = tf.reduce_sum(cdna_kerns, [1, 2, 3], keep_dims=True)", "last hidden layer. cdna_kerns = slim.layers.fully_connected( cdna_input, DNA_KERN_SIZE * DNA_KERN_SIZE", "previous image. Args: prev_image: previous image to be transformed. cdna_input:", "At training time this tower generates a latent distribution (mean", "stride=2, scope='conv3') # Pass in state and action. smear =", "ground truth image sequences Returns: latent_mean: predicted latent mean latent_std:", "[lstm_func, slim.layers.conv2d, slim.layers.fully_connected, tf_layers.layer_norm, slim.layers.conv2d_transpose], reuse=reuse): if feedself and done_warm_start:", "examples to include in batch. Returns: New batch with num_ground_truth", "params)) return transformed def cdna_transformation(prev_image, cdna_input, num_masks, color_channels): \"\"\"Apply convolutional", "# Feed in generated image. prev_image = gen_images[-1] elif done_warm_start:", "latent_std = slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3], stride=2, scope='latent_std', normalizer_fn=tf_layers.layer_norm,", "hidden4 = tf_layers.layer_norm(hidden4, scope='layer_norm5') enc2 = slim.layers.conv2d( hidden4, hidden4.get_shape()[3], [3,", "be unnecessary). if num_masks != 1: raise ValueError('Only one mask", "raise ValueError('More than one, or no network option specified.') batch_size,", "scope='layer_norm7') # Skip connection. hidden6 = tf.concat(axis=3, values=[hidden6, enc1]) #", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "state_action = tf.concat(axis=1, values=[action, current_state]) enc0 = slim.layers.conv2d( prev_image, 32,", "[2, 2], [0, 0]]) image_height = int(prev_image.get_shape()[1]) image_width = int(prev_image.get_shape()[2])", "int(batch_size))) ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx) generated_examps = tf.gather(generated_x, generated_idx) return", "transformed = [] for i in range(num_masks - 1): params", "by the predicted CDNA kernels. \"\"\" # Construct translated images.", "tf.expand_dims( kernel / tf.reduce_sum( kernel, [3], keep_dims=True), [4]) return tf.reduce_sum(kernel", "hidden7, hidden7.get_shape()[3], 3, stride=2, scope='convt3', activation_fn=None, normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm9'}) if", "... given how TF queues work. images = [tf.identity(image) for", "\"\"\"Apply convolutional dynamic neural advection to previous image. Args: prev_image:", "Apache License, Version 2.0 (the \"License\"); # you may not", "slim.layers.conv2d, slim.layers.fully_connected, tf_layers.layer_norm, slim.layers.conv2d_transpose], reuse=reuse): if feedself and done_warm_start: #", "Scheduled sampling prev_image = scheduled_sample(image, gen_images[-1], batch_size, num_ground_truth) else: #", "> context_frames - 1 with slim.arg_scope( [lstm_func, slim.layers.conv2d, slim.layers.fully_connected, tf_layers.layer_norm,", "either express or implied. # See the License for the", "cdna: cdna_input = tf.reshape(hidden5, [int(batch_size), -1]) transformed += cdna_transformation(prev_image, cdna_input,", "tf.convert_to_tensor( np.array([1.0, 0.0, 0.0, 0.0, 1.0, 0.0], np.float32)) transformed =", "same # transformation is applied to each color channel. #", "[DNA_KERN_SIZE, DNA_KERN_SIZE, batch_size, num_masks]) # Swap the batch and channel", "inputs = [] for xkern in range(DNA_KERN_SIZE): for ykern in", "/= norm_factor # Treat the color channel dimension as the", "cdna_input: hidden lyaer to be used for computing CDNA kernels.", "variable to be used for future frames prediction. At inference", "cdna_kerns, [batch_size, DNA_KERN_SIZE, DNA_KERN_SIZE, 1, num_masks]) cdna_kerns = tf.nn.relu(cdna_kerns -", "gen_images, gen_states, latent_loss ## Utility functions def stp_transformation(prev_image, stp_input, num_masks):", "as tf import tensorflow.contrib.slim as slim from tensorflow.python.platform import flags", "def cdna_transformation(prev_image, cdna_input, num_masks, color_channels): \"\"\"Apply convolutional dynamic neural advection", "images[0].get_shape()[0:4] lstm_func = basic_conv_lstm_cell # Generated robot states and images.", "ground truth and generated data points. Args: ground_truth_x: tensor of", "+ latent_mean.shape, 0, 1, dtype=tf.float32) else: # batch_size x latent_size", "def stp_transformation(prev_image, stp_input, num_masks): \"\"\"Apply spatial transformer predictor (STP) to", "of the image become unoccluded. transformed = [tf.nn.sigmoid(enc7)] if stp:", "Args: prev_image: previous image to be transformed. dna_input: hidden lyaer", "smear]) # Setup latent if FLAGS.stochastic_model: latent = samples if", "enc2, hidden4.get_shape()[3], [1, 1], stride=1, scope='conv4') hidden5, lstm_state5 = lstm_func(", "states=None, iter_num=-1.0, k=-1, use_state=True, num_masks=10, stp=False, cdna=True, dna=False, context_frames=2): \"\"\"Build", "cdna_transformation(prev_image, cdna_input, num_masks, color_channels): \"\"\"Apply convolutional dynamic neural advection to", "actions=None, states=None, iter_num=-1.0, k=-1, use_state=True, num_masks=10, stp=False, cdna=True, dna=False, context_frames=2):", "ground-truth examples to include in batch. Returns: New batch with", "to each color channel. # Treat the batch dimension as", "timestep x batch_size x latent_size samples = tf.random_normal( [FLAGS.sequence_length-1] +", "for xkern in range(DNA_KERN_SIZE): for ykern in range(DNA_KERN_SIZE): inputs.append( tf.expand_dims(", "latent tower for stochastic model. At training time this tower", "queues work. images = [tf.identity(image) for image in images] if", "batch with num_ground_truth sampled from ground_truth_x and the rest from", "if k == -1: feedself = True else: # Scheduled", "None, samples else: return latent_mean, latent_std, latent_loss, samples def construct_model(images,", "\"\"\" # Only import spatial transformer if needed. from spatial_transformer", "channels to 1. kernel = tf.nn.relu(dna_input - RELU_SHIFT) + RELU_SHIFT", "different pixel motion predictions (and the number of masks for", "to pass in. num_ground_truth = tf.to_int32( tf.round(tf.to_float(batch_size) * (k /", "network to also generate one image from scratch, # which", "lstm_state2, lstm_size[1], scope='state2') hidden2 = tf_layers.layer_norm(hidden2, scope='layer_norm3') enc1 = slim.layers.conv2d(", "not FLAGS.inference_time: latent = tf.cond(iter_num < FLAGS.num_iterations_1st_stage, lambda: tf.identity(latent), lambda:", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "latent_std) latent_loss = tf.reduce_mean(divergence) if FLAGS.multi_latent: # timestep x batch_size", "64, 128, 64, 32])) lstm_state1, lstm_state2, lstm_state3, lstm_state4 = None,", "List of images transformed by the predicted CDNA kernels. \"\"\"", "allows the network to also generate one image from scratch,", "1])), [int(batch_size), int(img_height), int(img_width), num_masks + 1]) mask_list = tf.split(axis=3,", "and normalize. cdna_kerns = tf.reshape( cdna_kerns, [batch_size, DNA_KERN_SIZE, DNA_KERN_SIZE, 1,", "hidden state for predicting untied conv kernels. enc7 = slim.layers.conv2d_transpose(", "# Generated robot states and images. gen_states, gen_images = [],", "num_masks]) transformed = tf.transpose(transformed, [3, 1, 2, 0, 4]) transformed", "to be transformed. stp_input: hidden layer to be used for", "DNA model.') transformed = [dna_transformation(prev_image, enc7)] masks = slim.layers.conv2d_transpose( enc6,", "inputs = tf.concat(axis=3, values=inputs) # Normalize channels to 1. kernel", "16x16 enc5 = slim.layers.conv2d_transpose( hidden6, hidden6.get_shape()[3], 3, stride=2, scope='convt2') hidden7,", "tf.reshape(transformed, [color_channels, height, width, batch_size, num_masks]) transformed = tf.transpose(transformed, [3,", "[] for xkern in range(DNA_KERN_SIZE): for ykern in range(DNA_KERN_SIZE): inputs.append(", "to each sample. cdna_kerns = tf.transpose(cdna_kerns, [1, 2, 0, 4,", "32x32 hidden7 = tf_layers.layer_norm(hidden7, scope='layer_norm8') # Skip connection. hidden7 =", "transformed def cdna_transformation(prev_image, cdna_input, num_masks, color_channels): \"\"\"Apply convolutional dynamic neural", "stride=2, scope='convt1') hidden6, lstm_state6 = lstm_func( enc4, lstm_state6, lstm_size[5], scope='state6')", "of generated data points. batch_size: batch size num_ground_truth: number of", "include state and action in prediction num_masks: the number of", "+ log_sigma - tf.square(mu) - tf.exp(log_sigma), axis=1) def construct_latent_tower(images): \"\"\"Builds", "FLAGS.latent_channels, [3, 3], stride=2, activation_fn=None, scope='latent_mean', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm_mean'}) latent_std", "a different latent for every timestep would be generated. Args:", "translated images. prev_image_pad = tf.pad(prev_image, [[0, 0], [2, 2], [2,", "stp_input: hidden layer to be used for computing STN parameters.", "num_masks, color_channels): \"\"\"Apply convolutional dynamic neural advection to previous image.", "as the channel dimension so that # depthwise_conv2d can apply", "color_channels = images[0].get_shape()[0:4] lstm_func = basic_conv_lstm_cell # Generated robot states", "True to use Spatial Transformer Predictor (STP) cdna: True to", "normalizer_params={'scope': 'layer_norm9'}) if dna: # Using largest hidden state for", "lstm_state6, lstm_size[5], scope='state6') # 16x16 hidden6 = tf_layers.layer_norm(hidden6, scope='layer_norm7') #", "states[0] if k == -1: feedself = True else: #", "predicted STP parameters. \"\"\" # Only import spatial transformer if", "dna_input): \"\"\"Apply dynamic neural advection to previous image. Args: prev_image:", "tf.reduce_sum(1. + log_sigma - tf.square(mu) - tf.exp(log_sigma), axis=1) def construct_latent_tower(images):", "Authors All Rights Reserved. # # Licensed under the Apache", "lambda: latent_mean + tf.exp(latent_std / 2.0) * latent) with tf.control_dependencies([latent]):", "tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth)) generated_idx = tf.gather(idx, tf.range(num_ground_truth, int(batch_size)))", "tower for image, action in zip(images[:-1], actions[:-1]): # Reuse variables", "pixel motion predictions (and the number of masks for each", "scope='state1') hidden1 = tf_layers.layer_norm(hidden1, scope='layer_norm2') hidden2, lstm_state2 = lstm_func( hidden1,", "use Dynamic Neural Advection (DNA) context_frames: number of ground truth", "-1: feedself = True else: # Scheduled sampling: # Calculate", "STP, CDNA, or DNA. Args: images: tensor of ground truth", "return -.5 * tf.reduce_sum(1. + log_sigma - tf.square(mu) - tf.exp(log_sigma),", "num_masks: the number of masks and hence the number of", "use this file except in compliance with the License. #", "hidden3, lstm_state3 = lstm_func( enc1, lstm_state3, lstm_size[2], scope='state3') hidden3 =", "of masks and hence the number of STP transformations. Returns:", "predicted latent mean latent_std: predicted latent standard deviation latent_loss: loss", "stp=False, cdna=True, dna=False, context_frames=2): \"\"\"Build convolutional lstm video predictor using", "use_state: True to include state and action in prediction num_masks:", "image_height = int(prev_image.get_shape()[1]) image_width = int(prev_image.get_shape()[2]) inputs = [] for", "model.') transformed = [dna_transformation(prev_image, enc7)] masks = slim.layers.conv2d_transpose( enc6, num_masks", "tensor of generated data points. batch_size: batch size num_ground_truth: number", "= tf_layers.layer_norm(hidden6, scope='layer_norm7') # Skip connection. hidden6 = tf.concat(axis=3, values=[hidden6,", "the number of different pixel motion predictions (and the number", "connection. hidden6 = tf.concat(axis=3, values=[hidden6, enc1]) # both 16x16 enc5", "= [tf.nn.sigmoid(enc7)] if stp: stp_input0 = tf.reshape(hidden5, [int(batch_size), -1]) stp_input1", "truth state sequences iter_num: tensor of the current training iteration", "latent_tower_outputs # Main tower for image, action in zip(images[:-1], actions[:-1]):", "3], stride=2, scope='latent_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm1'}) latent_enc2 = slim.conv2d( latent_enc1,", "slim.layers.conv2d( enc2, hidden4.get_shape()[3], [1, 1], stride=1, scope='conv4') hidden5, lstm_state5 =", "= scheduled_sample(image, gen_images[-1], batch_size, num_ground_truth) else: # Always feed in", "= len(gen_images) > context_frames - 1 with slim.arg_scope( [lstm_func, slim.layers.conv2d,", "cdna_transformation(prev_image, cdna_input, num_masks, int(color_channels)) elif dna: # Only one mask", "the image become unoccluded. transformed = [tf.nn.sigmoid(enc7)] if stp: stp_input0", "= tf.concat(axis=3, values=[hidden7, enc0]) # both 32x32 enc6 = slim.layers.conv2d_transpose(", "to be used for computing CDNA kernels. num_masks: the number", "+ 1, 1, stride=1, scope='convt7', activation_fn=None) masks = tf.reshape( tf.nn.softmax(tf.reshape(masks,", "Returns: the KL loss. \"\"\" return -.5 * tf.reduce_sum(1. +", "\"\"\" with slim.arg_scope([slim.conv2d], reuse=False): stacked_images = tf.concat(images, 3) latent_enc1 =", "0.0], np.float32)) transformed = [] for i in range(num_masks -", "slim.layers.fully_connected( cdna_input, DNA_KERN_SIZE * DNA_KERN_SIZE * num_masks, scope='cdna_params', activation_fn=None) #", "option specified.') batch_size, img_height, img_width, color_channels = images[0].get_shape()[0:4] lstm_func =", "needed. from spatial_transformer import transformer identity_params = tf.convert_to_tensor( np.array([1.0, 0.0,", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "True to use Convoluational Dynamic Neural Advection (CDNA) dna: True", "enc0, lstm_state1, lstm_size[0], scope='state1') hidden1 = tf_layers.layer_norm(hidden1, scope='layer_norm2') hidden2, lstm_state2", "tf.reduce_mean(divergence) if FLAGS.multi_latent: # timestep x batch_size x latent_size samples", "than one, or no network option specified.') batch_size, img_height, img_width,", "def construct_model(images, actions=None, states=None, iter_num=-1.0, k=-1, use_state=True, num_masks=10, stp=False, cdna=True,", "1: raise ValueError('Only one mask is supported for DNA model.')", "= slim.conv2d( stacked_images, 32, [3, 3], stride=2, scope='latent_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope':", "CDNA kernels. \"\"\" # Construct translated images. prev_image_pad = tf.pad(prev_image,", "sampling prev_image = scheduled_sample(image, gen_images[-1], batch_size, num_ground_truth) else: # Always", "enc6 = slim.layers.conv2d_transpose( hidden7, hidden7.get_shape()[3], 3, stride=2, scope='convt3', activation_fn=None, normalizer_fn=tf_layers.layer_norm,", "parameter of the distribution. Returns: the KL loss. \"\"\" return", "np.float32)) transformed = [] for i in range(num_masks - 1):", "'latent_norm2'}) latent_enc3 = slim.conv2d( latent_enc2, 64, [3, 3], stride=1, scope='latent_conv3',", "dna != 1: raise ValueError('More than one, or no network", "# Predicted state is always fed back in state_action =", "= tf_layers.layer_norm(hidden7, scope='layer_norm8') # Skip connection. hidden7 = tf.concat(axis=3, values=[hidden7,", "for DNA model. \"\"\" # Each image is being used", "Convoluational Dynamic Neural Advection (CDNA) dna: True to use Dynamic", "hidden1, lstm_state1 = lstm_func( enc0, lstm_state1, lstm_size[0], scope='state1') hidden1 =", "use when lower bounding tensors RELU_SHIFT = 1e-12 # kernel", "else: # batch_size x latent_size samples = tf.random_normal(latent_mean.shape, 0, 1,", "used for computing DNA transformation. Returns: List of images transformed", "stp: stp_input0 = tf.reshape(hidden5, [int(batch_size), -1]) stp_input1 = slim.layers.fully_connected( stp_input0,", "images: tensor of ground truth image sequences Returns: latent_mean: predicted", "Normalize channels to 1. kernel = tf.nn.relu(dna_input - RELU_SHIFT) +", "= tf.pad(prev_image, [[0, 0], [2, 2], [2, 2], [0, 0]])", "lstm_func( enc0, lstm_state1, lstm_size[0], scope='state1') hidden1 = tf_layers.layer_norm(hidden1, scope='layer_norm2') hidden2,", "2.0) * latent) with tf.control_dependencies([latent]): enc2 = tf.concat([enc2, latent], 3)", "tf.reshape( cdna_kerns, [batch_size, DNA_KERN_SIZE, DNA_KERN_SIZE, 1, num_masks]) cdna_kerns = tf.nn.relu(cdna_kerns", "the number of STP transformations. Returns: List of images transformed", "1, 1, stride=1, scope='convt7', activation_fn=None) masks = tf.reshape( tf.nn.softmax(tf.reshape(masks, [-1,", "norm_factor # Treat the color channel dimension as the batch", "batch_size: batch size num_ground_truth: number of ground-truth examples to include", "Generated robot states and images. gen_states, gen_images = [], []", "for future frames prediction. At inference time, the tower is", "2, 3], keep_dims=True) cdna_kerns /= norm_factor # Treat the color", "normalizer_params={'scope': 'latent_norm3'}) latent_mean = slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3], stride=2,", "If the multi_latent flag is on, a different latent for", "network option specified.') batch_size, img_height, img_width, color_channels = images[0].get_shape()[0:4] lstm_func", "each color channel. # Treat the batch dimension as the", "transformation. Returns: List of images transformed by the predicted CDNA", "frames gen_states: predicted future states Raises: ValueError: if more than", "= slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3], stride=2, activation_fn=None, scope='latent_mean', normalizer_fn=tf_layers.layer_norm,", "actions[:-1]): # Reuse variables after the first timestep. reuse =", "= samples[timestep] if not FLAGS.inference_time: latent = tf.cond(iter_num < FLAGS.num_iterations_1st_stage,", "hidden1, lstm_state2, lstm_size[1], scope='state2') hidden2 = tf_layers.layer_norm(hidden2, scope='layer_norm3') enc1 =", "with the License. # You may obtain a copy of", "Using largest hidden state for predicting a new image layer.", "and action in prediction num_masks: the number of different pixel", "= slim.layers.conv2d( hidden2, hidden2.get_shape()[3], [3, 3], stride=2, scope='conv2') hidden3, lstm_state3", "tf.range(num_ground_truth)) generated_idx = tf.gather(idx, tf.range(num_ground_truth, int(batch_size))) ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx)", "of images transformed by the predicted CDNA kernels. \"\"\" #", "one network option specified or more than 1 mask specified", "values=[hidden6, enc1]) # both 16x16 enc5 = slim.layers.conv2d_transpose( hidden6, hidden6.get_shape()[3],", "= tf_layers.layer_norm(hidden1, scope='layer_norm2') hidden2, lstm_state2 = lstm_func( hidden1, lstm_state2, lstm_size[1],", "including CDNA, DNA, and STP.\"\"\" import numpy as np import", "the rest from generated_x. \"\"\" idx = tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx =", "neural advection to previous image. Args: prev_image: previous image to", "width, batch_size, num_masks]) transformed = tf.transpose(transformed, [3, 1, 2, 0,", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "log_sigma: log(sigma) parameter of the distribution. Returns: the KL loss.", "mu parameter of the distribution. log_sigma: log(sigma) parameter of the", "= lstm_func( enc4, lstm_state6, lstm_size[5], scope='state6') # 16x16 hidden6 =", "data points. batch_size: batch size num_ground_truth: number of ground-truth examples", "scope='conv4') hidden5, lstm_state5 = lstm_func( enc3, lstm_state5, lstm_size[4], scope='state5') #", "and channel dimensions. prev_image = tf.transpose(prev_image, [3, 1, 2, 0])", "cdna=True, dna=False, context_frames=2): \"\"\"Build convolutional lstm video predictor using STP,", "size num_ground_truth: number of ground-truth examples to include in batch.", "images = [tf.identity(image) for image in images] if stp +", "construct_latent_tower(images) latent_mean, latent_std, latent_loss, samples = latent_tower_outputs # Main tower", "= tf.concat([enc2, latent], 3) enc3 = slim.layers.conv2d( enc2, hidden4.get_shape()[3], [1,", "mask is supported for DNA model.') transformed = [dna_transformation(prev_image, enc7)]", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "mask_list = tf.split(axis=3, num_or_size_splits=num_masks + 1, value=masks) output = mask_list[0]", "done_warm_start: # Feed in generated image. prev_image = gen_images[-1] elif", "[tf.nn.sigmoid(enc7)] if stp: stp_input0 = tf.reshape(hidden5, [int(batch_size), -1]) stp_input1 =", "hidden4, lstm_state4 = lstm_func( hidden3, lstm_state4, lstm_size[3], scope='state4') hidden4 =", "and generated data points. Args: ground_truth_x: tensor of ground-truth data", "in. num_ground_truth = tf.to_int32( tf.round(tf.to_float(batch_size) * (k / (k +", "be fed to the main tower as an extra variable", "apply a different transformation to each sample. cdna_kerns = tf.transpose(cdna_kerns,", "CONDITIONS OF ANY KIND, either express or implied. # See", "[], [] current_state = states[0] if k == -1: feedself", "= tf.to_int32( tf.round(tf.to_float(batch_size) * (k / (k + tf.exp(iter_num /", "image is being used twice, in latent tower and main", "prev_image: previous image to be transformed. dna_input: hidden lyaer to", "computing CDNA kernels. num_masks: the number of masks and hence", "= tf.concat(axis=3, values=inputs) # Normalize channels to 1. kernel =", "= tf.reshape(cdna_kerns, [DNA_KERN_SIZE, DNA_KERN_SIZE, batch_size, num_masks]) # Swap the batch", "if FLAGS.stochastic_model: latent_tower_outputs = construct_latent_tower(images) latent_mean, latent_std, latent_loss, samples =", "STP transformations. Returns: List of images transformed by the predicted", "used for computing CDNA kernels. num_masks: the number of masks", "0], [2, 2], [2, 2], [0, 0]]) image_height = int(prev_image.get_shape()[1])", "predictions Returns: gen_images: predicted future image frames gen_states: predicted future", "cdna_kerns = tf.nn.relu(cdna_kerns - RELU_SHIFT) + RELU_SHIFT norm_factor = tf.reduce_sum(cdna_kerns,", "tf.nn.relu(cdna_kerns - RELU_SHIFT) + RELU_SHIFT norm_factor = tf.reduce_sum(cdna_kerns, [1, 2,", "scope='cdna_params', activation_fn=None) # Reshape and normalize. cdna_kerns = tf.reshape( cdna_kerns,", "is applied to each color channel. # Treat the batch", "in generated image. prev_image = gen_images[-1] elif done_warm_start: # Scheduled", "num_ground_truth sampled from ground_truth_x and the rest from generated_x. \"\"\"", "latent distribution (mean and std) conditioned on the entire video.", "32, 64, 64, 128, 64, 32])) lstm_state1, lstm_state2, lstm_state3, lstm_state4", "action in zip(images[:-1], actions[:-1]): # Reuse variables after the first", "Construct translated images. prev_image_pad = tf.pad(prev_image, [[0, 0], [2, 2],", "tensorflow.contrib.layers.python import layers as tf_layers from lstm_ops import basic_conv_lstm_cell FLAGS", "current_state = slim.layers.fully_connected( state_action, int(current_state.get_shape()[1]), scope='state_pred', activation_fn=None) gen_states.append(current_state) return gen_images,", "latent_loss, samples def construct_model(images, actions=None, states=None, iter_num=-1.0, k=-1, use_state=True, num_masks=10,", "from lstm_ops import basic_conv_lstm_cell FLAGS = flags.FLAGS # Amount to", "hidden4, hidden4.get_shape()[3], [3, 3], stride=2, scope='conv3') # Pass in state", "4, 3]) cdna_kerns = tf.reshape(cdna_kerns, [DNA_KERN_SIZE, DNA_KERN_SIZE, batch_size, num_masks]) #", "scope='layer_norm8') # Skip connection. hidden7 = tf.concat(axis=3, values=[hidden7, enc0]) #", "no network option specified.') batch_size, img_height, img_width, color_channels = images[0].get_shape()[0:4]", "image to be transformed. cdna_input: hidden lyaer to be used", "CDNA. DNA_KERN_SIZE = 5 def kl_divergence(mu, log_sigma): \"\"\"KL divergence of", "tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.python.platform import", "dtype=tf.float32) else: # batch_size x latent_size samples = tf.random_normal(latent_mean.shape, 0,", "1: raise ValueError('More than one, or no network option specified.')", "[int(batch_size), 1, 1, int(state_action.get_shape()[1])]) smear = tf.tile( smear, [1, int(enc2.get_shape()[1]),", "zip(images[:-1], actions[:-1]): # Reuse variables after the first timestep. reuse", "hidden state for predicting a new image layer. enc7 =", "hidden7 = tf_layers.layer_norm(hidden7, scope='layer_norm8') # Skip connection. hidden7 = tf.concat(axis=3,", "return tf.reduce_sum(kernel * inputs, [3], keep_dims=False) def scheduled_sample(ground_truth_x, generated_x, batch_size,", "belong. transformed = tf.reshape(transformed, [color_channels, height, width, batch_size, num_masks]) transformed", "in latent tower and main tower. # This is to", "bool(gen_images) done_warm_start = len(gen_images) > context_frames - 1 with slim.arg_scope(", "batch_size = int(cdna_input.get_shape()[0]) height = int(prev_image.get_shape()[1]) width = int(prev_image.get_shape()[2]) #", "first timestep. reuse = bool(gen_images) done_warm_start = len(gen_images) > context_frames", "= int(prev_image.get_shape()[2]) inputs = [] for xkern in range(DNA_KERN_SIZE): for", "tf.transpose(cdna_kerns, [1, 2, 0, 4, 3]) cdna_kerns = tf.reshape(cdna_kerns, [DNA_KERN_SIZE,", "0.0, 1.0, 0.0], np.float32)) transformed = [] for i in", "unnecessary). if num_masks != 1: raise ValueError('Only one mask is", "3, stride=2, scope='convt1') hidden6, lstm_state6 = lstm_func( enc4, lstm_state6, lstm_size[5],", "tf.round(tf.to_float(batch_size) * (k / (k + tf.exp(iter_num / k))))) feedself", "tf.concat(axis=1, values=[action, current_state]) enc0 = slim.layers.conv2d( prev_image, 32, [5, 5],", "for ykern in range(DNA_KERN_SIZE): inputs.append( tf.expand_dims( tf.slice(prev_image_pad, [0, xkern, ykern,", "scope='convt4', activation_fn=None) else: # Using largest hidden state for predicting", "be transformed. stp_input: hidden layer to be used for computing", "# Skip connection. hidden7 = tf.concat(axis=3, values=[hidden7, enc0]) # both", "dimension so that # depthwise_conv2d can apply a different transformation", "= tf.reshape( tf.nn.softmax(tf.reshape(masks, [-1, num_masks + 1])), [int(batch_size), int(img_height), int(img_width),", "or no network option specified.') batch_size, img_height, img_width, color_channels =", "masks and hence the number of CDNA transformations. color_channels: the", "for stochastic model. At training time this tower generates a", "images transformed by the predicted CDNA kernels. \"\"\" # Construct", "None, None, None # Latent tower latent_loss = 0.0 if", "stride=1, scope='convt4', activation_fn=None) # This allows the network to also", "xkern, ykern, 0], [-1, image_height, image_width, -1]), [3])) inputs =", "img_width, color_channels = images[0].get_shape()[0:4] lstm_func = basic_conv_lstm_cell # Generated robot", "The TensorFlow Authors All Rights Reserved. # # Licensed under", "for predicting a new image layer. enc7 = slim.layers.conv2d_transpose( enc6,", "tensor of ground truth state sequences iter_num: tensor of the", "CDNA, or DNA. Args: images: tensor of ground truth image", "standard deviation latent_loss: loss of the latent twoer samples: random", "iter_num=-1.0, k=-1, use_state=True, num_masks=10, stp=False, cdna=True, dna=False, context_frames=2): \"\"\"Build convolutional", "tower as an extra variable to be used for future", "dna_input: hidden lyaer to be used for computing DNA transformation.", "tensorflow.contrib.slim as slim from tensorflow.python.platform import flags from tensorflow.contrib.layers.python import", "inference time, just standard gaussian. return None, None, None, samples", "True to include state and action in prediction num_masks: the", "tf.concat([enc2, latent], 3) enc3 = slim.layers.conv2d( enc2, hidden4.get_shape()[3], [1, 1],", "is supported for DNA model.') transformed = [dna_transformation(prev_image, enc7)] masks", "tensor of ground truth image sequences Returns: latent_mean: predicted latent", "axis=-1) return transformed def dna_transformation(prev_image, dna_input): \"\"\"Apply dynamic neural advection", "stp_input0, 100, scope='fc_stp') transformed += stp_transformation(prev_image, stp_input1, num_masks) elif cdna:", "generated data points. batch_size: batch size num_ground_truth: number of ground-truth", "lstm_state3, lstm_size[2], scope='state3') hidden3 = tf_layers.layer_norm(hidden3, scope='layer_norm4') hidden4, lstm_state4 =", "1e-12 # kernel size for DNA and CDNA. DNA_KERN_SIZE =", "License. # ============================================================================== \"\"\"Model architecture for predictive model, including CDNA,", "training time this tower generates a latent distribution (mean and", "# kernel size for DNA and CDNA. DNA_KERN_SIZE = 5", "= tf.nn.relu(dna_input - RELU_SHIFT) + RELU_SHIFT kernel = tf.expand_dims( kernel", "[3, 3], stride=2, scope='latent_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm1'}) latent_enc2 = slim.conv2d(", "transformed. cdna_input: hidden lyaer to be used for computing CDNA", "x batch_size x latent_size samples = tf.random_normal( [FLAGS.sequence_length-1] + latent_mean.shape,", "stride=2, scope='scale1_conv1', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm1'}) hidden1, lstm_state1 = lstm_func( enc0,", "if use_state: enc2 = tf.concat(axis=3, values=[enc2, smear]) # Setup latent", "= tf.nn.relu(cdna_kerns - RELU_SHIFT) + RELU_SHIFT norm_factor = tf.reduce_sum(cdna_kerns, [1,", "latents sampled from N(0,1). If the multi_latent flag is on,", "gen_images: predicted future image frames gen_states: predicted future states Raises:", "training iteration (for sched. sampling) k: constant used for scheduled", "state and action in prediction num_masks: the number of different", "for each of those predictions) stp: True to use Spatial", "number of masks and hence the number of CDNA transformations.", "layer to be used for computing STN parameters. num_masks: number", "to be transformed. cdna_input: hidden lyaer to be used for", "CDNA kernels. num_masks: the number of masks and hence the", "= slim.layers.conv2d_transpose( enc6, color_channels, 1, stride=1, scope='convt4', activation_fn=None) # This", "= tf.gather(idx, tf.range(num_ground_truth)) generated_idx = tf.gather(idx, tf.range(num_ground_truth, int(batch_size))) ground_truth_examps =", "tf.concat(images, 3) latent_enc1 = slim.conv2d( stacked_images, 32, [3, 3], stride=2,", "= image # Predicted state is always fed back in", "+ cdna + dna != 1: raise ValueError('More than one,", "tf.nn.softmax(tf.reshape(masks, [-1, num_masks + 1])), [int(batch_size), int(img_height), int(img_width), num_masks +", "5 def kl_divergence(mu, log_sigma): \"\"\"KL divergence of diagonal gaussian N(mu,exp(log_sigma))", "Only import spatial transformer if needed. from spatial_transformer import transformer", "more than 1 mask specified for DNA model. \"\"\" #", "and images. gen_states, gen_images = [], [] current_state = states[0]", "tf.slice(prev_image_pad, [0, xkern, ykern, 0], [-1, image_height, image_width, -1]), [3]))", "latent_std: predicted latent standard deviation latent_loss: loss of the latent", "truth image sequences actions: tensor of action sequences states: tensor", "np.array([1.0, 0.0, 0.0, 0.0, 1.0, 0.0], np.float32)) transformed = []", "[-1, num_masks + 1])), [int(batch_size), int(img_height), int(img_width), num_masks + 1])", "batch_size, num_masks]) transformed = tf.transpose(transformed, [3, 1, 2, 0, 4])", "timestep would be generated. Args: images: tensor of ground truth", "tf.concat(axis=3, values=[hidden7, enc0]) # both 32x32 enc6 = slim.layers.conv2d_transpose( hidden7,", "i in range(num_masks - 1): params = slim.layers.fully_connected( stp_input, 6,", "previous image. Args: prev_image: previous image to be transformed. stp_input:", "points. Args: ground_truth_x: tensor of ground-truth data points. generated_x: tensor", "image sequences Returns: latent_mean: predicted latent mean latent_std: predicted latent", "0]]) image_height = int(prev_image.get_shape()[1]) image_width = int(prev_image.get_shape()[2]) inputs = []", "the predicted STP parameters. \"\"\" # Only import spatial transformer", "scope='state2') hidden2 = tf_layers.layer_norm(hidden2, scope='layer_norm3') enc1 = slim.layers.conv2d( hidden2, hidden2.get_shape()[3],", "'latent_norm_mean'}) latent_std = slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3], stride=2, scope='latent_std',", "tower. # This is to make sure we are using", "0, 4]) transformed = tf.unstack(transformed, axis=-1) return transformed def dna_transformation(prev_image,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "layers as tf_layers from lstm_ops import basic_conv_lstm_cell FLAGS = flags.FLAGS", "This latent variable will be fed to the main tower", "prediction. use_state: True to include state and action in prediction", "as an extra variable to be used for future frames", "= int(cdna_input.get_shape()[0]) height = int(prev_image.get_shape()[1]) width = int(prev_image.get_shape()[2]) # Predict", "specified or more than 1 mask specified for DNA model.", "ground truth image sequences actions: tensor of action sequences states:", "int(img_height), int(img_width), num_masks + 1]) mask_list = tf.split(axis=3, num_or_size_splits=num_masks +", "latent_enc1, 64, [3, 3], stride=2, scope='latent_conv2', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm2'}) latent_enc3", "elif dna: # Only one mask is supported (more should", "prediction. At inference time, the tower is disabled and only", "normalizer_params={'scope': 'latent_norm2'}) latent_enc3 = slim.conv2d( latent_enc2, 64, [3, 3], stride=1,", "stride=1, scope='latent_conv3', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm3'}) latent_mean = slim.conv2d( latent_enc3, FLAGS.latent_channels,", "is to make sure we are using the *same* image", "color_channels, 1, stride=1, scope='convt4', activation_fn=None) # This allows the network", "generated data points. Args: ground_truth_x: tensor of ground-truth data points.", "latent_enc3 = slim.conv2d( latent_enc2, 64, [3, 3], stride=1, scope='latent_conv3', normalizer_fn=tf_layers.layer_norm,", "use Convoluational Dynamic Neural Advection (CDNA) dna: True to use", "we are using the *same* image for both, ... #", "activation_fn=None) # Reshape and normalize. cdna_kerns = tf.reshape( cdna_kerns, [batch_size,", "= int(prev_image.get_shape()[1]) width = int(prev_image.get_shape()[2]) # Predict kernels using linear", "tf.expand_dims( tf.slice(prev_image_pad, [0, xkern, ykern, 0], [-1, image_height, image_width, -1]),", "the number of CDNA transformations. color_channels: the number of color", "in before feeding in own predictions Returns: gen_images: predicted future", "video predictor using STP, CDNA, or DNA. Args: images: tensor", "under the License. # ============================================================================== \"\"\"Model architecture for predictive model,", "k))))) feedself = False # LSTM state sizes and states.", "scratch, # which is useful when regions of the image", "Version 2.0 (the \"License\"); # you may not use this", "normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_std_norm'}) latent_std += FLAGS.latent_std_min divergence = kl_divergence(latent_mean, latent_std)", "return transformed def cdna_transformation(prev_image, cdna_input, num_masks, color_channels): \"\"\"Apply convolutional dynamic", "image. Args: prev_image: previous image to be transformed. dna_input: hidden", "scope='state5') # last 8x8 hidden5 = tf_layers.layer_norm(hidden5, scope='layer_norm6') enc4 =", "batch_size, num_ground_truth): \"\"\"Sample batch with specified mix of ground truth", "[3, 1, 2, 0, 4]) transformed = tf.unstack(transformed, axis=-1) return", "None, None, None lstm_state5, lstm_state6, lstm_state7 = None, None, None", "x latent_size samples = tf.random_normal(latent_mean.shape, 0, 1, dtype=tf.float32) if FLAGS.inference_time:", "different latent for every timestep would be generated. Args: images:", "tf.concat(axis=3, values=[hidden6, enc1]) # both 16x16 enc5 = slim.layers.conv2d_transpose( hidden6,", "image_width = int(prev_image.get_shape()[2]) inputs = [] for xkern in range(DNA_KERN_SIZE):", "Transform image. transformed = tf.nn.depthwise_conv2d(prev_image, cdna_kerns, [1, 1, 1, 1],", "sampled from N(0,1). If the multi_latent flag is on, a", "generated_x, batch_size, num_ground_truth): \"\"\"Sample batch with specified mix of ground", "states and images. gen_states, gen_images = [], [] current_state =", "by applicable law or agreed to in writing, software #", "in range(DNA_KERN_SIZE): for ykern in range(DNA_KERN_SIZE): inputs.append( tf.expand_dims( tf.slice(prev_image_pad, [0,", "constant used for scheduled sampling. -1 to feed in own", "the color channel dimension as the batch dimension since the", "hidden2.get_shape()[3], [3, 3], stride=2, scope='conv2') hidden3, lstm_state3 = lstm_func( enc1,", "samples if FLAGS.multi_latent: latent = samples[timestep] if not FLAGS.inference_time: latent", "[int(batch_size), int(img_height), int(img_width), num_masks + 1]) mask_list = tf.split(axis=3, num_or_size_splits=num_masks", "in ground_truth prev_image = image # Predicted state is always", "of color channels in the images. Returns: List of images", "the entire video. This latent variable will be fed to", "stp_input, num_masks): \"\"\"Apply spatial transformer predictor (STP) to previous image.", "in range(num_masks - 1): params = slim.layers.fully_connected( stp_input, 6, scope='stp_params'", "action sequences states: tensor of ground truth state sequences iter_num:", "# limitations under the License. # ============================================================================== \"\"\"Model architecture for", "images] if stp + cdna + dna != 1: raise", "enc7 = slim.layers.conv2d_transpose( enc6, DNA_KERN_SIZE**2, 1, stride=1, scope='convt4', activation_fn=None) else:", "= tf.random_normal(latent_mean.shape, 0, 1, dtype=tf.float32) if FLAGS.inference_time: # No latent", "done_warm_start: # Scheduled sampling prev_image = scheduled_sample(image, gen_images[-1], batch_size, num_ground_truth)", "kernels. enc7 = slim.layers.conv2d_transpose( enc6, DNA_KERN_SIZE**2, 1, stride=1, scope='convt4', activation_fn=None)", "future frames prediction. At inference time, the tower is disabled", "/ k))))) feedself = False # LSTM state sizes and", "2, 0]) # Transform image. transformed = tf.nn.depthwise_conv2d(prev_image, cdna_kerns, [1,", "and only returns latents sampled from N(0,1). If the multi_latent", "= tf.random_normal( [FLAGS.sequence_length-1] + latent_mean.shape, 0, 1, dtype=tf.float32) else: #", "[3, 3], stride=1, scope='latent_conv3', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm3'}) latent_mean = slim.conv2d(", "hidden5, lstm_state5 = lstm_func( enc3, lstm_state5, lstm_size[4], scope='state5') # last", "time this tower generates a latent distribution (mean and std)", "ValueError('Only one mask is supported for DNA model.') transformed =", "transformed.append(transformer(prev_image, params)) return transformed def cdna_transformation(prev_image, cdna_input, num_masks, color_channels): \"\"\"Apply", "keep_dims=True), [4]) return tf.reduce_sum(kernel * inputs, [3], keep_dims=False) def scheduled_sample(ground_truth_x,", "slim.layers.conv2d_transpose( enc6, color_channels, 1, stride=1, scope='convt4', activation_fn=None) # This allows", "using the *same* image for both, ... # ... given", "= tf.random_shuffle(tf.range(int(batch_size))) ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth)) generated_idx = tf.gather(idx, tf.range(num_ground_truth,", "predicted CDNA kernels. \"\"\" # Construct translated images. prev_image_pad =", "applicable law or agreed to in writing, software # distributed", "(STP) to previous image. Args: prev_image: previous image to be", "FLAGS.latent_channels, [3, 3], stride=2, scope='latent_std', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_std_norm'}) latent_std +=", "hidden5 = tf_layers.layer_norm(hidden5, scope='layer_norm6') enc4 = slim.layers.conv2d_transpose( hidden5, hidden5.get_shape()[3], 3,", "or DNA. Args: images: tensor of ground truth image sequences", "scheduled_sample(ground_truth_x, generated_x, batch_size, num_ground_truth): \"\"\"Sample batch with specified mix of", "scope='layer_norm5') enc2 = slim.layers.conv2d( hidden4, hidden4.get_shape()[3], [3, 3], stride=2, scope='conv3')", "model. At training time this tower generates a latent distribution", "DNA_KERN_SIZE, 1, num_masks]) cdna_kerns = tf.nn.relu(cdna_kerns - RELU_SHIFT) + RELU_SHIFT", "channel dimension as the batch dimension since the same #", "0, 1, dtype=tf.float32) if FLAGS.inference_time: # No latent tower at", "* num_masks, scope='cdna_params', activation_fn=None) # Reshape and normalize. cdna_kerns =", "1, 2, 0, 4]) transformed = tf.unstack(transformed, axis=-1) return transformed", "Dynamic Neural Advection (CDNA) dna: True to use Dynamic Neural", "[3, 3], stride=2, activation_fn=None, scope='latent_mean', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm_mean'}) latent_std =", "the main tower as an extra variable to be used", "for computing DNA transformation. Returns: List of images transformed by", "1]) mask_list = tf.split(axis=3, num_or_size_splits=num_masks + 1, value=masks) output =", "mask_list[1:]): output += layer * mask gen_images.append(output) current_state = slim.layers.fully_connected(", "tf.reshape( tf.nn.softmax(tf.reshape(masks, [-1, num_masks + 1])), [int(batch_size), int(img_height), int(img_width), num_masks", "DNA, and STP.\"\"\" import numpy as np import tensorflow as", "stp_input1, num_masks) elif cdna: cdna_input = tf.reshape(hidden5, [int(batch_size), -1]) transformed", "axis=1) def construct_latent_tower(images): \"\"\"Builds convolutional latent tower for stochastic model.", "stride=2, scope='latent_std', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_std_norm'}) latent_std += FLAGS.latent_std_min divergence =", "# You may obtain a copy of the License at", "of different pixel motion predictions (and the number of masks", "activation_fn=None) gen_states.append(current_state) return gen_images, gen_states, latent_loss ## Utility functions def", "tower and main tower. # This is to make sure", "tf.cond(iter_num < FLAGS.num_iterations_1st_stage, lambda: tf.identity(latent), lambda: latent_mean + tf.exp(latent_std /", "normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm3'}) latent_mean = slim.conv2d( latent_enc3, FLAGS.latent_channels, [3, 3],", "# Calculate number of ground-truth frames to pass in. num_ground_truth", "dna_transformation(prev_image, dna_input): \"\"\"Apply dynamic neural advection to previous image. Args:", "from ground_truth_x and the rest from generated_x. \"\"\" idx =", "before feeding in own predictions Returns: gen_images: predicted future image", "[color_channels, height, width, batch_size, num_masks]) transformed = tf.transpose(transformed, [3, 1,", "number of masks for each of those predictions) stp: True", "ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx) generated_examps = tf.gather(generated_x, generated_idx) return tf.dynamic_stitch([ground_truth_idx,", "transformed = tf.transpose(transformed, [3, 1, 2, 0, 4]) transformed =", "dimension as the batch dimension since the same # transformation", "states. lstm_size = np.int32(np.array([32, 32, 64, 64, 128, 64, 32]))", "of the distribution. log_sigma: log(sigma) parameter of the distribution. Returns:", "mix of ground truth and generated data points. Args: ground_truth_x:", "None # Latent tower latent_loss = 0.0 if FLAGS.stochastic_model: latent_tower_outputs", "values=[enc2, smear]) # Setup latent if FLAGS.stochastic_model: latent = samples", "tensor of action sequences states: tensor of ground truth state", "tf.exp(iter_num / k))))) feedself = False # LSTM state sizes", "= None, None, None # Latent tower latent_loss = 0.0", "feedself = True else: # Scheduled sampling: # Calculate number", "= slim.layers.conv2d_transpose( enc6, num_masks + 1, 1, stride=1, scope='convt7', activation_fn=None)", "stp_input0 = tf.reshape(hidden5, [int(batch_size), -1]) stp_input1 = slim.layers.fully_connected( stp_input0, 100,", "make sure we are using the *same* image for both,", "1, dtype=tf.float32) else: # batch_size x latent_size samples = tf.random_normal(latent_mean.shape,", "\"License\"); # you may not use this file except in", "STP.\"\"\" import numpy as np import tensorflow as tf import", "as np import tensorflow as tf import tensorflow.contrib.slim as slim", "bounding tensors RELU_SHIFT = 1e-12 # kernel size for DNA", "number of ground-truth examples to include in batch. Returns: New", "Setup latent if FLAGS.stochastic_model: latent = samples if FLAGS.multi_latent: latent", "# batch_size x latent_size samples = tf.random_normal(latent_mean.shape, 0, 1, dtype=tf.float32)", "feed in own prediction. use_state: True to include state and", "frames prediction. At inference time, the tower is disabled and", "by the predicted CDNA kernels. \"\"\" batch_size = int(cdna_input.get_shape()[0]) height", "64, [3, 3], stride=1, scope='latent_conv3', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'latent_norm3'}) latent_mean =", "from tensorflow.python.platform import flags from tensorflow.contrib.layers.python import layers as tf_layers", "hidden6 = tf.concat(axis=3, values=[hidden6, enc1]) # both 16x16 enc5 =", "(for sched. sampling) k: constant used for scheduled sampling. -1", "1, dtype=tf.float32) if FLAGS.inference_time: # No latent tower at inference", "tf.unstack(transformed, axis=-1) return transformed def dna_transformation(prev_image, dna_input): \"\"\"Apply dynamic neural", "latent_mean + tf.exp(latent_std / 2.0) * latent) with tf.control_dependencies([latent]): enc2", "Dynamic Neural Advection (DNA) context_frames: number of ground truth frames", "num_ground_truth: number of ground-truth examples to include in batch. Returns:", "import tensorflow.contrib.slim as slim from tensorflow.python.platform import flags from tensorflow.contrib.layers.python", "import transformer identity_params = tf.convert_to_tensor( np.array([1.0, 0.0, 0.0, 0.0, 1.0,", "of ground truth state sequences iter_num: tensor of the current", "and hence the number of STP transformations. Returns: List of", "specified for DNA model. \"\"\" # Each image is being", "0.0, 0.0, 1.0, 0.0], np.float32)) transformed = [] for i", "sampled from standard guassian \"\"\" with slim.arg_scope([slim.conv2d], reuse=False): stacked_images =", "hidden7.get_shape()[3], 3, stride=2, scope='convt3', activation_fn=None, normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm9'}) if dna:", "slim.arg_scope( [lstm_func, slim.layers.conv2d, slim.layers.fully_connected, tf_layers.layer_norm, slim.layers.conv2d_transpose], reuse=reuse): if feedself and", "hence the number of STP transformations. Returns: List of images" ]
[ "- https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD # - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 # - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel def junit5_test(name,", "For more information see # - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD # - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5", "= [], deps = [], runtime_deps = [], **kwargs): \"\"\"JUnit", "kwargs.pop(arg) junit_console_args = [] if test_package: junit_console_args += [\"--select-package\", test_package]", "artifact(\"org.hamcrest:hamcrest-core\"), artifact(\"org.hamcrest:hamcrest\"), artifact(\"org.mockito:mockito-core\"), ], visibility = [\"//java:__subpackages__\"], resources = resources,", "\"\"\"JUnit runner macro\"\"\" FILTER_KWARGS = [ \"main_class\", \"use_testrunner\", \"args\", ]", "<filename>junit5/rules.bzl load(\"@rules_jvm_external//:defs.bzl\", \"artifact\") # For more information see # -", "name, srcs = srcs, use_testrunner = False, main_class = \"org.junit.platform.console.ConsoleLauncher\",", "https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 # - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel def junit5_test(name, srcs, test_package, resources =", "# - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD # - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 # - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel def", "args = junit_console_args, deps = deps + [ artifact(\"org.junit.jupiter:junit-jupiter-api\"), artifact(\"org.junit.jupiter:junit-jupiter-params\"),", "\"args\", ] for arg in FILTER_KWARGS: if arg in kwargs.keys():", "use_testrunner = False, main_class = \"org.junit.platform.console.ConsoleLauncher\", args = junit_console_args, deps", "if test_package: junit_console_args += [\"--select-package\", test_package] else: fail(\"must specify 'test_package'\")", "kwargs.keys(): kwargs.pop(arg) junit_console_args = [] if test_package: junit_console_args += [\"--select-package\",", "= [], **kwargs): \"\"\"JUnit runner macro\"\"\" FILTER_KWARGS = [ \"main_class\",", "arg in FILTER_KWARGS: if arg in kwargs.keys(): kwargs.pop(arg) junit_console_args =", "= junit_console_args, deps = deps + [ artifact(\"org.junit.jupiter:junit-jupiter-api\"), artifact(\"org.junit.jupiter:junit-jupiter-params\"), artifact(\"org.junit.jupiter:junit-jupiter-engine\"),", "for arg in FILTER_KWARGS: if arg in kwargs.keys(): kwargs.pop(arg) junit_console_args", "# - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 # - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel def junit5_test(name, srcs, test_package,", "runtime_deps = [], **kwargs): \"\"\"JUnit runner macro\"\"\" FILTER_KWARGS = [", "] for arg in FILTER_KWARGS: if arg in kwargs.keys(): kwargs.pop(arg)", "specify 'test_package'\") native.java_test( name = name, srcs = srcs, use_testrunner", "[], runtime_deps = [], **kwargs): \"\"\"JUnit runner macro\"\"\" FILTER_KWARGS =", "if arg in kwargs.keys(): kwargs.pop(arg) junit_console_args = [] if test_package:", "information see # - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD # - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 # -", "see # - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD # - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 # - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel", "resources = resources, runtime_deps = runtime_deps + [ artifact(\"org.junit.platform:junit-platform-console\"), ],", "+ [ artifact(\"org.junit.jupiter:junit-jupiter-api\"), artifact(\"org.junit.jupiter:junit-jupiter-params\"), artifact(\"org.junit.jupiter:junit-jupiter-engine\"), artifact(\"org.hamcrest:hamcrest-library\"), artifact(\"org.hamcrest:hamcrest-core\"), artifact(\"org.hamcrest:hamcrest\"), artifact(\"org.mockito:mockito-core\"), ],", "# For more information see # - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD # -", "= srcs, use_testrunner = False, main_class = \"org.junit.platform.console.ConsoleLauncher\", args =", "[], deps = [], runtime_deps = [], **kwargs): \"\"\"JUnit runner", "junit5_test(name, srcs, test_package, resources = [], deps = [], runtime_deps", "fail(\"must specify 'test_package'\") native.java_test( name = name, srcs = srcs,", "FILTER_KWARGS = [ \"main_class\", \"use_testrunner\", \"args\", ] for arg in", "artifact(\"org.hamcrest:hamcrest\"), artifact(\"org.mockito:mockito-core\"), ], visibility = [\"//java:__subpackages__\"], resources = resources, runtime_deps", "= deps + [ artifact(\"org.junit.jupiter:junit-jupiter-api\"), artifact(\"org.junit.jupiter:junit-jupiter-params\"), artifact(\"org.junit.jupiter:junit-jupiter-engine\"), artifact(\"org.hamcrest:hamcrest-library\"), artifact(\"org.hamcrest:hamcrest-core\"), artifact(\"org.hamcrest:hamcrest\"),", "\"artifact\") # For more information see # - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD #", "more information see # - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD # - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 #", "visibility = [\"//java:__subpackages__\"], resources = resources, runtime_deps = runtime_deps +", "in kwargs.keys(): kwargs.pop(arg) junit_console_args = [] if test_package: junit_console_args +=", "[\"//java:__subpackages__\"], resources = resources, runtime_deps = runtime_deps + [ artifact(\"org.junit.platform:junit-platform-console\"),", "def junit5_test(name, srcs, test_package, resources = [], deps = [],", "in FILTER_KWARGS: if arg in kwargs.keys(): kwargs.pop(arg) junit_console_args = []", "macro\"\"\" FILTER_KWARGS = [ \"main_class\", \"use_testrunner\", \"args\", ] for arg", "https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD # - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 # - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel def junit5_test(name, srcs,", "deps = deps + [ artifact(\"org.junit.jupiter:junit-jupiter-api\"), artifact(\"org.junit.jupiter:junit-jupiter-params\"), artifact(\"org.junit.jupiter:junit-jupiter-engine\"), artifact(\"org.hamcrest:hamcrest-library\"), artifact(\"org.hamcrest:hamcrest-core\"),", "[ \"main_class\", \"use_testrunner\", \"args\", ] for arg in FILTER_KWARGS: if", "arg in kwargs.keys(): kwargs.pop(arg) junit_console_args = [] if test_package: junit_console_args", "main_class = \"org.junit.platform.console.ConsoleLauncher\", args = junit_console_args, deps = deps +", "junit_console_args = [] if test_package: junit_console_args += [\"--select-package\", test_package] else:", "= [] if test_package: junit_console_args += [\"--select-package\", test_package] else: fail(\"must", "else: fail(\"must specify 'test_package'\") native.java_test( name = name, srcs =", "resources, runtime_deps = runtime_deps + [ artifact(\"org.junit.platform:junit-platform-console\"), ], **kwargs )", "artifact(\"org.junit.jupiter:junit-jupiter-params\"), artifact(\"org.junit.jupiter:junit-jupiter-engine\"), artifact(\"org.hamcrest:hamcrest-library\"), artifact(\"org.hamcrest:hamcrest-core\"), artifact(\"org.hamcrest:hamcrest\"), artifact(\"org.mockito:mockito-core\"), ], visibility = [\"//java:__subpackages__\"],", "], visibility = [\"//java:__subpackages__\"], resources = resources, runtime_deps = runtime_deps", "native.java_test( name = name, srcs = srcs, use_testrunner = False,", "= [\"//java:__subpackages__\"], resources = resources, runtime_deps = runtime_deps + [", "- https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel def junit5_test(name, srcs, test_package, resources = [], deps", "junit_console_args, deps = deps + [ artifact(\"org.junit.jupiter:junit-jupiter-api\"), artifact(\"org.junit.jupiter:junit-jupiter-params\"), artifact(\"org.junit.jupiter:junit-jupiter-engine\"), artifact(\"org.hamcrest:hamcrest-library\"),", "test_package: junit_console_args += [\"--select-package\", test_package] else: fail(\"must specify 'test_package'\") native.java_test(", "# - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel def junit5_test(name, srcs, test_package, resources = [],", "test_package, resources = [], deps = [], runtime_deps = [],", "False, main_class = \"org.junit.platform.console.ConsoleLauncher\", args = junit_console_args, deps = deps", "artifact(\"org.junit.jupiter:junit-jupiter-engine\"), artifact(\"org.hamcrest:hamcrest-library\"), artifact(\"org.hamcrest:hamcrest-core\"), artifact(\"org.hamcrest:hamcrest\"), artifact(\"org.mockito:mockito-core\"), ], visibility = [\"//java:__subpackages__\"], resources", "= [], runtime_deps = [], **kwargs): \"\"\"JUnit runner macro\"\"\" FILTER_KWARGS", "srcs = srcs, use_testrunner = False, main_class = \"org.junit.platform.console.ConsoleLauncher\", args", "[], **kwargs): \"\"\"JUnit runner macro\"\"\" FILTER_KWARGS = [ \"main_class\", \"use_testrunner\",", "= resources, runtime_deps = runtime_deps + [ artifact(\"org.junit.platform:junit-platform-console\"), ], **kwargs", "junit_console_args += [\"--select-package\", test_package] else: fail(\"must specify 'test_package'\") native.java_test( name", "FILTER_KWARGS: if arg in kwargs.keys(): kwargs.pop(arg) junit_console_args = [] if", "\"org.junit.platform.console.ConsoleLauncher\", args = junit_console_args, deps = deps + [ artifact(\"org.junit.jupiter:junit-jupiter-api\"),", "= name, srcs = srcs, use_testrunner = False, main_class =", "artifact(\"org.junit.jupiter:junit-jupiter-api\"), artifact(\"org.junit.jupiter:junit-jupiter-params\"), artifact(\"org.junit.jupiter:junit-jupiter-engine\"), artifact(\"org.hamcrest:hamcrest-library\"), artifact(\"org.hamcrest:hamcrest-core\"), artifact(\"org.hamcrest:hamcrest\"), artifact(\"org.mockito:mockito-core\"), ], visibility =", "deps = [], runtime_deps = [], **kwargs): \"\"\"JUnit runner macro\"\"\"", "name = name, srcs = srcs, use_testrunner = False, main_class", "\"main_class\", \"use_testrunner\", \"args\", ] for arg in FILTER_KWARGS: if arg", "[\"--select-package\", test_package] else: fail(\"must specify 'test_package'\") native.java_test( name = name,", "**kwargs): \"\"\"JUnit runner macro\"\"\" FILTER_KWARGS = [ \"main_class\", \"use_testrunner\", \"args\",", "artifact(\"org.hamcrest:hamcrest-library\"), artifact(\"org.hamcrest:hamcrest-core\"), artifact(\"org.hamcrest:hamcrest\"), artifact(\"org.mockito:mockito-core\"), ], visibility = [\"//java:__subpackages__\"], resources =", "\"use_testrunner\", \"args\", ] for arg in FILTER_KWARGS: if arg in", "load(\"@rules_jvm_external//:defs.bzl\", \"artifact\") # For more information see # - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD", "srcs, use_testrunner = False, main_class = \"org.junit.platform.console.ConsoleLauncher\", args = junit_console_args,", "[ artifact(\"org.junit.jupiter:junit-jupiter-api\"), artifact(\"org.junit.jupiter:junit-jupiter-params\"), artifact(\"org.junit.jupiter:junit-jupiter-engine\"), artifact(\"org.hamcrest:hamcrest-library\"), artifact(\"org.hamcrest:hamcrest-core\"), artifact(\"org.hamcrest:hamcrest\"), artifact(\"org.mockito:mockito-core\"), ], visibility", "= \"org.junit.platform.console.ConsoleLauncher\", args = junit_console_args, deps = deps + [", "[] if test_package: junit_console_args += [\"--select-package\", test_package] else: fail(\"must specify", "= False, main_class = \"org.junit.platform.console.ConsoleLauncher\", args = junit_console_args, deps =", "= [ \"main_class\", \"use_testrunner\", \"args\", ] for arg in FILTER_KWARGS:", "test_package] else: fail(\"must specify 'test_package'\") native.java_test( name = name, srcs", "runner macro\"\"\" FILTER_KWARGS = [ \"main_class\", \"use_testrunner\", \"args\", ] for", "resources = [], deps = [], runtime_deps = [], **kwargs):", "artifact(\"org.mockito:mockito-core\"), ], visibility = [\"//java:__subpackages__\"], resources = resources, runtime_deps =", "srcs, test_package, resources = [], deps = [], runtime_deps =", "'test_package'\") native.java_test( name = name, srcs = srcs, use_testrunner =", "https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel def junit5_test(name, srcs, test_package, resources = [], deps =", "deps + [ artifact(\"org.junit.jupiter:junit-jupiter-api\"), artifact(\"org.junit.jupiter:junit-jupiter-params\"), artifact(\"org.junit.jupiter:junit-jupiter-engine\"), artifact(\"org.hamcrest:hamcrest-library\"), artifact(\"org.hamcrest:hamcrest-core\"), artifact(\"org.hamcrest:hamcrest\"), artifact(\"org.mockito:mockito-core\"),", "+= [\"--select-package\", test_package] else: fail(\"must specify 'test_package'\") native.java_test( name =", "- https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 # - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel def junit5_test(name, srcs, test_package, resources" ]
[ "z class Rotation(object): \"\"\" A mock class for carla.Rotation. \"\"\"", "self.roll = roll class Vector3D(object): \"\"\" A mock class for", "def __init__(self, pitch, yaw, roll): self.pitch = pitch self.yaw =", "A mock class for carla.Location. \"\"\" def __init__(self, x, y,", "mock class for carla.Vector3D. \"\"\" def __init__(self, x, y, z):", "classes and functions provided # by Carla in our runtime", "Location(object): \"\"\" A mock class for carla.Location. \"\"\" def __init__(self,", "= roll class Vector3D(object): \"\"\" A mock class for carla.Vector3D.", "mocked versions of classes and functions provided # by Carla", "class for carla.Location. \"\"\" def __init__(self, x, y, z): self.x", "functions provided # by Carla in our runtime environment. class", "our runtime environment. class Location(object): \"\"\" A mock class for", "mock class for carla.Location. \"\"\" def __init__(self, x, y, z):", "roll): self.pitch = pitch self.yaw = yaw self.roll = roll", "for carla.Rotation. \"\"\" def __init__(self, pitch, yaw, roll): self.pitch =", "x, y, z): self.x = x self.y = y self.z", "\"\"\" A mock class for carla.Rotation. \"\"\" def __init__(self, pitch,", "pitch self.yaw = yaw self.roll = roll class Vector3D(object): \"\"\"", "yaw self.roll = roll class Vector3D(object): \"\"\" A mock class", "__init__(self, pitch, yaw, roll): self.pitch = pitch self.yaw = yaw", "= x self.y = y self.z = z class Rotation(object):", "roll class Vector3D(object): \"\"\" A mock class for carla.Vector3D. \"\"\"", "class Vector3D(object): \"\"\" A mock class for carla.Vector3D. \"\"\" def", "for carla.Vector3D. \"\"\" def __init__(self, x, y, z): self.x =", "self.pitch = pitch self.yaw = yaw self.roll = roll class", "of classes and functions provided # by Carla in our", "= z class Rotation(object): \"\"\" A mock class for carla.Rotation.", "carla.Rotation. \"\"\" def __init__(self, pitch, yaw, roll): self.pitch = pitch", "x self.y = y self.z = z class Rotation(object): \"\"\"", "Rotation(object): \"\"\" A mock class for carla.Rotation. \"\"\" def __init__(self,", "by Carla in our runtime environment. class Location(object): \"\"\" A", "carla.Vector3D. \"\"\" def __init__(self, x, y, z): self.x = x", "A mock class for carla.Rotation. \"\"\" def __init__(self, pitch, yaw,", "mock class for carla.Rotation. \"\"\" def __init__(self, pitch, yaw, roll):", "__init__(self, x, y, z): self.x = x self.y = y", "class for carla.Rotation. \"\"\" def __init__(self, pitch, yaw, roll): self.pitch", "carla.Location. \"\"\" def __init__(self, x, y, z): self.x = x", "class for carla.Vector3D. \"\"\" def __init__(self, x, y, z): self.x", "# by Carla in our runtime environment. class Location(object): \"\"\"", "provides mocked versions of classes and functions provided # by", "Vector3D(object): \"\"\" A mock class for carla.Vector3D. \"\"\" def __init__(self,", "and functions provided # by Carla in our runtime environment.", "= pitch self.yaw = yaw self.roll = roll class Vector3D(object):", "z): self.x = x self.y = y self.z = z", "self.yaw = yaw self.roll = roll class Vector3D(object): \"\"\" A", "self.y = y self.z = z class Rotation(object): \"\"\" A", "in our runtime environment. class Location(object): \"\"\" A mock class", "# This module provides mocked versions of classes and functions", "runtime environment. class Location(object): \"\"\" A mock class for carla.Location.", "self.x = x self.y = y self.z = z class", "def __init__(self, x, y, z): self.x = x self.y =", "yaw, roll): self.pitch = pitch self.yaw = yaw self.roll =", "for carla.Location. \"\"\" def __init__(self, x, y, z): self.x =", "\"\"\" A mock class for carla.Vector3D. \"\"\" def __init__(self, x,", "This module provides mocked versions of classes and functions provided", "provided # by Carla in our runtime environment. class Location(object):", "y self.z = z class Rotation(object): \"\"\" A mock class", "module provides mocked versions of classes and functions provided #", "class Location(object): \"\"\" A mock class for carla.Location. \"\"\" def", "A mock class for carla.Vector3D. \"\"\" def __init__(self, x, y,", "= y self.z = z class Rotation(object): \"\"\" A mock", "self.z = z class Rotation(object): \"\"\" A mock class for", "class Rotation(object): \"\"\" A mock class for carla.Rotation. \"\"\" def", "pitch, yaw, roll): self.pitch = pitch self.yaw = yaw self.roll", "Carla in our runtime environment. class Location(object): \"\"\" A mock", "\"\"\" def __init__(self, x, y, z): self.x = x self.y", "y, z): self.x = x self.y = y self.z =", "= yaw self.roll = roll class Vector3D(object): \"\"\" A mock", "\"\"\" A mock class for carla.Location. \"\"\" def __init__(self, x,", "\"\"\" def __init__(self, pitch, yaw, roll): self.pitch = pitch self.yaw", "versions of classes and functions provided # by Carla in", "environment. class Location(object): \"\"\" A mock class for carla.Location. \"\"\"" ]
[ "[R,G,B]] K = round(K * 0x64,1) print(f'{yellow}CMYK: {green}{C}%, {M}%, {Y}%,", "-*- coding: utf-8 -*- ee = '\\033[1m' green = '\\033[32m'", "= cyan+'-' * 0x2D print(ee+line) R,G,B = [float(X) / 0xFF", "'\\033[33m' cyan = '\\033[36m' line = cyan+'-' * 0x2D print(ee+line)", "[round(float((1-X-K)/(1-K) * 0x64),1) for X in [R,G,B]] K = round(K", "R,G,B = [float(X) / 0xFF for X in input(f'{yellow}RGB: {green}').split()]", "0xFF for X in input(f'{yellow}RGB: {green}').split()] K = 1-max(R,G,B) C,M,Y", "X in input(f'{yellow}RGB: {green}').split()] K = 1-max(R,G,B) C,M,Y = [round(float((1-X-K)/(1-K)", "0x2D print(ee+line) R,G,B = [float(X) / 0xFF for X in", "* 0x64),1) for X in [R,G,B]] K = round(K *", "K = 1-max(R,G,B) C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1) for X", "0x64),1) for X in [R,G,B]] K = round(K * 0x64,1)", "python3 # -*- coding: utf-8 -*- ee = '\\033[1m' green", "= '\\033[36m' line = cyan+'-' * 0x2D print(ee+line) R,G,B =", "/ 0xFF for X in input(f'{yellow}RGB: {green}').split()] K = 1-max(R,G,B)", "C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1) for X in [R,G,B]] K", "'\\033[1m' green = '\\033[32m' yellow = '\\033[33m' cyan = '\\033[36m'", "K = round(K * 0x64,1) print(f'{yellow}CMYK: {green}{C}%, {M}%, {Y}%, {K}%')", "yellow = '\\033[33m' cyan = '\\033[36m' line = cyan+'-' *", "= '\\033[1m' green = '\\033[32m' yellow = '\\033[33m' cyan =", "= [round(float((1-X-K)/(1-K) * 0x64),1) for X in [R,G,B]] K =", "cyan = '\\033[36m' line = cyan+'-' * 0x2D print(ee+line) R,G,B", "[float(X) / 0xFF for X in input(f'{yellow}RGB: {green}').split()] K =", "# -*- coding: utf-8 -*- ee = '\\033[1m' green =", "'\\033[32m' yellow = '\\033[33m' cyan = '\\033[36m' line = cyan+'-'", "'\\033[36m' line = cyan+'-' * 0x2D print(ee+line) R,G,B = [float(X)", "= '\\033[32m' yellow = '\\033[33m' cyan = '\\033[36m' line =", "for X in [R,G,B]] K = round(K * 0x64,1) print(f'{yellow}CMYK:", "= 1-max(R,G,B) C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1) for X in", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- ee = '\\033[1m'", "input(f'{yellow}RGB: {green}').split()] K = 1-max(R,G,B) C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1)", "for X in input(f'{yellow}RGB: {green}').split()] K = 1-max(R,G,B) C,M,Y =", "coding: utf-8 -*- ee = '\\033[1m' green = '\\033[32m' yellow", "in input(f'{yellow}RGB: {green}').split()] K = 1-max(R,G,B) C,M,Y = [round(float((1-X-K)/(1-K) *", "line = cyan+'-' * 0x2D print(ee+line) R,G,B = [float(X) /", "in [R,G,B]] K = round(K * 0x64,1) print(f'{yellow}CMYK: {green}{C}%, {M}%,", "utf-8 -*- ee = '\\033[1m' green = '\\033[32m' yellow =", "ee = '\\033[1m' green = '\\033[32m' yellow = '\\033[33m' cyan", "= [float(X) / 0xFF for X in input(f'{yellow}RGB: {green}').split()] K", "{green}').split()] K = 1-max(R,G,B) C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1) for", "1-max(R,G,B) C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1) for X in [R,G,B]]", "X in [R,G,B]] K = round(K * 0x64,1) print(f'{yellow}CMYK: {green}{C}%,", "-*- ee = '\\033[1m' green = '\\033[32m' yellow = '\\033[33m'", "= '\\033[33m' cyan = '\\033[36m' line = cyan+'-' * 0x2D", "print(ee+line) R,G,B = [float(X) / 0xFF for X in input(f'{yellow}RGB:", "* 0x2D print(ee+line) R,G,B = [float(X) / 0xFF for X", "= round(K * 0x64,1) print(f'{yellow}CMYK: {green}{C}%, {M}%, {Y}%, {K}%') print(line)", "green = '\\033[32m' yellow = '\\033[33m' cyan = '\\033[36m' line", "cyan+'-' * 0x2D print(ee+line) R,G,B = [float(X) / 0xFF for" ]
[ "reads source and creates rst files in dest with the", "= os.path.abspath(ipath) idefault = [ipath] parser.add_argument('-i', '--input', nargs='+', default=idefault, help='list", "source dirs.\\ WARNING: the output directories are emptied by default.", "for source, the last output dir\\ is used for the", "the source code. Then it runs sphinx make.\\ WARNING: this", "gadefault = ['-T', '-f', '-e', '-o'] parser.add_argument('-ga', '--gendocargs', nargs='*', default=gadefault,", "in dest with the given args. :param source: The python", "prepare_dir(directory, delete=True): \"\"\"Create apidoc dir, delete contents if delete is", "directories. gendoc is called for every\\ source dir.\\ Default is", "destination for the rst files. Can be a relative path.", "directories. if you have multiple source\\ directories, the corresponding output", "be a relative path. :type dest: str :param args: Arguments", "genparser.print_help() sys.exit(0) print 'Preparing output directories' print '='*80 for odir", "import gendoc thisdir = os.path.abspath(os.path.dirname(__file__)) def setup_argparse(): \"\"\"Sets up the", "relative path. :type dest: str :param args: Arguments for gendoc.", "not args.nodelete) print '\\nRunning gendoc' print '='*80 for i, idir", "help='list of output directories. if you have multiple source\\ directories,", "[opath] parser.add_argument('-o', '--output', nargs='+', default=odefault, help='list of output directories. if", "args.append(dest) args.append(source) print 'Running gendoc.main with: %s' % args gendoc.main(args)", "#!/usr/bin/env python \"\"\"Builds the documentaion. First it runs gendoc to", "args: Arguments for gendoc. See gendoc for more information. :type", "can use relative paths here :type directory: str :param delete:", "the last output dir\\ is used for the remaining source", "exit') return parser def prepare_dir(directory, delete=True): \"\"\"Create apidoc dir, delete", "i, idir in enumerate(args.input): if i >= len(args.output): odir =", "gendoc which reads source and creates rst files in dest", "args.insert(0, 'gendoc.py') args.append(dest) args.append(source) print 'Running gendoc.main with: %s' %", "nargs='+', default=idefault, help='list of input directories. gendoc is called for", "up the argument parser and returns it :returns: the parser", "make.\\ WARNING: this will delete the contents of the output", "% directory os.mkdir(directory) def run_gendoc(source, dest, args): \"\"\"Starts gendoc which", "= os.path.abspath(os.path.dirname(__file__)) def setup_argparse(): \"\"\"Sets up the argument parser and", "for gendoc. See gendoc for more information. :type args: list", "idefault = [ipath] parser.add_argument('-i', '--input', nargs='+', default=idefault, help='list of input", "rst files for the source code. Then it runs sphinx", "args: list :returns: None :rtype: None :raises: SystemExit \"\"\" args.insert(0,", "print '\\nRunning gendoc' print '='*80 for i, idir in enumerate(args.input):", "help='print the help for gendoc and exit') return parser def", "print 'Preparing output directories' print '='*80 for odir in args.output:", "source code. Then it runs sphinx make. .. Warning:: This", "which reads source and creates rst files in dest with", "directory first! So you might loose data. You can use", "Warning:: This will delete the content of the output directory", "dir.\\ Default is \\'%s\\'.' % ', '.join(idefault)) opath = os.path.join(thisdir,", "os.path.abspath(os.path.dirname(__file__)) def setup_argparse(): \"\"\"Sets up the argument parser and returns", "os.path.exists(directory): if delete: assert directory != thisdir, 'Trying to delete", "other output dir!' print 'Deleting %s' % directory shutil.rmtree(directory) print", "None :raises: None \"\"\" if os.path.exists(directory): if delete: assert directory", "%s' % args gendoc.main(args) def main(argv=sys.argv[1:]): \"\"\"Parse commandline arguments and", "\"\"\" parser = setup_argparse() args = parser.parse_args(argv) if args.gendochelp: sys.argv[0]", "WARNING: the output directories are emptied by default. See -nod.\\", "documentaion. First it runs gendoc to create rst files\\ for", "'Creating %s' % directory os.mkdir(directory) def run_gendoc(source, dest, args): \"\"\"Starts", "source and creates rst files in dest with the given", "len(args.output): odir = args.output[-1] else: odir = args.output[i] run_gendoc(idir, odir,", "help for gendoc and exit') return parser def prepare_dir(directory, delete=True):", ":class:`argparse.ArgumentParser` :raises: None \"\"\" parser = argparse.ArgumentParser( description=\"Builds the documentaion.", "gendoc' print '='*80 for i, idir in enumerate(args.input): if i", "sys.exit(0) print 'Preparing output directories' print '='*80 for odir in", "import argparse import os import shutil import sys import gendoc", "for gendoc and exit') return parser def prepare_dir(directory, delete=True): \"\"\"Create", "the apidoc directory. you can use relative paths here :type", "None :rtype: None :raises: None \"\"\" if os.path.exists(directory): if delete:", "it runs sphinx make.\\ WARNING: this will delete the contents", "'../src') ipath = os.path.abspath(ipath) idefault = [ipath] parser.add_argument('-i', '--input', nargs='+',", "os.path.join(thisdir, 'reference') opath = os.path.abspath(opath) odefault = [opath] parser.add_argument('-o', '--output',", "output directories. if you have multiple source\\ directories, the corresponding", "first.') parser.add_argument('-gh', '--gendochelp', action='store_true', help='print the help for gendoc and", "See gendoc for more information. :type args: list :returns: None", "True, deletes the contents of apidoc. This acts like an", "contents of apidoc. This acts like an override switch. :type", "parser.add_argument('-o', '--output', nargs='+', default=odefault, help='list of output directories. if you", "See -nod.\\ Default is \\'%s\\'.' % ', '.join(odefault)) gadefault =", "source, the last output dir\\ is used for the remaining", "output directories are emptied by default. See -nod.\\ Default is", "gendoc.setup_parser() genparser.print_help() sys.exit(0) print 'Preparing output directories' print '='*80 for", "gendoc to create rst files for the source code. Then", "'Creating %s' % directory os.mkdir(directory) else: print 'Creating %s' %", "assert directory != thisdir, 'Trying to delete docs! Specify other", "import sys import gendoc thisdir = os.path.abspath(os.path.dirname(__file__)) def setup_argparse(): \"\"\"Sets", "\"\"\"Starts gendoc which reads source and creates rst files in", "a relative path. :type source: str :param dest: The destination", "the source code. Then it runs sphinx make. .. Warning::", "commandline arguments. :type argv: list :returns: None :rtype: None :raises:", "None \"\"\" parser = setup_argparse() args = parser.parse_args(argv) if args.gendochelp:", "data. You can use updatedoc.py -nod. Usage, just call:: updatedoc.py", "shutil import sys import gendoc thisdir = os.path.abspath(os.path.dirname(__file__)) def setup_argparse():", "% directory os.mkdir(directory) else: print 'Creating %s' % directory os.mkdir(directory)", "parser.add_argument('-i', '--input', nargs='+', default=idefault, help='list of input directories. gendoc is", "= argparse.ArgumentParser( description=\"Builds the documentaion. First it runs gendoc to", "to create rst files\\ for the source code. Then it", "not empty the output directories first.') parser.add_argument('-gh', '--gendochelp', action='store_true', help='print", "\"\"\"Builds the documentaion. First it runs gendoc to create rst", ":type source: str :param dest: The destination for the rst", "odir = args.output[i] run_gendoc(idir, odir, args.gendocargs) if __name__ == '__main__':", "directorie is used.\\ if there are less dirs than for", "dest with the given args. :param source: The python source", "delete docs! Specify other output dir!' print 'Deleting %s' %", "python source directory for gendoc. Can be a relative path.", "'gendoc.py' genparser = gendoc.setup_parser() genparser.print_help() sys.exit(0) print 'Preparing output directories'", "shutil.rmtree(directory) print 'Creating %s' % directory os.mkdir(directory) else: print 'Creating", "\"\"\"Sets up the argument parser and returns it :returns: the", "remaining source dirs.\\ WARNING: the output directories are emptied by", "like an override switch. :type delete: bool :returns: None :rtype:", "gendoc. See gendoc for more information. :type args: list :returns:", "to delete docs! Specify other output dir!' print 'Deleting %s'", "-h \"\"\" import argparse import os import shutil import sys", "use -nod.\") ipath = os.path.join(thisdir, '../src') ipath = os.path.abspath(ipath) idefault", "parser.add_argument('-nod', '--nodelete', action='store_true', help='Do not empty the output directories first.')", "make. .. Warning:: This will delete the content of the", "args gendoc.main(args) def main(argv=sys.argv[1:]): \"\"\"Parse commandline arguments and run the", "is \\'%s\\'.' % ', '.join(odefault)) gadefault = ['-T', '-f', '-e',", "info.\\ Default is \\'%s\\'\" % ', '.join(gadefault)) parser.add_argument('-nod', '--nodelete', action='store_true',", "\\'%s\\'\" % ', '.join(gadefault)) parser.add_argument('-nod', '--nodelete', action='store_true', help='Do not empty", "else: odir = args.output[i] run_gendoc(idir, odir, args.gendocargs) if __name__ ==", "str :param args: Arguments for gendoc. See gendoc for more", "for the rst files. Can be a relative path. :type", "delete: if True, deletes the contents of apidoc. This acts", "will delete the content of the output directory first! So", "if True, deletes the contents of apidoc. This acts like", "here :type directory: str :param delete: if True, deletes the", "runs gendoc to create rst files\\ for the source code.", "args.output[-1] else: odir = args.output[i] run_gendoc(idir, odir, args.gendocargs) if __name__", "None \"\"\" if os.path.exists(directory): if delete: assert directory != thisdir,", "if delete: assert directory != thisdir, 'Trying to delete docs!", "args.append(source) print 'Running gendoc.main with: %s' % args gendoc.main(args) def", "sys import gendoc thisdir = os.path.abspath(os.path.dirname(__file__)) def setup_argparse(): \"\"\"Sets up", ":raises: SystemExit \"\"\" args.insert(0, 'gendoc.py') args.append(dest) args.append(source) print 'Running gendoc.main", "rst files\\ for the source code. Then it runs sphinx", "rst files. Can be a relative path. :type dest: str", "use -gh for info.\\ Default is \\'%s\\'\" % ', '.join(gadefault))", "updatedoc.py -h \"\"\" import argparse import os import shutil import", ":raises: None \"\"\" parser = argparse.ArgumentParser( description=\"Builds the documentaion. First", "the corresponding output directorie is used.\\ if there are less", "source directory for gendoc. Can be a relative path. :type", "and returns it :returns: the parser :rtype: :class:`argparse.ArgumentParser` :raises: None", "source\\ directories, the corresponding output directorie is used.\\ if there", "of input directories. gendoc is called for every\\ source dir.\\", "delete: assert directory != thisdir, 'Trying to delete docs! Specify", "is used for the remaining source dirs.\\ WARNING: the output", "runs sphinx make.\\ WARNING: this will delete the contents of", "opath = os.path.join(thisdir, 'reference') opath = os.path.abspath(opath) odefault = [opath]", ":raises: None \"\"\" parser = setup_argparse() args = parser.parse_args(argv) if", "os.mkdir(directory) else: print 'Creating %s' % directory os.mkdir(directory) def run_gendoc(source,", "% ', '.join(idefault)) opath = os.path.join(thisdir, 'reference') opath = os.path.abspath(opath)", "default=idefault, help='list of input directories. gendoc is called for every\\", "dirs than for source, the last output dir\\ is used", "You can use -nod.\") ipath = os.path.join(thisdir, '../src') ipath =", "'--gendochelp', action='store_true', help='print the help for gendoc and exit') return", "None \"\"\" parser = argparse.ArgumentParser( description=\"Builds the documentaion. First it", "nargs='+', default=odefault, help='list of output directories. if you have multiple", "You can use updatedoc.py -nod. Usage, just call:: updatedoc.py -h", "'gendoc.py') args.append(dest) args.append(source) print 'Running gendoc.main with: %s' % args", "pass to gendoc. use -gh for info.\\ Default is \\'%s\\'\"", "= os.path.join(thisdir, 'reference') opath = os.path.abspath(opath) odefault = [opath] parser.add_argument('-o',", "delete is True. :param directory: the apidoc directory. you can", "last output dir\\ is used for the remaining source dirs.\\", "default=odefault, help='list of output directories. if you have multiple source\\", "print 'Deleting %s' % directory shutil.rmtree(directory) print 'Creating %s' %", "arguments. :type argv: list :returns: None :rtype: None :raises: None", "override switch. :type delete: bool :returns: None :rtype: None :raises:", "you might loose data. You can use updatedoc.py -nod. Usage,", "dest: The destination for the rst files. Can be a", "= os.path.join(thisdir, '../src') ipath = os.path.abspath(ipath) idefault = [ipath] parser.add_argument('-i',", "is \\'%s\\'\" % ', '.join(gadefault)) parser.add_argument('-nod', '--nodelete', action='store_true', help='Do not", ":type args: list :returns: None :rtype: None :raises: SystemExit \"\"\"", "to pass to gendoc. use -gh for info.\\ Default is", "the given args. :param source: The python source directory for", "output dir\\ is used for the remaining source dirs.\\ WARNING:", "parser.add_argument('-gh', '--gendochelp', action='store_true', help='print the help for gendoc and exit')", "just call:: updatedoc.py -h \"\"\" import argparse import os import", "argv: list :returns: None :rtype: None :raises: None \"\"\" parser", "if you have multiple source\\ directories, the corresponding output directorie", "directory != thisdir, 'Trying to delete docs! Specify other output", "\"\"\" import argparse import os import shutil import sys import", "parser def prepare_dir(directory, delete=True): \"\"\"Create apidoc dir, delete contents if", "', '.join(gadefault)) parser.add_argument('-nod', '--nodelete', action='store_true', help='Do not empty the output", "import shutil import sys import gendoc thisdir = os.path.abspath(os.path.dirname(__file__)) def", "\\'%s\\'.' % ', '.join(odefault)) gadefault = ['-T', '-f', '-e', '-o']", "paths here :type directory: str :param delete: if True, deletes", "runs gendoc to create rst files for the source code.", "and creates rst files in dest with the given args.", "use updatedoc.py -nod. Usage, just call:: updatedoc.py -h \"\"\" import", "the argument parser and returns it :returns: the parser :rtype:", "tool :param argv: the commandline arguments. :type argv: list :returns:", "arguments and run the tool :param argv: the commandline arguments.", "sys.argv[0] = 'gendoc.py' genparser = gendoc.setup_parser() genparser.print_help() sys.exit(0) print 'Preparing", "\"\"\"Parse commandline arguments and run the tool :param argv: the", "dir\\ is used for the remaining source dirs.\\ WARNING: the", "\"\"\" args.insert(0, 'gendoc.py') args.append(dest) args.append(source) print 'Running gendoc.main with: %s'", "returns it :returns: the parser :rtype: :class:`argparse.ArgumentParser` :raises: None \"\"\"", "output dir!' print 'Deleting %s' % directory shutil.rmtree(directory) print 'Creating", "args. :param source: The python source directory for gendoc. Can", "Specify other output dir!' print 'Deleting %s' % directory shutil.rmtree(directory)", "relative path. :type source: str :param dest: The destination for", "gendoc thisdir = os.path.abspath(os.path.dirname(__file__)) def setup_argparse(): \"\"\"Sets up the argument", "genparser = gendoc.setup_parser() genparser.print_help() sys.exit(0) print 'Preparing output directories' print", "os.path.abspath(opath) odefault = [opath] parser.add_argument('-o', '--output', nargs='+', default=odefault, help='list of", "docs! Specify other output dir!' print 'Deleting %s' % directory", "call:: updatedoc.py -h \"\"\" import argparse import os import shutil", "'.join(idefault)) opath = os.path.join(thisdir, 'reference') opath = os.path.abspath(opath) odefault =", "will delete the contents of the output dirs. You can", "rst files in dest with the given args. :param source:", "given args. :param source: The python source directory for gendoc.", "argparse import os import shutil import sys import gendoc thisdir", "gendoc.main(args) def main(argv=sys.argv[1:]): \"\"\"Parse commandline arguments and run the tool", ">= len(args.output): odir = args.output[-1] else: odir = args.output[i] run_gendoc(idir,", "output dirs. You can use -nod.\") ipath = os.path.join(thisdir, '../src')", "have multiple source\\ directories, the corresponding output directorie is used.\\", ":type delete: bool :returns: None :rtype: None :raises: None \"\"\"", "delete the content of the output directory first! So you", "list :returns: None :rtype: None :raises: None \"\"\" parser =", "action='store_true', help='Do not empty the output directories first.') parser.add_argument('-gh', '--gendochelp',", "setup_argparse(): \"\"\"Sets up the argument parser and returns it :returns:", "'reference') opath = os.path.abspath(opath) odefault = [opath] parser.add_argument('-o', '--output', nargs='+',", "directories' print '='*80 for odir in args.output: prepare_dir(odir, not args.nodelete)", "import os import shutil import sys import gendoc thisdir =", "setup_argparse() args = parser.parse_args(argv) if args.gendochelp: sys.argv[0] = 'gendoc.py' genparser", "print '='*80 for odir in args.output: prepare_dir(odir, not args.nodelete) print", "the content of the output directory first! So you might", "if args.gendochelp: sys.argv[0] = 'gendoc.py' genparser = gendoc.setup_parser() genparser.print_help() sys.exit(0)", "First it runs gendoc to create rst files\\ for the", "description=\"Builds the documentaion. First it runs gendoc to create rst", "is called for every\\ source dir.\\ Default is \\'%s\\'.' %", "This will delete the content of the output directory first!", "used.\\ if there are less dirs than for source, the", "\"\"\" if os.path.exists(directory): if delete: assert directory != thisdir, 'Trying", "help='Do not empty the output directories first.') parser.add_argument('-gh', '--gendochelp', action='store_true',", "', '.join(idefault)) opath = os.path.join(thisdir, 'reference') opath = os.path.abspath(opath) odefault", ":type argv: list :returns: None :rtype: None :raises: None \"\"\"", "run the tool :param argv: the commandline arguments. :type argv:", "None :rtype: None :raises: SystemExit \"\"\" args.insert(0, 'gendoc.py') args.append(dest) args.append(source)", "parser and returns it :returns: the parser :rtype: :class:`argparse.ArgumentParser` :raises:", "'--nodelete', action='store_true', help='Do not empty the output directories first.') parser.add_argument('-gh',", "os import shutil import sys import gendoc thisdir = os.path.abspath(os.path.dirname(__file__))", ":param args: Arguments for gendoc. See gendoc for more information.", "parser.add_argument('-ga', '--gendocargs', nargs='*', default=gadefault, help=\"list of arguments to pass to", "is \\'%s\\'.' % ', '.join(idefault)) opath = os.path.join(thisdir, 'reference') opath", "directory shutil.rmtree(directory) print 'Creating %s' % directory os.mkdir(directory) else: print", "<gh_stars>1-10 #!/usr/bin/env python \"\"\"Builds the documentaion. First it runs gendoc", "gendoc to create rst files\\ for the source code. Then", "apidoc. This acts like an override switch. :type delete: bool", "opath = os.path.abspath(opath) odefault = [opath] parser.add_argument('-o', '--output', nargs='+', default=odefault,", "def run_gendoc(source, dest, args): \"\"\"Starts gendoc which reads source and", "delete the contents of the output dirs. You can use", "= gendoc.setup_parser() genparser.print_help() sys.exit(0) print 'Preparing output directories' print '='*80", "args = parser.parse_args(argv) if args.gendochelp: sys.argv[0] = 'gendoc.py' genparser =", "WARNING: this will delete the contents of the output dirs.", "directory. you can use relative paths here :type directory: str", "delete=True): \"\"\"Create apidoc dir, delete contents if delete is True.", "of the output dirs. You can use -nod.\") ipath =", "with: %s' % args gendoc.main(args) def main(argv=sys.argv[1:]): \"\"\"Parse commandline arguments", "content of the output directory first! So you might loose", "the documentaion. First it runs gendoc to create rst files", ":returns: None :rtype: None :raises: None \"\"\" parser = setup_argparse()", "for every\\ source dir.\\ Default is \\'%s\\'.' % ', '.join(idefault))", "parser = setup_argparse() args = parser.parse_args(argv) if args.gendochelp: sys.argv[0] =", "source dir.\\ Default is \\'%s\\'.' % ', '.join(idefault)) opath =", ":returns: None :rtype: None :raises: SystemExit \"\"\" args.insert(0, 'gendoc.py') args.append(dest)", "of apidoc. This acts like an override switch. :type delete:", "-gh for info.\\ Default is \\'%s\\'\" % ', '.join(gadefault)) parser.add_argument('-nod',", "can use -nod.\") ipath = os.path.join(thisdir, '../src') ipath = os.path.abspath(ipath)", "if i >= len(args.output): odir = args.output[-1] else: odir =", "files\\ for the source code. Then it runs sphinx make.\\", "The python source directory for gendoc. Can be a relative", "\"\"\"Create apidoc dir, delete contents if delete is True. :param", "documentaion. First it runs gendoc to create rst files for", "create rst files for the source code. Then it runs", "multiple source\\ directories, the corresponding output directorie is used.\\ if", "% args gendoc.main(args) def main(argv=sys.argv[1:]): \"\"\"Parse commandline arguments and run", "The destination for the rst files. Can be a relative", "print '='*80 for i, idir in enumerate(args.input): if i >=", "arguments to pass to gendoc. use -gh for info.\\ Default", "'--output', nargs='+', default=odefault, help='list of output directories. if you have", "default. See -nod.\\ Default is \\'%s\\'.' % ', '.join(odefault)) gadefault", "and exit') return parser def prepare_dir(directory, delete=True): \"\"\"Create apidoc dir,", "%s' % directory os.mkdir(directory) def run_gendoc(source, dest, args): \"\"\"Starts gendoc", "directories are emptied by default. See -nod.\\ Default is \\'%s\\'.'", "it :returns: the parser :rtype: :class:`argparse.ArgumentParser` :raises: None \"\"\" parser", "i >= len(args.output): odir = args.output[-1] else: odir = args.output[i]", "code. Then it runs sphinx make. .. Warning:: This will", "apidoc dir, delete contents if delete is True. :param directory:", "['-T', '-f', '-e', '-o'] parser.add_argument('-ga', '--gendocargs', nargs='*', default=gadefault, help=\"list of", "Default is \\'%s\\'.' % ', '.join(idefault)) opath = os.path.join(thisdir, 'reference')", "directory os.mkdir(directory) else: print 'Creating %s' % directory os.mkdir(directory) def", "os.mkdir(directory) def run_gendoc(source, dest, args): \"\"\"Starts gendoc which reads source", "enumerate(args.input): if i >= len(args.output): odir = args.output[-1] else: odir", "the output directory first! So you might loose data. You", "print 'Creating %s' % directory os.mkdir(directory) def run_gendoc(source, dest, args):", "runs sphinx make. .. Warning:: This will delete the content", "= args.output[-1] else: odir = args.output[i] run_gendoc(idir, odir, args.gendocargs) if", "= ['-T', '-f', '-e', '-o'] parser.add_argument('-ga', '--gendocargs', nargs='*', default=gadefault, help=\"list", "action='store_true', help='print the help for gendoc and exit') return parser", "than for source, the last output dir\\ is used for", "for odir in args.output: prepare_dir(odir, not args.nodelete) print '\\nRunning gendoc'", "with the given args. :param source: The python source directory", "is used.\\ if there are less dirs than for source,", "Then it runs sphinx make.\\ WARNING: this will delete the", "odir in args.output: prepare_dir(odir, not args.nodelete) print '\\nRunning gendoc' print", ".. Warning:: This will delete the content of the output", "might loose data. You can use updatedoc.py -nod. Usage, just", "there are less dirs than for source, the last output", "switch. :type delete: bool :returns: None :rtype: None :raises: None", "[ipath] parser.add_argument('-i', '--input', nargs='+', default=idefault, help='list of input directories. gendoc", "True. :param directory: the apidoc directory. you can use relative", "can use updatedoc.py -nod. Usage, just call:: updatedoc.py -h \"\"\"", "gendoc. use -gh for info.\\ Default is \\'%s\\'\" % ',", ":returns: None :rtype: None :raises: None \"\"\" if os.path.exists(directory): if", ":raises: None \"\"\" if os.path.exists(directory): if delete: assert directory !=", "output directory first! So you might loose data. You can", "= 'gendoc.py' genparser = gendoc.setup_parser() genparser.print_help() sys.exit(0) print 'Preparing output", "less dirs than for source, the last output dir\\ is", "path. :type source: str :param dest: The destination for the", "-nod.\\ Default is \\'%s\\'.' % ', '.join(odefault)) gadefault = ['-T',", "Default is \\'%s\\'\" % ', '.join(gadefault)) parser.add_argument('-nod', '--nodelete', action='store_true', help='Do", "the contents of the output dirs. You can use -nod.\")", "Usage, just call:: updatedoc.py -h \"\"\" import argparse import os", "source: str :param dest: The destination for the rst files.", "dest: str :param args: Arguments for gendoc. See gendoc for", "os.path.abspath(ipath) idefault = [ipath] parser.add_argument('-i', '--input', nargs='+', default=idefault, help='list of", "default=gadefault, help=\"list of arguments to pass to gendoc. use -gh", "for info.\\ Default is \\'%s\\'\" % ', '.join(gadefault)) parser.add_argument('-nod', '--nodelete',", "directory: str :param delete: if True, deletes the contents of", "the parser :rtype: :class:`argparse.ArgumentParser` :raises: None \"\"\" parser = argparse.ArgumentParser(", "updatedoc.py -nod. Usage, just call:: updatedoc.py -h \"\"\" import argparse", "source: The python source directory for gendoc. Can be a", "and run the tool :param argv: the commandline arguments. :type", "are emptied by default. See -nod.\\ Default is \\'%s\\'.' %", "parser :rtype: :class:`argparse.ArgumentParser` :raises: None \"\"\" parser = argparse.ArgumentParser( description=\"Builds", "if os.path.exists(directory): if delete: assert directory != thisdir, 'Trying to", "Default is \\'%s\\'.' % ', '.join(odefault)) gadefault = ['-T', '-f',", "os.path.join(thisdir, '../src') ipath = os.path.abspath(ipath) idefault = [ipath] parser.add_argument('-i', '--input',", "loose data. You can use updatedoc.py -nod. Usage, just call::", "the rst files. Can be a relative path. :type dest:", "-nod. Usage, just call:: updatedoc.py -h \"\"\" import argparse import", "creates rst files in dest with the given args. :param", "'.join(odefault)) gadefault = ['-T', '-f', '-e', '-o'] parser.add_argument('-ga', '--gendocargs', nargs='*',", "% directory shutil.rmtree(directory) print 'Creating %s' % directory os.mkdir(directory) else:", "source code. Then it runs sphinx make.\\ WARNING: this will", "parser = argparse.ArgumentParser( description=\"Builds the documentaion. First it runs gendoc", "you can use relative paths here :type directory: str :param", "the output directories first.') parser.add_argument('-gh', '--gendochelp', action='store_true', help='print the help", "Arguments for gendoc. See gendoc for more information. :type args:", "None :raises: None \"\"\" parser = setup_argparse() args = parser.parse_args(argv)", "the remaining source dirs.\\ WARNING: the output directories are emptied", "bool :returns: None :rtype: None :raises: None \"\"\" if os.path.exists(directory):", "str :param delete: if True, deletes the contents of apidoc.", "def prepare_dir(directory, delete=True): \"\"\"Create apidoc dir, delete contents if delete", "'Deleting %s' % directory shutil.rmtree(directory) print 'Creating %s' % directory", "files for the source code. Then it runs sphinx make.", "input directories. gendoc is called for every\\ source dir.\\ Default", "dir, delete contents if delete is True. :param directory: the", "= [opath] parser.add_argument('-o', '--output', nargs='+', default=odefault, help='list of output directories.", ":type directory: str :param delete: if True, deletes the contents", "'='*80 for i, idir in enumerate(args.input): if i >= len(args.output):", "emptied by default. See -nod.\\ Default is \\'%s\\'.' % ',", "thisdir = os.path.abspath(os.path.dirname(__file__)) def setup_argparse(): \"\"\"Sets up the argument parser", "'Trying to delete docs! Specify other output dir!' print 'Deleting", "ipath = os.path.join(thisdir, '../src') ipath = os.path.abspath(ipath) idefault = [ipath]", "if there are less dirs than for source, the last", "dirs. You can use -nod.\") ipath = os.path.join(thisdir, '../src') ipath", "is True. :param directory: the apidoc directory. you can use", "print 'Running gendoc.main with: %s' % args gendoc.main(args) def main(argv=sys.argv[1:]):", "\"\"\" parser = argparse.ArgumentParser( description=\"Builds the documentaion. First it runs", "% ', '.join(gadefault)) parser.add_argument('-nod', '--nodelete', action='store_true', help='Do not empty the", "First it runs gendoc to create rst files for the", "= parser.parse_args(argv) if args.gendochelp: sys.argv[0] = 'gendoc.py' genparser = gendoc.setup_parser()", "for the source code. Then it runs sphinx make.\\ WARNING:", "'--gendocargs', nargs='*', default=gadefault, help=\"list of arguments to pass to gendoc.", "for more information. :type args: list :returns: None :rtype: None", "args.gendochelp: sys.argv[0] = 'gendoc.py' genparser = gendoc.setup_parser() genparser.print_help() sys.exit(0) print", ":type dest: str :param args: Arguments for gendoc. See gendoc", "'Preparing output directories' print '='*80 for odir in args.output: prepare_dir(odir,", "ipath = os.path.abspath(ipath) idefault = [ipath] parser.add_argument('-i', '--input', nargs='+', default=idefault,", "used for the remaining source dirs.\\ WARNING: the output directories", "by default. See -nod.\\ Default is \\'%s\\'.' % ', '.join(odefault))", ":param dest: The destination for the rst files. Can be", "the commandline arguments. :type argv: list :returns: None :rtype: None", "for the remaining source dirs.\\ WARNING: the output directories are", "'-e', '-o'] parser.add_argument('-ga', '--gendocargs', nargs='*', default=gadefault, help=\"list of arguments to", ":param delete: if True, deletes the contents of apidoc. This", "this will delete the contents of the output dirs. You", "Then it runs sphinx make. .. Warning:: This will delete", "%s' % directory shutil.rmtree(directory) print 'Creating %s' % directory os.mkdir(directory)", "main(argv=sys.argv[1:]): \"\"\"Parse commandline arguments and run the tool :param argv:", "= setup_argparse() args = parser.parse_args(argv) if args.gendochelp: sys.argv[0] = 'gendoc.py'", "acts like an override switch. :type delete: bool :returns: None", "for gendoc. Can be a relative path. :type source: str", "SystemExit \"\"\" args.insert(0, 'gendoc.py') args.append(dest) args.append(source) print 'Running gendoc.main with:", "directories first.') parser.add_argument('-gh', '--gendochelp', action='store_true', help='print the help for gendoc", "gendoc.main with: %s' % args gendoc.main(args) def main(argv=sys.argv[1:]): \"\"\"Parse commandline", "idir in enumerate(args.input): if i >= len(args.output): odir = args.output[-1]", "% ', '.join(odefault)) gadefault = ['-T', '-f', '-e', '-o'] parser.add_argument('-ga',", "'Running gendoc.main with: %s' % args gendoc.main(args) def main(argv=sys.argv[1:]): \"\"\"Parse", "in args.output: prepare_dir(odir, not args.nodelete) print '\\nRunning gendoc' print '='*80", ":rtype: :class:`argparse.ArgumentParser` :raises: None \"\"\" parser = argparse.ArgumentParser( description=\"Builds the", "for i, idir in enumerate(args.input): if i >= len(args.output): odir", ":rtype: None :raises: SystemExit \"\"\" args.insert(0, 'gendoc.py') args.append(dest) args.append(source) print", "prepare_dir(odir, not args.nodelete) print '\\nRunning gendoc' print '='*80 for i,", "parser.parse_args(argv) if args.gendochelp: sys.argv[0] = 'gendoc.py' genparser = gendoc.setup_parser() genparser.print_help()", "sphinx make.\\ WARNING: this will delete the contents of the", "output directories first.') parser.add_argument('-gh', '--gendochelp', action='store_true', help='print the help for", "So you might loose data. You can use updatedoc.py -nod.", "-nod.\") ipath = os.path.join(thisdir, '../src') ipath = os.path.abspath(ipath) idefault =", "directory: the apidoc directory. you can use relative paths here", "relative paths here :type directory: str :param delete: if True,", "directories, the corresponding output directorie is used.\\ if there are", "called for every\\ source dir.\\ Default is \\'%s\\'.' % ',", "first! So you might loose data. You can use updatedoc.py", "sphinx make. .. Warning:: This will delete the content of", ":param source: The python source directory for gendoc. Can be", "'-f', '-e', '-o'] parser.add_argument('-ga', '--gendocargs', nargs='*', default=gadefault, help=\"list of arguments", "the contents of apidoc. This acts like an override switch.", "commandline arguments and run the tool :param argv: the commandline", "argv: the commandline arguments. :type argv: list :returns: None :rtype:", "are less dirs than for source, the last output dir\\", "it runs gendoc to create rst files for the source", "python \"\"\"Builds the documentaion. First it runs gendoc to create", "files. Can be a relative path. :type dest: str :param", "gendoc is called for every\\ source dir.\\ Default is \\'%s\\'.'", ":param directory: the apidoc directory. you can use relative paths", "print 'Creating %s' % directory os.mkdir(directory) else: print 'Creating %s'", "return parser def prepare_dir(directory, delete=True): \"\"\"Create apidoc dir, delete contents", "odir = args.output[-1] else: odir = args.output[i] run_gendoc(idir, odir, args.gendocargs)", "be a relative path. :type source: str :param dest: The", "'--input', nargs='+', default=idefault, help='list of input directories. gendoc is called", "every\\ source dir.\\ Default is \\'%s\\'.' % ', '.join(idefault)) opath", "contents if delete is True. :param directory: the apidoc directory.", "dir!' print 'Deleting %s' % directory shutil.rmtree(directory) print 'Creating %s'", "str :param dest: The destination for the rst files. Can", "the tool :param argv: the commandline arguments. :type argv: list", "This acts like an override switch. :type delete: bool :returns:", "else: print 'Creating %s' % directory os.mkdir(directory) def run_gendoc(source, dest,", "= os.path.abspath(opath) odefault = [opath] parser.add_argument('-o', '--output', nargs='+', default=odefault, help='list", "an override switch. :type delete: bool :returns: None :rtype: None", "apidoc directory. you can use relative paths here :type directory:", "directory os.mkdir(directory) def run_gendoc(source, dest, args): \"\"\"Starts gendoc which reads", "the documentaion. First it runs gendoc to create rst files\\", "= [ipath] parser.add_argument('-i', '--input', nargs='+', default=idefault, help='list of input directories.", "to gendoc. use -gh for info.\\ Default is \\'%s\\'\" %", "files in dest with the given args. :param source: The", ":returns: the parser :rtype: :class:`argparse.ArgumentParser` :raises: None \"\"\" parser =", "odefault = [opath] parser.add_argument('-o', '--output', nargs='+', default=odefault, help='list of output", "contents of the output dirs. You can use -nod.\") ipath", "delete: bool :returns: None :rtype: None :raises: None \"\"\" if", "list :returns: None :rtype: None :raises: SystemExit \"\"\" args.insert(0, 'gendoc.py')", "argument parser and returns it :returns: the parser :rtype: :class:`argparse.ArgumentParser`", "output directorie is used.\\ if there are less dirs than", "code. Then it runs sphinx make.\\ WARNING: this will delete", "of arguments to pass to gendoc. use -gh for info.\\", "gendoc. Can be a relative path. :type source: str :param", "in enumerate(args.input): if i >= len(args.output): odir = args.output[-1] else:", "Can be a relative path. :type source: str :param dest:", "a relative path. :type dest: str :param args: Arguments for", "gendoc for more information. :type args: list :returns: None :rtype:", "None :rtype: None :raises: None \"\"\" parser = setup_argparse() args", "run_gendoc(source, dest, args): \"\"\"Starts gendoc which reads source and creates", "dest, args): \"\"\"Starts gendoc which reads source and creates rst", "path. :type dest: str :param args: Arguments for gendoc. See", "corresponding output directorie is used.\\ if there are less dirs", "more information. :type args: list :returns: None :rtype: None :raises:", "create rst files\\ for the source code. Then it runs", "output directories' print '='*80 for odir in args.output: prepare_dir(odir, not", "Can be a relative path. :type dest: str :param args:", ":rtype: None :raises: None \"\"\" parser = setup_argparse() args =", "it runs sphinx make. .. Warning:: This will delete the", "of output directories. if you have multiple source\\ directories, the", "'.join(gadefault)) parser.add_argument('-nod', '--nodelete', action='store_true', help='Do not empty the output directories", ":rtype: None :raises: None \"\"\" if os.path.exists(directory): if delete: assert", "empty the output directories first.') parser.add_argument('-gh', '--gendochelp', action='store_true', help='print the", "the output directories are emptied by default. See -nod.\\ Default", "args.output: prepare_dir(odir, not args.nodelete) print '\\nRunning gendoc' print '='*80 for", "None :raises: SystemExit \"\"\" args.insert(0, 'gendoc.py') args.append(dest) args.append(source) print 'Running", "'-o'] parser.add_argument('-ga', '--gendocargs', nargs='*', default=gadefault, help=\"list of arguments to pass", "'\\nRunning gendoc' print '='*80 for i, idir in enumerate(args.input): if", "def main(argv=sys.argv[1:]): \"\"\"Parse commandline arguments and run the tool :param", "to create rst files for the source code. Then it", "directory for gendoc. Can be a relative path. :type source:", "you have multiple source\\ directories, the corresponding output directorie is", "args): \"\"\"Starts gendoc which reads source and creates rst files", "= args.output[i] run_gendoc(idir, odir, args.gendocargs) if __name__ == '__main__': main()", "args.nodelete) print '\\nRunning gendoc' print '='*80 for i, idir in", "\\'%s\\'.' % ', '.join(idefault)) opath = os.path.join(thisdir, 'reference') opath =", ":param argv: the commandline arguments. :type argv: list :returns: None", "thisdir, 'Trying to delete docs! Specify other output dir!' print", "the help for gendoc and exit') return parser def prepare_dir(directory,", "def setup_argparse(): \"\"\"Sets up the argument parser and returns it", "of the output directory first! So you might loose data.", "%s' % directory os.mkdir(directory) else: print 'Creating %s' % directory", "argparse.ArgumentParser( description=\"Builds the documentaion. First it runs gendoc to create", "'='*80 for odir in args.output: prepare_dir(odir, not args.nodelete) print '\\nRunning", "for the source code. Then it runs sphinx make. ..", "nargs='*', default=gadefault, help=\"list of arguments to pass to gendoc. use", "help=\"list of arguments to pass to gendoc. use -gh for", "deletes the contents of apidoc. This acts like an override", "!= thisdir, 'Trying to delete docs! Specify other output dir!'", "it runs gendoc to create rst files\\ for the source", "', '.join(odefault)) gadefault = ['-T', '-f', '-e', '-o'] parser.add_argument('-ga', '--gendocargs',", "help='list of input directories. gendoc is called for every\\ source", "dirs.\\ WARNING: the output directories are emptied by default. See", "information. :type args: list :returns: None :rtype: None :raises: SystemExit", "delete contents if delete is True. :param directory: the apidoc", "use relative paths here :type directory: str :param delete: if", "the output dirs. You can use -nod.\") ipath = os.path.join(thisdir,", "if delete is True. :param directory: the apidoc directory. you", "gendoc and exit') return parser def prepare_dir(directory, delete=True): \"\"\"Create apidoc" ]
[ "for j in range(i+1, n): # encontra o menor elemento", "1) + (3n + n/2) + (n^2/2) # The complexity", "encontra o menor elemento da lista a partir de i", "+ (n-1)*[3 + X] = 1 + 3*(n-1) + X*(n-1)", "X*(n-1) = 1 + 3*(n-1) + (n^2 + n -", "= i for j in range(i+1, n): # encontra o", "posicao correta return A # 1 + (n-1)*[3 + X]", "range(i+1, n): # encontra o menor elemento da lista a", "A[min] = A[min], A[i] # insere o elemento na posicao", "j in range(i+1, n): # encontra o menor elemento da", "= A[min], A[i] # insere o elemento na posicao correta", "min = j A[i], A[min] = A[min], A[i] # insere", "= 1 + 3*(n-1) + (n^2 + n - 2)/2", "O(n^2) n = len(A) for i in range(n-1): # percorre", "1 + 3*(n-1) + (n^2 + n - 2)/2 #", "- 1) + (3n + n/2) + (n^2/2) # The", "+ 1 if A[j] < A[min]: min = j A[i],", "+ X*(n-1) = 1 + 3*(n-1) + (n^2 + n", "< A[min]: min = j A[i], A[min] = A[min], A[i]", "i for j in range(i+1, n): # encontra o menor", "a lista min = i for j in range(i+1, n):", "o elemento na posicao correta return A # 1 +", "+ n - 2)/2 # = (1 - 3 -", "3 - 1) + (3n + n/2) + (n^2/2) #", "in range(n-1): # percorre a lista min = i for", "i + 1 if A[j] < A[min]: min = j", "# O(n^2) n = len(A) for i in range(n-1): #", "+ (n^2 + n - 2)/2 # = (1 -", "lista a partir de i + 1 if A[j] <", "3*(n-1) + X*(n-1) = 1 + 3*(n-1) + (n^2 +", "menor elemento da lista a partir de i + 1", "+ 3*(n-1) + (n^2 + n - 2)/2 # =", "# 1 + (n-1)*[3 + X] = 1 + 3*(n-1)", "a partir de i + 1 if A[j] < A[min]:", "= 1 + 3*(n-1) + X*(n-1) = 1 + 3*(n-1)", "# insere o elemento na posicao correta return A #", "correta return A # 1 + (n-1)*[3 + X] =", "min = i for j in range(i+1, n): # encontra", "n = len(A) for i in range(n-1): # percorre a", "if A[j] < A[min]: min = j A[i], A[min] =", "1 + 3*(n-1) + X*(n-1) = 1 + 3*(n-1) +", "X] = 1 + 3*(n-1) + X*(n-1) = 1 +", "(n^2 + n - 2)/2 # = (1 - 3", "j A[i], A[min] = A[min], A[i] # insere o elemento", "+ X] = 1 + 3*(n-1) + X*(n-1) = 1", "2)/2 # = (1 - 3 - 1) + (3n", "+ (3n + n/2) + (n^2/2) # The complexity is", "(3n + n/2) + (n^2/2) # The complexity is O(n^2)", "A[min], A[i] # insere o elemento na posicao correta return", "# = (1 - 3 - 1) + (3n +", "= (1 - 3 - 1) + (3n + n/2)", "elemento na posicao correta return A # 1 + (n-1)*[3", "- 3 - 1) + (3n + n/2) + (n^2/2)", "n - 2)/2 # = (1 - 3 - 1)", "de i + 1 if A[j] < A[min]: min =", "in range(i+1, n): # encontra o menor elemento da lista", "o menor elemento da lista a partir de i +", "= j A[i], A[min] = A[min], A[i] # insere o", "lista min = i for j in range(i+1, n): #", "selection_sort(A): # O(n^2) n = len(A) for i in range(n-1):", "A[i] # insere o elemento na posicao correta return A", "A[j] < A[min]: min = j A[i], A[min] = A[min],", "1 + (n-1)*[3 + X] = 1 + 3*(n-1) +", "(n-1)*[3 + X] = 1 + 3*(n-1) + X*(n-1) =", "# percorre a lista min = i for j in", "= len(A) for i in range(n-1): # percorre a lista", "elemento da lista a partir de i + 1 if", "partir de i + 1 if A[j] < A[min]: min", "len(A) for i in range(n-1): # percorre a lista min", "# encontra o menor elemento da lista a partir de", "insere o elemento na posicao correta return A # 1", "def selection_sort(A): # O(n^2) n = len(A) for i in", "(1 - 3 - 1) + (3n + n/2) +", "A[min]: min = j A[i], A[min] = A[min], A[i] #", "+ 3*(n-1) + X*(n-1) = 1 + 3*(n-1) + (n^2", "A[i], A[min] = A[min], A[i] # insere o elemento na", "for i in range(n-1): # percorre a lista min =", "percorre a lista min = i for j in range(i+1,", "na posicao correta return A # 1 + (n-1)*[3 +", "- 2)/2 # = (1 - 3 - 1) +", "1 if A[j] < A[min]: min = j A[i], A[min]", "A # 1 + (n-1)*[3 + X] = 1 +", "da lista a partir de i + 1 if A[j]", "return A # 1 + (n-1)*[3 + X] = 1", "3*(n-1) + (n^2 + n - 2)/2 # = (1", "range(n-1): # percorre a lista min = i for j", "n): # encontra o menor elemento da lista a partir", "i in range(n-1): # percorre a lista min = i" ]
[ "load_collector_type == SPC: spc: SPC = load tcl_commands.append( f\"*createmark nodes", "0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 8134 1 1 0", "None: \"\"\" Creates all the load collectors (has to be", "tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 8134 1 1 0 0\") tcl_commands.append(", "spc: SPC = load tcl_commands.append( f\"*createmark nodes 1 {' '.join([str(x)", "= f\"{str(load_collector_type.__name__)}_{str(load_collector.get_id())}\" tcl_commands.append( f\"*createentity loadcols includeid=0 name=\\\"{load_collector.name}\\\"\") # create loads", "from typing import List, Tuple from BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector from", "for x in spc.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 3 1", "loadsteps {load_step_id} 4145 1 1 0 loadcols {spc_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateentity", "1\") tcl_commands.append( f\"*loadstepscreate \\\"loadstep_{load_step_id}\\\" 1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4143", "load tcl_commands.append( f\"*createmark nodes 1 {' '.join([str(x) for x in", "f\"*createmark loadcols 1 \\\"{spc_loadCollector.name}\\\" \\\"{load_loadCollector.name}\\\"\") tcl_commands.append(\"*createmark outputblocks 1\") tcl_commands.append(\"*createmark groups", "== Force: force: Force = load tcl_commands.append( f\"*createmark nodes 1", "0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2396 1 1 0 0\")", "to the file \"\"\" self.write_tcl_commands_loadCollectors(tcl_commands) # create the load step", "tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4143 1 1 0 1\") tcl_commands.append(", "{force.y} {force.z} 0 0 0 0\") elif load_collector_type == SPC:", "tcl_commands.append(\"*createmark groups 1\") tcl_commands.append( f\"*loadstepscreate \\\"loadstep_{load_step_id}\\\" 1\") tcl_commands.append( f\"*attributeupdateint loadsteps", "the loadcollectors are referenced) \"\"\" load_collector: LoadCollector = None #", "-> None: \"\"\" Single method to write all tcl commands", "{load_step_id} 2160 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id}", "loadcollectors are referenced) \"\"\" load_collector: LoadCollector = None # create", "done before creating loadsteps, as the loadcollectors are referenced) \"\"\"", "LoadStep.instances: load_step_id = str(load_step.get_id()) # TODO: should be possible to", "0 loadcols {load_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 3800 1 1", "collectors and loads first for load_collector in LoadCollector.instances: load_collector_type =", "the load step load_step: LoadStep = None for load_step in", "-> None: \"\"\" Creates all the load collectors (has to", "tcl_commands.append( f\"*loadstepscreate \\\"loadstep_{load_step_id}\\\" 1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4143 1", "{force.x} {force.y} {force.z} 0 {force.x} {force.y} {force.z} 0 0 0", "{force.y} {force.z} 0 {force.x} {force.y} {force.z} 0 0 0 0\")", "elif load_collector_type == SPC: spc: SPC = load tcl_commands.append( f\"*createmark", "f\"*loadstepscreate \\\"loadstep_{load_step_id}\\\" 1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4143 1 1", "force: Force = load tcl_commands.append( f\"*createmark nodes 1 {' '.join([str(x)", "1 1 0 1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4709 1", "from BridgeOptimizer.datastructure.hypermesh.Force import Force from BridgeOptimizer.datastructure.hypermesh.SPC import SPC class ScriptBuilderBoundaryConditions:", "loadsteps, as the loadcollectors are referenced) \"\"\" load_collector: LoadCollector =", "pass def write_tcl_commands_loadCollectors(self, tcl_commands: List) -> None: \"\"\" Creates all", "def write_tcl_commands_loadsteps(self, tcl_commands: List) -> None: \"\"\" Single method to", "1 {force.x} {force.y} {force.z} 0 {force.x} {force.y} {force.z} 0 0", "1 {' '.join([str(x) for x in spc.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes", "tcl_commands: List) -> None: \"\"\" Single method to write all", "to just use a spc collector - not possible rn.", "ScriptBuilderBoundaryConditions: \"\"\" Extra class for generating Loadstep, Loadcollectors, Forces and", "== SPC: spc: SPC = load tcl_commands.append( f\"*createmark nodes 1", "possible to just use a spc collector - not possible", "{spc.dofs[5]} 0 0 0 0 0\") tcl_commands.append(\"*createmark loads 0 1\")", "4060=STATICS\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4145 1 1 0 loadcols", "as the loadcollectors are referenced) \"\"\" load_collector: LoadCollector = None", "1 1 {force.x} {force.y} {force.z} 0 {force.x} {force.y} {force.z} 0", "4145 1 1 0 loadcols {spc_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id}", "tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 3 1 {spc.dofs[0]} {spc.dofs[1]} {spc.dofs[2]} {spc.dofs[3]}", "load_collector: LoadCollector = None # create all load collectors and", "tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4147 1 1 0 loadcols {load_loadCollector_id}\")", "load_loadCollector = load_step.load_loadCollector spc_loadCollector_id = str(spc_loadCollector.get_id()) load_loadCollector_id = str(load_loadCollector.get_id()) tcl_commands.append(", "create loads for load in load_collector.loads: if load_collector_type == Force:", "tcl_commands.append(\"*loadsupdatefixedvalue 0 0\") def write_tcl_commands_loadsteps(self, tcl_commands: List) -> None: \"\"\"", "0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2396 1 1 0", "loadsteps {load_step_id} 3800 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps", "{force.z} 0 {force.x} {force.y} {force.z} 0 0 0 0\") elif", "{load_step_id} 4145 1 1 0 loadcols {spc_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateentity loadsteps", "for load_collector in LoadCollector.instances: load_collector_type = load_collector.get_load_collector_type() load_collector.name = f\"{str(load_collector_type.__name__)}_{str(load_collector.get_id())}\"", "{spc.dofs[0]} {spc.dofs[1]} {spc.dofs[2]} {spc.dofs[3]} {spc.dofs[4]} {spc.dofs[5]} 0 0 0 0", "load_collector in LoadCollector.instances: load_collector_type = load_collector.get_load_collector_type() load_collector.name = f\"{str(load_collector_type.__name__)}_{str(load_collector.get_id())}\" tcl_commands.append(", "1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4143 1 1 0 1\")", "1 0 loadcols {load_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 3800 1", "1\") tcl_commands.append( f\"*setvalue loadsteps id={load_step_id} STATUS=2 4059=1 4060=STATICS\") tcl_commands.append( f\"*attributeupdateentity", "generating Loadstep, Loadcollectors, Forces and Constraints Parameters: --------- None \"\"\"", "be done before creating loadsteps, as the loadcollectors are referenced)", "f\"*createmark nodes 1 {' '.join([str(x) for x in force.nodeIds])}\") tcl_commands.append(", "{spc.dofs[1]} {spc.dofs[2]} {spc.dofs[3]} {spc.dofs[4]} {spc.dofs[5]} 0 0 0 0 0\")", "loads first for load_collector in LoadCollector.instances: load_collector_type = load_collector.get_load_collector_type() load_collector.name", "load_collector.name = f\"{str(load_collector_type.__name__)}_{str(load_collector.get_id())}\" tcl_commands.append( f\"*createentity loadcols includeid=0 name=\\\"{load_collector.name}\\\"\") # create", "1 {spc.dofs[0]} {spc.dofs[1]} {spc.dofs[2]} {spc.dofs[3]} {spc.dofs[4]} {spc.dofs[5]} 0 0 0", "all tcl commands to the file \"\"\" self.write_tcl_commands_loadCollectors(tcl_commands) # create", "if load_collector_type == Force: force: Force = load tcl_commands.append( f\"*createmark", "tcl_commands.append( f\"*createmark nodes 1 {' '.join([str(x) for x in spc.nodeIds])}\")", "loadcols {load_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 3800 1 1 0", "1\") tcl_commands.append(\"*loadsupdatefixedvalue 0 0\") def write_tcl_commands_loadsteps(self, tcl_commands: List) -> None:", "0 1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4709 1 1 0", "\"\"\" Creates all the load collectors (has to be done", "includeid=0 name=\\\"{load_collector.name}\\\"\") # create loads for load in load_collector.loads: if", "1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 707 1", "to be done before creating loadsteps, as the loadcollectors are", "'.join([str(x) for x in force.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 1", "tcl commands to the file \"\"\" self.write_tcl_commands_loadCollectors(tcl_commands) # create the", "f\"*attributeupdateint loadsteps {load_step_id} 2160 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint", "load_step.spc_loadCollector load_loadCollector = load_step.load_loadCollector spc_loadCollector_id = str(spc_loadCollector.get_id()) load_loadCollector_id = str(load_loadCollector.get_id())", "0 0\") elif load_collector_type == SPC: spc: SPC = load", "import SPC class ScriptBuilderBoundaryConditions: \"\"\" Extra class for generating Loadstep,", "f\"*attributeupdateint loadsteps {load_step_id} 707 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint", "tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4145 1 1 0 loadcols {spc_loadCollector_id}\")", "0 loadcols {spc_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4147 1 1", "\"\"\" Extra class for generating Loadstep, Loadcollectors, Forces and Constraints", "method to write all tcl commands to the file \"\"\"", "import LoadStep from BridgeOptimizer.datastructure.hypermesh.Force import Force from BridgeOptimizer.datastructure.hypermesh.SPC import SPC", "create all load collectors and loads first for load_collector in", "tcl_commands.append( f\"*createmark nodes 1 {' '.join([str(x) for x in force.nodeIds])}\")", "{load_step_id} 3800 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id}", "in LoadStep.instances: load_step_id = str(load_step.get_id()) # TODO: should be possible", "2160 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 10212", "= None for load_step in LoadStep.instances: load_step_id = str(load_step.get_id()) #", "{spc.dofs[2]} {spc.dofs[3]} {spc.dofs[4]} {spc.dofs[5]} 0 0 0 0 0\") tcl_commands.append(\"*createmark", "0 0\") tcl_commands.append(\"*createmark loads 0 1\") tcl_commands.append(\"*loadsupdatefixedvalue 0 0\") def", "BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep from BridgeOptimizer.datastructure.hypermesh.Force import Force from BridgeOptimizer.datastructure.hypermesh.SPC import", "0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 10212 1 1 0", "id={load_step_id} STATUS=2 4059=1 4060=STATICS\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4145 1", "commands to the file \"\"\" self.write_tcl_commands_loadCollectors(tcl_commands) # create the load", "0 0 0 0 0\") tcl_commands.append(\"*createmark loads 0 1\") tcl_commands.append(\"*loadsupdatefixedvalue", "f\"*attributeupdateentity loadsteps {load_step_id} 4145 1 1 0 loadcols {spc_loadCollector_id}\") tcl_commands.append(", "spc collector - not possible rn. spc_loadCollector = load_step.spc_loadCollector load_loadCollector", "\"\"\" self.write_tcl_commands_loadCollectors(tcl_commands) # create the load step load_step: LoadStep =", "just use a spc collector - not possible rn. spc_loadCollector", "= load tcl_commands.append( f\"*createmark nodes 1 {' '.join([str(x) for x", "{load_step_id} 4709 1 1 0 1\") tcl_commands.append( f\"*setvalue loadsteps id={load_step_id}", "f\"*setvalue loadsteps id={load_step_id} STATUS=2 4059=1 4060=STATICS\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id}", "x in spc.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 3 1 {spc.dofs[0]}", "load_collector.loads: if load_collector_type == Force: force: Force = load tcl_commands.append(", "f\"*attributeupdateint loadsteps {load_step_id} 2396 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint", "0 1\") tcl_commands.append( f\"*setvalue loadsteps id={load_step_id} STATUS=2 4059=1 4060=STATICS\") tcl_commands.append(", "0\") tcl_commands.append(\"*createmark loads 0 1\") tcl_commands.append(\"*loadsupdatefixedvalue 0 0\") def write_tcl_commands_loadsteps(self,", "1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2396 1 1", "class ScriptBuilderBoundaryConditions: \"\"\" Extra class for generating Loadstep, Loadcollectors, Forces", "spc.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 3 1 {spc.dofs[0]} {spc.dofs[1]} {spc.dofs[2]}", "0 1\") tcl_commands.append(\"*loadsupdatefixedvalue 0 0\") def write_tcl_commands_loadsteps(self, tcl_commands: List) ->", "{load_step_id} 8134 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id}", "tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4709 1 1 0 1\") tcl_commands.append(", "{' '.join([str(x) for x in spc.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1", "are referenced) \"\"\" load_collector: LoadCollector = None # create all", "spc_loadCollector = load_step.spc_loadCollector load_loadCollector = load_step.load_loadCollector spc_loadCollector_id = str(spc_loadCollector.get_id()) load_loadCollector_id", "{spc.dofs[4]} {spc.dofs[5]} 0 0 0 0 0\") tcl_commands.append(\"*createmark loads 0", "class for generating Loadstep, Loadcollectors, Forces and Constraints Parameters: ---------", "1 0 loadcols {spc_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4147 1", "load step load_step: LoadStep = None for load_step in LoadStep.instances:", "4147 1 1 0 loadcols {load_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id}", "tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 3800 1 1 0 0\") tcl_commands.append(", "f\"*createentity loadcols includeid=0 name=\\\"{load_collector.name}\\\"\") # create loads for load in", "name=\\\"{load_collector.name}\\\"\") # create loads for load in load_collector.loads: if load_collector_type", "f\"*attributeupdateint loadsteps {load_step_id} 8134 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint", "\"\"\" Single method to write all tcl commands to the", "os from typing import List, Tuple from BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector", "= str(load_step.get_id()) # TODO: should be possible to just use", "LoadCollector = None # create all load collectors and loads", "spc_loadCollector_id = str(spc_loadCollector.get_id()) load_loadCollector_id = str(load_loadCollector.get_id()) tcl_commands.append( f\"*createmark loadcols 1", "rn. spc_loadCollector = load_step.spc_loadCollector load_loadCollector = load_step.load_loadCollector spc_loadCollector_id = str(spc_loadCollector.get_id())", "TODO: should be possible to just use a spc collector", "before creating loadsteps, as the loadcollectors are referenced) \"\"\" load_collector:", "load_step_id = str(load_step.get_id()) # TODO: should be possible to just", "= None # create all load collectors and loads first", "# TODO: should be possible to just use a spc", "1\") tcl_commands.append(\"*createmark groups 1\") tcl_commands.append( f\"*loadstepscreate \\\"loadstep_{load_step_id}\\\" 1\") tcl_commands.append( f\"*attributeupdateint", "for x in force.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 1 1", "= load_collector.get_load_collector_type() load_collector.name = f\"{str(load_collector_type.__name__)}_{str(load_collector.get_id())}\" tcl_commands.append( f\"*createentity loadcols includeid=0 name=\\\"{load_collector.name}\\\"\")", "import LoadCollector from BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep from BridgeOptimizer.datastructure.hypermesh.Force import Force", "from BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep from BridgeOptimizer.datastructure.hypermesh.Force import Force from BridgeOptimizer.datastructure.hypermesh.SPC", "file \"\"\" self.write_tcl_commands_loadCollectors(tcl_commands) # create the load step load_step: LoadStep", "3800 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 707", "1 0 1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4709 1 1", "loadsteps id={load_step_id} STATUS=2 4059=1 4060=STATICS\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4145", "1 \\\"{spc_loadCollector.name}\\\" \\\"{load_loadCollector.name}\\\"\") tcl_commands.append(\"*createmark outputblocks 1\") tcl_commands.append(\"*createmark groups 1\") tcl_commands.append(", "1 3 1 {spc.dofs[0]} {spc.dofs[1]} {spc.dofs[2]} {spc.dofs[3]} {spc.dofs[4]} {spc.dofs[5]} 0", "load_step: LoadStep = None for load_step in LoadStep.instances: load_step_id =", "nodes 1 {' '.join([str(x) for x in spc.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve", "1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2160 1", "# create the load step load_step: LoadStep = None for", "# create all load collectors and loads first for load_collector", "BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector from BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep from BridgeOptimizer.datastructure.hypermesh.Force import", "LoadCollector from BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep from BridgeOptimizer.datastructure.hypermesh.Force import Force from", "1 1 0 1\") tcl_commands.append( f\"*setvalue loadsteps id={load_step_id} STATUS=2 4059=1", "4143 1 1 0 1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4709", "outputblocks 1\") tcl_commands.append(\"*createmark groups 1\") tcl_commands.append( f\"*loadstepscreate \\\"loadstep_{load_step_id}\\\" 1\") tcl_commands.append(", "1 {' '.join([str(x) for x in force.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes", "the load collectors (has to be done before creating loadsteps,", "1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 8134 1", "loads 0 1\") tcl_commands.append(\"*loadsupdatefixedvalue 0 0\") def write_tcl_commands_loadsteps(self, tcl_commands: List)", "a spc collector - not possible rn. spc_loadCollector = load_step.spc_loadCollector", "Creates all the load collectors (has to be done before", "loadsteps {load_step_id} 2396 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps", "4059=1 4060=STATICS\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4145 1 1 0", "tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2160 1 1 0 0\") tcl_commands.append(", "Parameters: --------- None \"\"\" def __init__(self) -> None: pass def", "be possible to just use a spc collector - not", "1 1 0 loadcols {load_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 3800", "1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 707 1 1", "{force.x} {force.y} {force.z} 0 0 0 0\") elif load_collector_type ==", "Tuple from BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector from BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep from", "Loadcollectors, Forces and Constraints Parameters: --------- None \"\"\" def __init__(self)", "loadsteps {load_step_id} 2160 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps", "0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2160 1 1 0 0\")", "1 1 0 loadcols {spc_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4147", "in LoadCollector.instances: load_collector_type = load_collector.get_load_collector_type() load_collector.name = f\"{str(load_collector_type.__name__)}_{str(load_collector.get_id())}\" tcl_commands.append( f\"*createentity", "tcl_commands.append(\"*createmark outputblocks 1\") tcl_commands.append(\"*createmark groups 1\") tcl_commands.append( f\"*loadstepscreate \\\"loadstep_{load_step_id}\\\" 1\")", "Force from BridgeOptimizer.datastructure.hypermesh.SPC import SPC class ScriptBuilderBoundaryConditions: \"\"\" Extra class", "Force = load tcl_commands.append( f\"*createmark nodes 1 {' '.join([str(x) for", "nodes 1 3 1 {spc.dofs[0]} {spc.dofs[1]} {spc.dofs[2]} {spc.dofs[3]} {spc.dofs[4]} {spc.dofs[5]}", "1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 8134 1 1", "tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 707 1 1 0 0\") tcl_commands.append(", "for load in load_collector.loads: if load_collector_type == Force: force: Force", "1 1 1 {force.x} {force.y} {force.z} 0 {force.x} {force.y} {force.z}", "\"\"\" def __init__(self) -> None: pass def write_tcl_commands_loadCollectors(self, tcl_commands: List)", "loadsteps {load_step_id} 8134 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps", "str(spc_loadCollector.get_id()) load_loadCollector_id = str(load_loadCollector.get_id()) tcl_commands.append( f\"*createmark loadcols 1 \\\"{spc_loadCollector.name}\\\" \\\"{load_loadCollector.name}\\\"\")", "step load_step: LoadStep = None for load_step in LoadStep.instances: load_step_id", "first for load_collector in LoadCollector.instances: load_collector_type = load_collector.get_load_collector_type() load_collector.name =", "3 1 {spc.dofs[0]} {spc.dofs[1]} {spc.dofs[2]} {spc.dofs[3]} {spc.dofs[4]} {spc.dofs[5]} 0 0", "loadcols 1 \\\"{spc_loadCollector.name}\\\" \\\"{load_loadCollector.name}\\\"\") tcl_commands.append(\"*createmark outputblocks 1\") tcl_commands.append(\"*createmark groups 1\")", "loadsteps {load_step_id} 707 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps", "x in force.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 1 1 {force.x}", "loads for load in load_collector.loads: if load_collector_type == Force: force:", "in force.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 1 1 {force.x} {force.y}", "0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 8134 1 1 0 0\")", "None: \"\"\" Single method to write all tcl commands to", "tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2396 1 1 0 0\") tcl_commands.append(", "None \"\"\" def __init__(self) -> None: pass def write_tcl_commands_loadCollectors(self, tcl_commands:", "for generating Loadstep, Loadcollectors, Forces and Constraints Parameters: --------- None", "SPC class ScriptBuilderBoundaryConditions: \"\"\" Extra class for generating Loadstep, Loadcollectors,", "707 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2396", "Forces and Constraints Parameters: --------- None \"\"\" def __init__(self) ->", "0 0\") def write_tcl_commands_loadsteps(self, tcl_commands: List) -> None: \"\"\" Single", "force.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 1 1 {force.x} {force.y} {force.z}", "for load_step in LoadStep.instances: load_step_id = str(load_step.get_id()) # TODO: should", "Constraints Parameters: --------- None \"\"\" def __init__(self) -> None: pass", "'.join([str(x) for x in spc.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 3", "f\"*loadcreateonentity_curve nodes 1 3 1 {spc.dofs[0]} {spc.dofs[1]} {spc.dofs[2]} {spc.dofs[3]} {spc.dofs[4]}", "{load_step_id} 2396 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id}", "STATUS=2 4059=1 4060=STATICS\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4145 1 1", "import os from typing import List, Tuple from BridgeOptimizer.datastructure.hypermesh.LoadCollector import", "write_tcl_commands_loadCollectors(self, tcl_commands: List) -> None: \"\"\" Creates all the load", "loadsteps {load_step_id} 4143 1 1 0 1\") tcl_commands.append( f\"*attributeupdateint loadsteps", "1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4709 1 1 0 1\")", "0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 10212 1 1 0 0\")", "load collectors and loads first for load_collector in LoadCollector.instances: load_collector_type", "= str(load_loadCollector.get_id()) tcl_commands.append( f\"*createmark loadcols 1 \\\"{spc_loadCollector.name}\\\" \\\"{load_loadCollector.name}\\\"\") tcl_commands.append(\"*createmark outputblocks", "tcl_commands.append(\"*createmark loads 0 1\") tcl_commands.append(\"*loadsupdatefixedvalue 0 0\") def write_tcl_commands_loadsteps(self, tcl_commands:", "0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2160 1 1 0", "from BridgeOptimizer.datastructure.hypermesh.SPC import SPC class ScriptBuilderBoundaryConditions: \"\"\" Extra class for", "load_collector_type = load_collector.get_load_collector_type() load_collector.name = f\"{str(load_collector_type.__name__)}_{str(load_collector.get_id())}\" tcl_commands.append( f\"*createentity loadcols includeid=0", "List) -> None: \"\"\" Single method to write all tcl", "write_tcl_commands_loadsteps(self, tcl_commands: List) -> None: \"\"\" Single method to write", "\\\"{spc_loadCollector.name}\\\" \\\"{load_loadCollector.name}\\\"\") tcl_commands.append(\"*createmark outputblocks 1\") tcl_commands.append(\"*createmark groups 1\") tcl_commands.append( f\"*loadstepscreate", "loadcols {spc_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4147 1 1 0", "and loads first for load_collector in LoadCollector.instances: load_collector_type = load_collector.get_load_collector_type()", "the file \"\"\" self.write_tcl_commands_loadCollectors(tcl_commands) # create the load step load_step:", "load_step in LoadStep.instances: load_step_id = str(load_step.get_id()) # TODO: should be", "{' '.join([str(x) for x in force.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1", "not possible rn. spc_loadCollector = load_step.spc_loadCollector load_loadCollector = load_step.load_loadCollector spc_loadCollector_id", "and Constraints Parameters: --------- None \"\"\" def __init__(self) -> None:", "{spc.dofs[3]} {spc.dofs[4]} {spc.dofs[5]} 0 0 0 0 0\") tcl_commands.append(\"*createmark loads", "load_step.load_loadCollector spc_loadCollector_id = str(spc_loadCollector.get_id()) load_loadCollector_id = str(load_loadCollector.get_id()) tcl_commands.append( f\"*createmark loadcols", "collector - not possible rn. spc_loadCollector = load_step.spc_loadCollector load_loadCollector =", "-> None: pass def write_tcl_commands_loadCollectors(self, tcl_commands: List) -> None: \"\"\"", "{load_step_id} 707 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id}", "- not possible rn. spc_loadCollector = load_step.spc_loadCollector load_loadCollector = load_step.load_loadCollector", "1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2396 1", "--------- None \"\"\" def __init__(self) -> None: pass def write_tcl_commands_loadCollectors(self,", "tcl_commands.append( f\"*createmark loadcols 1 \\\"{spc_loadCollector.name}\\\" \\\"{load_loadCollector.name}\\\"\") tcl_commands.append(\"*createmark outputblocks 1\") tcl_commands.append(\"*createmark", "str(load_step.get_id()) # TODO: should be possible to just use a", "load in load_collector.loads: if load_collector_type == Force: force: Force =", "0 0 0\") tcl_commands.append(\"*createmark loads 0 1\") tcl_commands.append(\"*loadsupdatefixedvalue 0 0\")", "nodes 1 1 1 {force.x} {force.y} {force.z} 0 {force.x} {force.y}", "def write_tcl_commands_loadCollectors(self, tcl_commands: List) -> None: \"\"\" Creates all the", "def __init__(self) -> None: pass def write_tcl_commands_loadCollectors(self, tcl_commands: List) ->", "f\"*attributeupdateint loadsteps {load_step_id} 3800 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint", "0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 707 1 1 0", "__init__(self) -> None: pass def write_tcl_commands_loadCollectors(self, tcl_commands: List) -> None:", "creating loadsteps, as the loadcollectors are referenced) \"\"\" load_collector: LoadCollector", "in spc.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 3 1 {spc.dofs[0]} {spc.dofs[1]}", "import Force from BridgeOptimizer.datastructure.hypermesh.SPC import SPC class ScriptBuilderBoundaryConditions: \"\"\" Extra", "in load_collector.loads: if load_collector_type == Force: force: Force = load", "should be possible to just use a spc collector -", "load_loadCollector_id = str(load_loadCollector.get_id()) tcl_commands.append( f\"*createmark loadcols 1 \\\"{spc_loadCollector.name}\\\" \\\"{load_loadCollector.name}\\\"\") tcl_commands.append(\"*createmark", "{load_step_id} 4143 1 1 0 1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id}", "1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 10212 1", "LoadStep = None for load_step in LoadStep.instances: load_step_id = str(load_step.get_id())", "f\"*createmark nodes 1 {' '.join([str(x) for x in spc.nodeIds])}\") tcl_commands.append(", "8134 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2160", "= load_step.load_loadCollector spc_loadCollector_id = str(spc_loadCollector.get_id()) load_loadCollector_id = str(load_loadCollector.get_id()) tcl_commands.append( f\"*createmark", "loadsteps {load_step_id} 4709 1 1 0 1\") tcl_commands.append( f\"*setvalue loadsteps", "self.write_tcl_commands_loadCollectors(tcl_commands) # create the load step load_step: LoadStep = None", "f\"*loadcreateonentity_curve nodes 1 1 1 {force.x} {force.y} {force.z} 0 {force.x}", "load_collector_type == Force: force: Force = load tcl_commands.append( f\"*createmark nodes", "1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 10212 1 1", "1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 2160 1 1", "None: pass def write_tcl_commands_loadCollectors(self, tcl_commands: List) -> None: \"\"\" Creates", "List, Tuple from BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector from BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep", "f\"*attributeupdateint loadsteps {load_step_id} 4143 1 1 0 1\") tcl_commands.append( f\"*attributeupdateint", "SPC: spc: SPC = load tcl_commands.append( f\"*createmark nodes 1 {'", "4709 1 1 0 1\") tcl_commands.append( f\"*setvalue loadsteps id={load_step_id} STATUS=2", "f\"{str(load_collector_type.__name__)}_{str(load_collector.get_id())}\" tcl_commands.append( f\"*createentity loadcols includeid=0 name=\\\"{load_collector.name}\\\"\") # create loads for", "List) -> None: \"\"\" Creates all the load collectors (has", "0\") elif load_collector_type == SPC: spc: SPC = load tcl_commands.append(", "collectors (has to be done before creating loadsteps, as the", "all load collectors and loads first for load_collector in LoadCollector.instances:", "BridgeOptimizer.datastructure.hypermesh.Force import Force from BridgeOptimizer.datastructure.hypermesh.SPC import SPC class ScriptBuilderBoundaryConditions: \"\"\"", "Single method to write all tcl commands to the file", "create the load step load_step: LoadStep = None for load_step", "{load_step_id} 4147 1 1 0 loadcols {load_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateint loadsteps", "from BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector from BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep from BridgeOptimizer.datastructure.hypermesh.Force", "f\"*attributeupdateint loadsteps {load_step_id} 4709 1 1 0 1\") tcl_commands.append( f\"*setvalue", "0 0 0\") elif load_collector_type == SPC: spc: SPC =", "load_collector.get_load_collector_type() load_collector.name = f\"{str(load_collector_type.__name__)}_{str(load_collector.get_id())}\" tcl_commands.append( f\"*createentity loadcols includeid=0 name=\\\"{load_collector.name}\\\"\") #", "LoadCollector.instances: load_collector_type = load_collector.get_load_collector_type() load_collector.name = f\"{str(load_collector_type.__name__)}_{str(load_collector.get_id())}\" tcl_commands.append( f\"*createentity loadcols", "None # create all load collectors and loads first for", "= str(spc_loadCollector.get_id()) load_loadCollector_id = str(load_loadCollector.get_id()) tcl_commands.append( f\"*createmark loadcols 1 \\\"{spc_loadCollector.name}\\\"", "str(load_loadCollector.get_id()) tcl_commands.append( f\"*createmark loadcols 1 \\\"{spc_loadCollector.name}\\\" \\\"{load_loadCollector.name}\\\"\") tcl_commands.append(\"*createmark outputblocks 1\")", "0 {force.x} {force.y} {force.z} 0 0 0 0\") elif load_collector_type", "Extra class for generating Loadstep, Loadcollectors, Forces and Constraints Parameters:", "to write all tcl commands to the file \"\"\" self.write_tcl_commands_loadCollectors(tcl_commands)", "(has to be done before creating loadsteps, as the loadcollectors", "tcl_commands.append( f\"*setvalue loadsteps id={load_step_id} STATUS=2 4059=1 4060=STATICS\") tcl_commands.append( f\"*attributeupdateentity loadsteps", "import List, Tuple from BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector from BridgeOptimizer.datastructure.hypermesh.LoadStep import", "{spc_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateentity loadsteps {load_step_id} 4147 1 1 0 loadcols", "None for load_step in LoadStep.instances: load_step_id = str(load_step.get_id()) # TODO:", "possible rn. spc_loadCollector = load_step.spc_loadCollector load_loadCollector = load_step.load_loadCollector spc_loadCollector_id =", "tcl_commands: List) -> None: \"\"\" Creates all the load collectors", "0\") def write_tcl_commands_loadsteps(self, tcl_commands: List) -> None: \"\"\" Single method", "loadcols includeid=0 name=\\\"{load_collector.name}\\\"\") # create loads for load in load_collector.loads:", "SPC = load tcl_commands.append( f\"*createmark nodes 1 {' '.join([str(x) for", "tcl_commands.append( f\"*createentity loadcols includeid=0 name=\\\"{load_collector.name}\\\"\") # create loads for load", "Force: force: Force = load tcl_commands.append( f\"*createmark nodes 1 {'", "LoadStep from BridgeOptimizer.datastructure.hypermesh.Force import Force from BridgeOptimizer.datastructure.hypermesh.SPC import SPC class", "# create loads for load in load_collector.loads: if load_collector_type ==", "groups 1\") tcl_commands.append( f\"*loadstepscreate \\\"loadstep_{load_step_id}\\\" 1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id}", "use a spc collector - not possible rn. spc_loadCollector =", "{force.z} 0 0 0 0\") elif load_collector_type == SPC: spc:", "Loadstep, Loadcollectors, Forces and Constraints Parameters: --------- None \"\"\" def", "nodes 1 {' '.join([str(x) for x in force.nodeIds])}\") tcl_commands.append( f\"*loadcreateonentity_curve", "0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 707 1 1 0 0\")", "0 0 0 0\") tcl_commands.append(\"*createmark loads 0 1\") tcl_commands.append(\"*loadsupdatefixedvalue 0", "tcl_commands.append( f\"*loadcreateonentity_curve nodes 1 1 1 {force.x} {force.y} {force.z} 0", "f\"*attributeupdateentity loadsteps {load_step_id} 4147 1 1 0 loadcols {load_loadCollector_id}\") tcl_commands.append(", "referenced) \"\"\" load_collector: LoadCollector = None # create all load", "{load_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 3800 1 1 0 0\")", "\"\"\" load_collector: LoadCollector = None # create all load collectors", "load collectors (has to be done before creating loadsteps, as", "\\\"loadstep_{load_step_id}\\\" 1\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 4143 1 1 0", "\\\"{load_loadCollector.name}\\\"\") tcl_commands.append(\"*createmark outputblocks 1\") tcl_commands.append(\"*createmark groups 1\") tcl_commands.append( f\"*loadstepscreate \\\"loadstep_{load_step_id}\\\"", "all the load collectors (has to be done before creating", "1 0 1\") tcl_commands.append( f\"*setvalue loadsteps id={load_step_id} STATUS=2 4059=1 4060=STATICS\")", "loadsteps {load_step_id} 4147 1 1 0 loadcols {load_loadCollector_id}\") tcl_commands.append( f\"*attributeupdateint", "BridgeOptimizer.datastructure.hypermesh.SPC import SPC class ScriptBuilderBoundaryConditions: \"\"\" Extra class for generating", "2396 1 1 0 0\") tcl_commands.append( f\"*attributeupdateint loadsteps {load_step_id} 8134", "0 0 0 0\") elif load_collector_type == SPC: spc: SPC", "typing import List, Tuple from BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector from BridgeOptimizer.datastructure.hypermesh.LoadStep", "write all tcl commands to the file \"\"\" self.write_tcl_commands_loadCollectors(tcl_commands) #", "= load_step.spc_loadCollector load_loadCollector = load_step.load_loadCollector spc_loadCollector_id = str(spc_loadCollector.get_id()) load_loadCollector_id =" ]
[ "== broj: print(\"Pogodak!\") elif tajniBroj < broj: print(\"Tajni broj je", "else: print(\"Tajni broj je veci od tog broja.\") print(\"Kraj programa\")", "broj: broj = int(input(\"Pogodite tajni broj: \")) if tajniBroj ==", "= 51 broj = 2 while tajniBroj != broj: broj", "je manji od tog broja.\") else: print(\"Tajni broj je veci", "tajniBroj != broj: broj = int(input(\"Pogodite tajni broj: \")) if", "tajniBroj == broj: print(\"Pogodak!\") elif tajniBroj < broj: print(\"Tajni broj", "od tog broja.\") else: print(\"Tajni broj je veci od tog", "broj: \")) if tajniBroj == broj: print(\"Pogodak!\") elif tajniBroj <", "if tajniBroj == broj: print(\"Pogodak!\") elif tajniBroj < broj: print(\"Tajni", "elif tajniBroj < broj: print(\"Tajni broj je manji od tog", "int(input(\"Pogodite tajni broj: \")) if tajniBroj == broj: print(\"Pogodak!\") elif", "tog broja.\") else: print(\"Tajni broj je veci od tog broja.\")", "broj: print(\"Pogodak!\") elif tajniBroj < broj: print(\"Tajni broj je manji", "broja.\") else: print(\"Tajni broj je veci od tog broja.\") print(\"Kraj", "broj: print(\"Tajni broj je manji od tog broja.\") else: print(\"Tajni", "= int(input(\"Pogodite tajni broj: \")) if tajniBroj == broj: print(\"Pogodak!\")", "broj = int(input(\"Pogodite tajni broj: \")) if tajniBroj == broj:", "< broj: print(\"Tajni broj je manji od tog broja.\") else:", "tajni broj: \")) if tajniBroj == broj: print(\"Pogodak!\") elif tajniBroj", "broj = 2 while tajniBroj != broj: broj = int(input(\"Pogodite", "tajniBroj = 51 broj = 2 while tajniBroj != broj:", "!= broj: broj = int(input(\"Pogodite tajni broj: \")) if tajniBroj", "print(\"Pogodak!\") elif tajniBroj < broj: print(\"Tajni broj je manji od", "while tajniBroj != broj: broj = int(input(\"Pogodite tajni broj: \"))", "51 broj = 2 while tajniBroj != broj: broj =", "= 2 while tajniBroj != broj: broj = int(input(\"Pogodite tajni", "broj je manji od tog broja.\") else: print(\"Tajni broj je", "print(\"Tajni broj je manji od tog broja.\") else: print(\"Tajni broj", "\")) if tajniBroj == broj: print(\"Pogodak!\") elif tajniBroj < broj:", "2 while tajniBroj != broj: broj = int(input(\"Pogodite tajni broj:", "tajniBroj < broj: print(\"Tajni broj je manji od tog broja.\")", "manji od tog broja.\") else: print(\"Tajni broj je veci od" ]
[ "modify data samples np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(y_train, y_train_before) self.assertPickledNetwork(cmac,", "= np.array([[1, 2, 3]]).T cmac.train(data, target, epochs=100) self.assertInvalidVectorPred( network=cmac, input_vector=np.array([1,", "2 * np.pi, 100), (100, 1)) X_train_before = X_train.copy() X_test", "np.reshape(np.linspace(0, 2 * np.pi, 100), (100, 1)) X_train_before = X_train.copy()", "associative_unit_size=32, step=0.2, ) cmac.train(X_train, y_train, X_test, y_test, epochs=100) predicted_test =", "data = np.array([[1, 2, 3]]).T target = np.array([[1, 2, 3]]).T", ") def test_predict_different_inputs(self): cmac = algorithms.CMAC() data = np.array([[1, 2,", "X_train = np.vstack([X_train, X_train]) X_test = np.linspace(0, 2 * np.pi,", "network=cmac, input_vector=np.array([1, 2, 3]), target=target, decimal=2 ) def test_cmac_multi_output(self): X_train", "* np.pi, 50), (50, 1)) y_train = np.sin(X_train) y_train_before =", "decimal=2 ) def test_cmac_multi_output(self): X_train = np.linspace(0, 2 * np.pi,", "Test that algorithm didn't modify data samples np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(X_train,", ") cmac.train(X_train, y_train, X_test, y_test, epochs=100) predicted_test = cmac.predict(X_test) error", "(100, 1)) X_train_before = X_train.copy() X_test = np.reshape(np.linspace(np.pi, 2 *", "X_test = np.linspace(0, 2 * np.pi, 100) X_test = np.vstack([X_test,", "100) X_train = np.vstack([X_train, X_train]) X_test = np.linspace(0, 2 *", "# Test that algorithm didn't modify data samples np.testing.assert_array_equal(X_train, X_train_before)", "class CMACTestCase(BaseTestCase): def test_cmac(self): X_train = np.reshape(np.linspace(0, 2 * np.pi,", "BaseTestCase class CMACTestCase(BaseTestCase): def test_cmac(self): X_train = np.reshape(np.linspace(0, 2 *", "2, 3]]).T cmac.train(data, target, epochs=100) self.assertInvalidVectorPred( network=cmac, input_vector=np.array([1, 2, 3]),", "= np.reshape(np.linspace(np.pi, 2 * np.pi, 50), (50, 1)) y_train =", "100) X_test = np.vstack([X_test, X_test]) y_train = np.sin(X_train) y_test =", "associative_unit_size=32, step=0.2, verbose=False, ) cmac.train(X_train, y_train, epochs=100) predicted_test = cmac.predict(X_test)", "sklearn import metrics from neupy import algorithms from base import", "samples np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(y_train, y_train_before) self.assertPickledNetwork(cmac, X_train) def", "X_test]) y_train = np.sin(X_train) y_test = np.sin(X_test) cmac = algorithms.CMAC(", "y_train_before = y_train.copy() y_test = np.sin(X_test) cmac = algorithms.CMAC( quantization=100,", "from base import BaseTestCase class CMACTestCase(BaseTestCase): def test_cmac(self): X_train =", "np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(y_train, y_train_before) self.assertPickledNetwork(cmac, X_train) def test_train_different_inputs(self):", "y_train, X_test, y_test, epochs=100) predicted_test = cmac.predict(X_test) error = metrics.mean_absolute_error(y_test,", "np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(y_train, y_train_before) self.assertPickledNetwork(cmac, X_train) def test_train_different_inputs(self): self.assertInvalidVectorTrain( network=algorithms.CMAC(),", "def test_predict_different_inputs(self): cmac = algorithms.CMAC() data = np.array([[1, 2, 3]]).T", "as np from sklearn import metrics from neupy import algorithms", "100), (100, 1)) X_train_before = X_train.copy() X_test = np.reshape(np.linspace(np.pi, 2", "2, 3]]).T target = np.array([[1, 2, 3]]).T cmac.train(data, target, epochs=100)", "= np.sin(X_train) y_train_before = y_train.copy() y_test = np.sin(X_test) cmac =", "predicted_test = cmac.predict(X_test) predicted_test = predicted_test.reshape((len(predicted_test), 1)) error = metrics.mean_absolute_error(y_test,", "target=np.array([1, 2, 3]) ) def test_predict_different_inputs(self): cmac = algorithms.CMAC() data", "CMACTestCase(BaseTestCase): def test_cmac(self): X_train = np.reshape(np.linspace(0, 2 * np.pi, 100),", "50), (50, 1)) y_train = np.sin(X_train) y_train_before = y_train.copy() y_test", "self.assertAlmostEqual(error, 0.0024, places=4) # Test that algorithm didn't modify data", "cmac.predict(X_test) error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0, places=6) def test_cmac_training_exceptions(self):", "places=4) # Test that algorithm didn't modify data samples np.testing.assert_array_equal(X_train,", "y_test, epochs=100) predicted_test = cmac.predict(X_test) error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error,", "test_cmac_training_exceptions(self): cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, ) with self.assertRaises(ValueError):", "1)) error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0.0024, places=4) # Test", "numpy as np from sklearn import metrics from neupy import", "def test_cmac_multi_output(self): X_train = np.linspace(0, 2 * np.pi, 100) X_train", "that algorithm didn't modify data samples np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(X_train, X_train_before)", "error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0, places=6) def test_cmac_training_exceptions(self): cmac", "X_train_before) np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(y_train, y_train_before) self.assertPickledNetwork(cmac, X_train) def test_train_different_inputs(self): self.assertInvalidVectorTrain(", "* np.pi, 100) X_train = np.vstack([X_train, X_train]) X_test = np.linspace(0,", "= y_train.copy() y_test = np.sin(X_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32,", "np.pi, 50), (50, 1)) y_train = np.sin(X_train) y_train_before = y_train.copy()", "1)) y_train = np.sin(X_train) y_train_before = y_train.copy() y_test = np.sin(X_test)", "np.array([[1, 2, 3]]).T cmac.train(data, target, epochs=100) self.assertInvalidVectorPred( network=cmac, input_vector=np.array([1, 2,", "np.vstack([X_train, X_train]) X_test = np.linspace(0, 2 * np.pi, 100) X_test", "X_train]) X_test = np.linspace(0, 2 * np.pi, 100) X_test =", "cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, ) with self.assertRaises(ValueError): cmac.train(X_train=True,", "X_train = np.linspace(0, 2 * np.pi, 100) X_train = np.vstack([X_train,", "= predicted_test.reshape((len(predicted_test), 1)) error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0.0024, places=4)", "np.sin(X_train) y_test = np.sin(X_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2,", "test_train_different_inputs(self): self.assertInvalidVectorTrain( network=algorithms.CMAC(), input_vector=np.array([1, 2, 3]), target=np.array([1, 2, 3]) )", "= np.sin(X_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, verbose=False, )", "= np.linspace(0, 2 * np.pi, 100) X_test = np.vstack([X_test, X_test])", "self.assertPickledNetwork(cmac, X_train) def test_train_different_inputs(self): self.assertInvalidVectorTrain( network=algorithms.CMAC(), input_vector=np.array([1, 2, 3]), target=np.array([1,", "data samples np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(y_train, y_train_before) self.assertPickledNetwork(cmac, X_train)", "cmac.train(X_train, y_train, epochs=100) predicted_test = cmac.predict(X_test) predicted_test = predicted_test.reshape((len(predicted_test), 1))", "np.reshape(np.linspace(np.pi, 2 * np.pi, 50), (50, 1)) y_train = np.sin(X_train)", "X_train) def test_train_different_inputs(self): self.assertInvalidVectorTrain( network=algorithms.CMAC(), input_vector=np.array([1, 2, 3]), target=np.array([1, 2,", "0.0024, places=4) # Test that algorithm didn't modify data samples", "def test_train_different_inputs(self): self.assertInvalidVectorTrain( network=algorithms.CMAC(), input_vector=np.array([1, 2, 3]), target=np.array([1, 2, 3])", "2 * np.pi, 100) X_train = np.vstack([X_train, X_train]) X_test =", "np.sin(X_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, verbose=False, ) cmac.train(X_train,", "np.sin(X_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, ) cmac.train(X_train, y_train,", "(50, 1)) y_train = np.sin(X_train) y_train_before = y_train.copy() y_test =", "= metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0, places=6) def test_cmac_training_exceptions(self): cmac =", "target = np.array([[1, 2, 3]]).T cmac.train(data, target, epochs=100) self.assertInvalidVectorPred( network=cmac,", "X_train.copy() X_test = np.reshape(np.linspace(np.pi, 2 * np.pi, 50), (50, 1))", "np from sklearn import metrics from neupy import algorithms from", "X_train_before = X_train.copy() X_test = np.reshape(np.linspace(np.pi, 2 * np.pi, 50),", "step=0.2, ) cmac.train(X_train, y_train, X_test, y_test, epochs=100) predicted_test = cmac.predict(X_test)", "y_test = np.sin(X_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, )", "np.linspace(0, 2 * np.pi, 100) X_train = np.vstack([X_train, X_train]) X_test", "0, places=6) def test_cmac_training_exceptions(self): cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2,", "= cmac.predict(X_test) predicted_test = predicted_test.reshape((len(predicted_test), 1)) error = metrics.mean_absolute_error(y_test, predicted_test)", "X_test = np.vstack([X_test, X_test]) y_train = np.sin(X_train) y_test = np.sin(X_test)", "algorithms.CMAC() data = np.array([[1, 2, 3]]).T target = np.array([[1, 2,", "1)) X_train_before = X_train.copy() X_test = np.reshape(np.linspace(np.pi, 2 * np.pi,", "= algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, ) cmac.train(X_train, y_train, X_test, y_test,", "<gh_stars>100-1000 import numpy as np from sklearn import metrics from", "quantization=100, associative_unit_size=32, step=0.2, ) with self.assertRaises(ValueError): cmac.train(X_train=True, y_train=True, X_test=None, y_test=True)", "np.pi, 100) X_test = np.vstack([X_test, X_test]) y_train = np.sin(X_train) y_test", "algorithms from base import BaseTestCase class CMACTestCase(BaseTestCase): def test_cmac(self): X_train", "quantization=100, associative_unit_size=32, step=0.2, verbose=False, ) cmac.train(X_train, y_train, epochs=100) predicted_test =", "* np.pi, 100) X_test = np.vstack([X_test, X_test]) y_train = np.sin(X_train)", "algorithm didn't modify data samples np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(y_train,", "X_test = np.reshape(np.linspace(np.pi, 2 * np.pi, 50), (50, 1)) y_train", "y_train = np.sin(X_train) y_test = np.sin(X_test) cmac = algorithms.CMAC( quantization=100,", "target, epochs=100) self.assertInvalidVectorPred( network=cmac, input_vector=np.array([1, 2, 3]), target=target, decimal=2 )", "= np.sin(X_train) y_test = np.sin(X_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32,", "epochs=100) predicted_test = cmac.predict(X_test) error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0,", "np.array([[1, 2, 3]]).T target = np.array([[1, 2, 3]]).T cmac.train(data, target,", "base import BaseTestCase class CMACTestCase(BaseTestCase): def test_cmac(self): X_train = np.reshape(np.linspace(0,", "def test_cmac(self): X_train = np.reshape(np.linspace(0, 2 * np.pi, 100), (100,", "verbose=False, ) cmac.train(X_train, y_train, epochs=100) predicted_test = cmac.predict(X_test) predicted_test =", "cmac = algorithms.CMAC() data = np.array([[1, 2, 3]]).T target =", "predicted_test = predicted_test.reshape((len(predicted_test), 1)) error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0.0024,", "3]) ) def test_predict_different_inputs(self): cmac = algorithms.CMAC() data = np.array([[1,", "predicted_test = cmac.predict(X_test) error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0, places=6)", "error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0.0024, places=4) # Test that", "3]]).T cmac.train(data, target, epochs=100) self.assertInvalidVectorPred( network=cmac, input_vector=np.array([1, 2, 3]), target=target,", "def test_cmac_training_exceptions(self): cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, ) with", "= algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, ) with self.assertRaises(ValueError): cmac.train(X_train=True, y_train=True,", "self.assertInvalidVectorPred( network=cmac, input_vector=np.array([1, 2, 3]), target=target, decimal=2 ) def test_cmac_multi_output(self):", "self.assertAlmostEqual(error, 0, places=6) def test_cmac_training_exceptions(self): cmac = algorithms.CMAC( quantization=100, associative_unit_size=32,", "= algorithms.CMAC() data = np.array([[1, 2, 3]]).T target = np.array([[1,", "np.linspace(0, 2 * np.pi, 100) X_test = np.vstack([X_test, X_test]) y_train", "input_vector=np.array([1, 2, 3]), target=target, decimal=2 ) def test_cmac_multi_output(self): X_train =", "from neupy import algorithms from base import BaseTestCase class CMACTestCase(BaseTestCase):", "import BaseTestCase class CMACTestCase(BaseTestCase): def test_cmac(self): X_train = np.reshape(np.linspace(0, 2", "y_train, epochs=100) predicted_test = cmac.predict(X_test) predicted_test = predicted_test.reshape((len(predicted_test), 1)) error", "cmac.train(data, target, epochs=100) self.assertInvalidVectorPred( network=cmac, input_vector=np.array([1, 2, 3]), target=target, decimal=2", "cmac.train(X_train, y_train, X_test, y_test, epochs=100) predicted_test = cmac.predict(X_test) error =", "np.pi, 100), (100, 1)) X_train_before = X_train.copy() X_test = np.reshape(np.linspace(np.pi,", "algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, ) with self.assertRaises(ValueError): cmac.train(X_train=True, y_train=True, X_test=None,", "= np.sin(X_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, ) cmac.train(X_train,", "metrics from neupy import algorithms from base import BaseTestCase class", "= np.array([[1, 2, 3]]).T target = np.array([[1, 2, 3]]).T cmac.train(data,", "= np.linspace(0, 2 * np.pi, 100) X_train = np.vstack([X_train, X_train])", "X_train_before) np.testing.assert_array_equal(y_train, y_train_before) self.assertPickledNetwork(cmac, X_train) def test_train_different_inputs(self): self.assertInvalidVectorTrain( network=algorithms.CMAC(), input_vector=np.array([1,", "import numpy as np from sklearn import metrics from neupy", "test_predict_different_inputs(self): cmac = algorithms.CMAC() data = np.array([[1, 2, 3]]).T target", "self.assertInvalidVectorTrain( network=algorithms.CMAC(), input_vector=np.array([1, 2, 3]), target=np.array([1, 2, 3]) ) def", "np.pi, 100) X_train = np.vstack([X_train, X_train]) X_test = np.linspace(0, 2", "2 * np.pi, 50), (50, 1)) y_train = np.sin(X_train) y_train_before", "= np.vstack([X_test, X_test]) y_train = np.sin(X_train) y_test = np.sin(X_test) cmac", "import metrics from neupy import algorithms from base import BaseTestCase", "y_train = np.sin(X_train) y_train_before = y_train.copy() y_test = np.sin(X_test) cmac", "epochs=100) predicted_test = cmac.predict(X_test) predicted_test = predicted_test.reshape((len(predicted_test), 1)) error =", "algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, ) cmac.train(X_train, y_train, X_test, y_test, epochs=100)", "= cmac.predict(X_test) error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0, places=6) def", ") cmac.train(X_train, y_train, epochs=100) predicted_test = cmac.predict(X_test) predicted_test = predicted_test.reshape((len(predicted_test),", "import algorithms from base import BaseTestCase class CMACTestCase(BaseTestCase): def test_cmac(self):", "= np.vstack([X_train, X_train]) X_test = np.linspace(0, 2 * np.pi, 100)", "epochs=100) self.assertInvalidVectorPred( network=cmac, input_vector=np.array([1, 2, 3]), target=target, decimal=2 ) def", "y_train.copy() y_test = np.sin(X_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2,", "cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, ) cmac.train(X_train, y_train, X_test,", "test_cmac_multi_output(self): X_train = np.linspace(0, 2 * np.pi, 100) X_train =", "predicted_test) self.assertAlmostEqual(error, 0.0024, places=4) # Test that algorithm didn't modify", "y_test = np.sin(X_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, verbose=False,", "2, 3]), target=np.array([1, 2, 3]) ) def test_predict_different_inputs(self): cmac =", "X_test, y_test, epochs=100) predicted_test = cmac.predict(X_test) error = metrics.mean_absolute_error(y_test, predicted_test)", "3]), target=np.array([1, 2, 3]) ) def test_predict_different_inputs(self): cmac = algorithms.CMAC()", "places=6) def test_cmac_training_exceptions(self): cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, )", "= algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, verbose=False, ) cmac.train(X_train, y_train, epochs=100)", ") def test_cmac_multi_output(self): X_train = np.linspace(0, 2 * np.pi, 100)", "test_cmac(self): X_train = np.reshape(np.linspace(0, 2 * np.pi, 100), (100, 1))", "predicted_test.reshape((len(predicted_test), 1)) error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0.0024, places=4) #", "np.vstack([X_test, X_test]) y_train = np.sin(X_train) y_test = np.sin(X_test) cmac =", "cmac.predict(X_test) predicted_test = predicted_test.reshape((len(predicted_test), 1)) error = metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error,", "quantization=100, associative_unit_size=32, step=0.2, ) cmac.train(X_train, y_train, X_test, y_test, epochs=100) predicted_test", "input_vector=np.array([1, 2, 3]), target=np.array([1, 2, 3]) ) def test_predict_different_inputs(self): cmac", "np.testing.assert_array_equal(y_train, y_train_before) self.assertPickledNetwork(cmac, X_train) def test_train_different_inputs(self): self.assertInvalidVectorTrain( network=algorithms.CMAC(), input_vector=np.array([1, 2,", "2 * np.pi, 100) X_test = np.vstack([X_test, X_test]) y_train =", "= np.reshape(np.linspace(0, 2 * np.pi, 100), (100, 1)) X_train_before =", "2, 3]), target=target, decimal=2 ) def test_cmac_multi_output(self): X_train = np.linspace(0,", "= X_train.copy() X_test = np.reshape(np.linspace(np.pi, 2 * np.pi, 50), (50,", "metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0, places=6) def test_cmac_training_exceptions(self): cmac = algorithms.CMAC(", "neupy import algorithms from base import BaseTestCase class CMACTestCase(BaseTestCase): def", "network=algorithms.CMAC(), input_vector=np.array([1, 2, 3]), target=np.array([1, 2, 3]) ) def test_predict_different_inputs(self):", "3]]).T target = np.array([[1, 2, 3]]).T cmac.train(data, target, epochs=100) self.assertInvalidVectorPred(", "didn't modify data samples np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(X_train, X_train_before) np.testing.assert_array_equal(y_train, y_train_before)", "y_train_before) self.assertPickledNetwork(cmac, X_train) def test_train_different_inputs(self): self.assertInvalidVectorTrain( network=algorithms.CMAC(), input_vector=np.array([1, 2, 3]),", "predicted_test) self.assertAlmostEqual(error, 0, places=6) def test_cmac_training_exceptions(self): cmac = algorithms.CMAC( quantization=100,", "step=0.2, verbose=False, ) cmac.train(X_train, y_train, epochs=100) predicted_test = cmac.predict(X_test) predicted_test", "from sklearn import metrics from neupy import algorithms from base", "metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0.0024, places=4) # Test that algorithm didn't", "2, 3]) ) def test_predict_different_inputs(self): cmac = algorithms.CMAC() data =", "3]), target=target, decimal=2 ) def test_cmac_multi_output(self): X_train = np.linspace(0, 2", "cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, verbose=False, ) cmac.train(X_train, y_train,", "X_train = np.reshape(np.linspace(0, 2 * np.pi, 100), (100, 1)) X_train_before", "np.sin(X_train) y_train_before = y_train.copy() y_test = np.sin(X_test) cmac = algorithms.CMAC(", "* np.pi, 100), (100, 1)) X_train_before = X_train.copy() X_test =", "= metrics.mean_absolute_error(y_test, predicted_test) self.assertAlmostEqual(error, 0.0024, places=4) # Test that algorithm", "target=target, decimal=2 ) def test_cmac_multi_output(self): X_train = np.linspace(0, 2 *", "algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, verbose=False, ) cmac.train(X_train, y_train, epochs=100) predicted_test" ]
[ "not None else None self.object_type = value.__class__.__name__ if value is", "joinstr = 'and_(foreign(TaskGroupObject.object_id) == {type}.id, '\\ 'foreign(TaskGroupObject.object_type) == \"{type}\")' joinstr", "'task_group', 'object_id', 'object_type' ] target = self.copy_into(_other, columns, **kwargs) return", "\\ else None return setattr(self, self.object_attr, value) @staticmethod def _extra_table_args(cls):", "'task_group', creator=lambda task_group: TaskGroupObject( task_group=task_group, object_type=cls.__name__, ) ) joinstr =", "import db from ggrc.models.mixins import Mapping from ggrc.models.mixins import Timeboxed", "return target class TaskGroupable(object): @classmethod def late_init_task_groupable(cls): def make_task_group_objects(cls): cls.task_groups", "None else None self.object_type = value.__class__.__name__ if value is not", "<see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>", "association_proxy( 'task_group_objects', 'task_group', creator=lambda task_group: TaskGroupObject( task_group=task_group, object_type=cls.__name__, ) )", "def make_task_group_objects(cls): cls.task_groups = association_proxy( 'task_group_objects', 'task_group', creator=lambda task_group: TaskGroupObject(", "joinstr.format(type=cls.__name__) return db.relationship( 'TaskGroupObject', primaryjoin=joinstr, backref='{0}_object'.format(cls.__name__), cascade='all, delete-orphan', ) cls.task_group_objects", "Mapping, db.Model): __tablename__ = 'task_group_objects' task_group_id = db.Column( db.Integer, db.ForeignKey('task_groups.id'),", "_display_name(self): return self.object.display_name + '<->' + self.task_group.display_name def copy(self, _other=None,", "not None \\ else None return setattr(self, self.object_attr, value) @staticmethod", "@property def object(self): return getattr(self, self.object_attr) @object.setter def object(self, value):", "'{0}_object'.format(self.object_type) @property def object(self): return getattr(self, self.object_attr) @object.setter def object(self,", "value.id if value is not None else None self.object_type =", "+ '<->' + self.task_group.display_name def copy(self, _other=None, **kwargs): columns =", "if value is not None \\ else None return setattr(self,", "Google Inc., authors, and contributors <see AUTHORS file> # Licensed", "<EMAIL> # Maintained By: <EMAIL> from sqlalchemy.ext.associationproxy import association_proxy from", "@staticmethod def _extra_table_args(cls): return ( db.UniqueConstraint('task_group_id', 'object_id', 'object_type'), db.Index('ix_task_group_id', 'task_group_id'),", "@classmethod def eager_query(cls): from sqlalchemy import orm query = super(TaskGroupable,", "db.Index('ix_task_group_id', 'task_group_id'), ) _publish_attrs = [ 'task_group', 'object', ] _sanitize_html", "def object(self): return getattr(self, self.object_attr) @object.setter def object(self, value): self.object_id", "'task_group', 'object', ] _sanitize_html = [] @classmethod def eager_query(cls): from", "return db.relationship( 'TaskGroupObject', primaryjoin=joinstr, backref='{0}_object'.format(cls.__name__), cascade='all, delete-orphan', ) cls.task_group_objects =", ") _publish_attrs = [ 'task_group', 'object', ] _sanitize_html = []", "'TaskGroupObject', primaryjoin=joinstr, backref='{0}_object'.format(cls.__name__), cascade='all, delete-orphan', ) cls.task_group_objects = make_task_group_objects(cls) _publish_attrs", "_include_links = [] @classmethod def eager_query(cls): from sqlalchemy import orm", "2013 Google Inc., authors, and contributors <see AUTHORS file> #", "+ self.task_group.display_name def copy(self, _other=None, **kwargs): columns = [ 'task_group',", "# Maintained By: <EMAIL> from sqlalchemy.ext.associationproxy import association_proxy from ggrc", "def copy(self, _other=None, **kwargs): columns = [ 'task_group', 'object_id', 'object_type'", "def late_init_task_groupable(cls): def make_task_group_objects(cls): cls.task_groups = association_proxy( 'task_group_objects', 'task_group', creator=lambda", "'\\ 'foreign(TaskGroupObject.object_type) == \"{type}\")' joinstr = joinstr.format(type=cls.__name__) return db.relationship( 'TaskGroupObject',", "LICENSE file> # Created By: <EMAIL> # Maintained By: <EMAIL>", "db.UniqueConstraint('task_group_id', 'object_id', 'object_type'), db.Index('ix_task_group_id', 'task_group_id'), ) _publish_attrs = [ 'task_group',", "query.options( orm.subqueryload('task_group')) def _display_name(self): return self.object.display_name + '<->' + self.task_group.display_name", "= [ PublishOnly('task_groups'), 'task_group_objects', ] _include_links = [] @classmethod def", "object_type=cls.__name__, ) ) joinstr = 'and_(foreign(TaskGroupObject.object_id) == {type}.id, '\\ 'foreign(TaskGroupObject.object_type)", "db.relationship( 'TaskGroupObject', primaryjoin=joinstr, backref='{0}_object'.format(cls.__name__), cascade='all, delete-orphan', ) cls.task_group_objects = make_task_group_objects(cls)", "] _include_links = [] @classmethod def eager_query(cls): from sqlalchemy import", "from sqlalchemy import orm query = super(TaskGroupable, cls).eager_query() return cls.eager_inclusions(query,", "'object_id', 'object_type' ] target = self.copy_into(_other, columns, **kwargs) return target", "'object_id', 'object_type'), db.Index('ix_task_group_id', 'task_group_id'), ) _publish_attrs = [ 'task_group', 'object',", "PublishOnly class TaskGroupObject(Timeboxed, Mapping, db.Model): __tablename__ = 'task_group_objects' task_group_id =", "return self.object.display_name + '<->' + self.task_group.display_name def copy(self, _other=None, **kwargs):", "'task_group_objects' task_group_id = db.Column( db.Integer, db.ForeignKey('task_groups.id'), nullable=False) object_id = db.Column(db.Integer,", "sqlalchemy import orm query = super(TaskGroupable, cls).eager_query() return cls.eager_inclusions(query, TaskGroupable._include_links).options(", "**kwargs) return target class TaskGroupable(object): @classmethod def late_init_task_groupable(cls): def make_task_group_objects(cls):", "from ggrc import db from ggrc.models.mixins import Mapping from ggrc.models.mixins", "= joinstr.format(type=cls.__name__) return db.relationship( 'TaskGroupObject', primaryjoin=joinstr, backref='{0}_object'.format(cls.__name__), cascade='all, delete-orphan', )", "= make_task_group_objects(cls) _publish_attrs = [ PublishOnly('task_groups'), 'task_group_objects', ] _include_links =", "task_group=task_group, object_type=cls.__name__, ) ) joinstr = 'and_(foreign(TaskGroupObject.object_id) == {type}.id, '\\", "db.Column( db.Integer, db.ForeignKey('task_groups.id'), nullable=False) object_id = db.Column(db.Integer, nullable=False) object_type =", "= [ 'task_group', 'object', ] _sanitize_html = [] @classmethod def", "task_group_id = db.Column( db.Integer, db.ForeignKey('task_groups.id'), nullable=False) object_id = db.Column(db.Integer, nullable=False)", "from ggrc.models.mixins import Mapping from ggrc.models.mixins import Timeboxed from ggrc.models.reflection", "file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created", "None self.object_type = value.__class__.__name__ if value is not None \\", "self.object.display_name + '<->' + self.task_group.display_name def copy(self, _other=None, **kwargs): columns", "= value.__class__.__name__ if value is not None \\ else None", "value is not None \\ else None return setattr(self, self.object_attr,", "ggrc.models.mixins import Mapping from ggrc.models.mixins import Timeboxed from ggrc.models.reflection import", "return '{0}_object'.format(self.object_type) @property def object(self): return getattr(self, self.object_attr) @object.setter def", "= db.Column( db.Integer, db.ForeignKey('task_groups.id'), nullable=False) object_id = db.Column(db.Integer, nullable=False) object_type", "<see LICENSE file> # Created By: <EMAIL> # Maintained By:", "'<->' + self.task_group.display_name def copy(self, _other=None, **kwargs): columns = [", "query = super(TaskGroupObject, cls).eager_query() return query.options( orm.subqueryload('task_group')) def _display_name(self): return", "return getattr(self, self.object_attr) @object.setter def object(self, value): self.object_id = value.id", "= db.Column(db.Integer, nullable=False) object_type = db.Column(db.String, nullable=False) @property def object_attr(self):", "eager_query(cls): from sqlalchemy import orm query = super(TaskGroupObject, cls).eager_query() return", "is not None else None self.object_type = value.__class__.__name__ if value", "Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS", "By: <EMAIL> from sqlalchemy.ext.associationproxy import association_proxy from ggrc import db", "import Timeboxed from ggrc.models.reflection import PublishOnly class TaskGroupObject(Timeboxed, Mapping, db.Model):", "_publish_attrs = [ 'task_group', 'object', ] _sanitize_html = [] @classmethod", "db.Model): __tablename__ = 'task_group_objects' task_group_id = db.Column( db.Integer, db.ForeignKey('task_groups.id'), nullable=False)", "value) @staticmethod def _extra_table_args(cls): return ( db.UniqueConstraint('task_group_id', 'object_id', 'object_type'), db.Index('ix_task_group_id',", "def object_attr(self): return '{0}_object'.format(self.object_type) @property def object(self): return getattr(self, self.object_attr)", "self.task_group.display_name def copy(self, _other=None, **kwargs): columns = [ 'task_group', 'object_id',", "joinstr = joinstr.format(type=cls.__name__) return db.relationship( 'TaskGroupObject', primaryjoin=joinstr, backref='{0}_object'.format(cls.__name__), cascade='all, delete-orphan',", "orm.subqueryload('task_group')) def _display_name(self): return self.object.display_name + '<->' + self.task_group.display_name def", "target = self.copy_into(_other, columns, **kwargs) return target class TaskGroupable(object): @classmethod", "file> # Created By: <EMAIL> # Maintained By: <EMAIL> from", "[ PublishOnly('task_groups'), 'task_group_objects', ] _include_links = [] @classmethod def eager_query(cls):", "db from ggrc.models.mixins import Mapping from ggrc.models.mixins import Timeboxed from", ") ) joinstr = 'and_(foreign(TaskGroupObject.object_id) == {type}.id, '\\ 'foreign(TaskGroupObject.object_type) ==", "import association_proxy from ggrc import db from ggrc.models.mixins import Mapping", "= db.Column(db.String, nullable=False) @property def object_attr(self): return '{0}_object'.format(self.object_type) @property def", "_sanitize_html = [] @classmethod def eager_query(cls): from sqlalchemy import orm", "sqlalchemy import orm query = super(TaskGroupObject, cls).eager_query() return query.options( orm.subqueryload('task_group'))", "By: <EMAIL> # Maintained By: <EMAIL> from sqlalchemy.ext.associationproxy import association_proxy", "db.ForeignKey('task_groups.id'), nullable=False) object_id = db.Column(db.Integer, nullable=False) object_type = db.Column(db.String, nullable=False)", "cls.task_groups = association_proxy( 'task_group_objects', 'task_group', creator=lambda task_group: TaskGroupObject( task_group=task_group, object_type=cls.__name__,", "from ggrc.models.reflection import PublishOnly class TaskGroupObject(Timeboxed, Mapping, db.Model): __tablename__ =", "self.object_type = value.__class__.__name__ if value is not None \\ else", "import Mapping from ggrc.models.mixins import Timeboxed from ggrc.models.reflection import PublishOnly", "= value.id if value is not None else None self.object_type", "'task_group_objects', ] _include_links = [] @classmethod def eager_query(cls): from sqlalchemy", "return query.options( orm.subqueryload('task_group')) def _display_name(self): return self.object.display_name + '<->' +", "import orm query = super(TaskGroupable, cls).eager_query() return cls.eager_inclusions(query, TaskGroupable._include_links).options( orm.subqueryload('task_group_objects'))", "TaskGroupable(object): @classmethod def late_init_task_groupable(cls): def make_task_group_objects(cls): cls.task_groups = association_proxy( 'task_group_objects',", "@classmethod def eager_query(cls): from sqlalchemy import orm query = super(TaskGroupObject,", "TaskGroupObject(Timeboxed, Mapping, db.Model): __tablename__ = 'task_group_objects' task_group_id = db.Column( db.Integer,", "Maintained By: <EMAIL> from sqlalchemy.ext.associationproxy import association_proxy from ggrc import", "# Created By: <EMAIL> # Maintained By: <EMAIL> from sqlalchemy.ext.associationproxy", "value is not None else None self.object_type = value.__class__.__name__ if", "__tablename__ = 'task_group_objects' task_group_id = db.Column( db.Integer, db.ForeignKey('task_groups.id'), nullable=False) object_id", "columns = [ 'task_group', 'object_id', 'object_type' ] target = self.copy_into(_other,", "{type}.id, '\\ 'foreign(TaskGroupObject.object_type) == \"{type}\")' joinstr = joinstr.format(type=cls.__name__) return db.relationship(", "Created By: <EMAIL> # Maintained By: <EMAIL> from sqlalchemy.ext.associationproxy import", "] _sanitize_html = [] @classmethod def eager_query(cls): from sqlalchemy import", "nullable=False) object_type = db.Column(db.String, nullable=False) @property def object_attr(self): return '{0}_object'.format(self.object_type)", "cascade='all, delete-orphan', ) cls.task_group_objects = make_task_group_objects(cls) _publish_attrs = [ PublishOnly('task_groups'),", "import PublishOnly class TaskGroupObject(Timeboxed, Mapping, db.Model): __tablename__ = 'task_group_objects' task_group_id", "'task_group_id'), ) _publish_attrs = [ 'task_group', 'object', ] _sanitize_html =", "http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: <EMAIL> # Maintained", "from sqlalchemy import orm query = super(TaskGroupObject, cls).eager_query() return query.options(", "def object(self, value): self.object_id = value.id if value is not", "# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By:", "sqlalchemy.ext.associationproxy import association_proxy from ggrc import db from ggrc.models.mixins import", "object(self, value): self.object_id = value.id if value is not None", "if value is not None else None self.object_type = value.__class__.__name__", "= super(TaskGroupObject, cls).eager_query() return query.options( orm.subqueryload('task_group')) def _display_name(self): return self.object.display_name", "backref='{0}_object'.format(cls.__name__), cascade='all, delete-orphan', ) cls.task_group_objects = make_task_group_objects(cls) _publish_attrs = [", "_publish_attrs = [ PublishOnly('task_groups'), 'task_group_objects', ] _include_links = [] @classmethod", "return ( db.UniqueConstraint('task_group_id', 'object_id', 'object_type'), db.Index('ix_task_group_id', 'task_group_id'), ) _publish_attrs =", "association_proxy from ggrc import db from ggrc.models.mixins import Mapping from", "from sqlalchemy.ext.associationproxy import association_proxy from ggrc import db from ggrc.models.mixins", "nullable=False) @property def object_attr(self): return '{0}_object'.format(self.object_type) @property def object(self): return", "Timeboxed from ggrc.models.reflection import PublishOnly class TaskGroupObject(Timeboxed, Mapping, db.Model): __tablename__", "= self.copy_into(_other, columns, **kwargs) return target class TaskGroupable(object): @classmethod def", "nullable=False) object_id = db.Column(db.Integer, nullable=False) object_type = db.Column(db.String, nullable=False) @property", "value): self.object_id = value.id if value is not None else", "self.object_attr) @object.setter def object(self, value): self.object_id = value.id if value", "== \"{type}\")' joinstr = joinstr.format(type=cls.__name__) return db.relationship( 'TaskGroupObject', primaryjoin=joinstr, backref='{0}_object'.format(cls.__name__),", "@object.setter def object(self, value): self.object_id = value.id if value is", "ggrc import db from ggrc.models.mixins import Mapping from ggrc.models.mixins import", "getattr(self, self.object_attr) @object.setter def object(self, value): self.object_id = value.id if", "'object', ] _sanitize_html = [] @classmethod def eager_query(cls): from sqlalchemy", "'object_type' ] target = self.copy_into(_other, columns, **kwargs) return target class", "AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> #", "TaskGroupObject( task_group=task_group, object_type=cls.__name__, ) ) joinstr = 'and_(foreign(TaskGroupObject.object_id) == {type}.id,", "def _display_name(self): return self.object.display_name + '<->' + self.task_group.display_name def copy(self,", "# Copyright (C) 2013 Google Inc., authors, and contributors <see", "ggrc.models.reflection import PublishOnly class TaskGroupObject(Timeboxed, Mapping, db.Model): __tablename__ = 'task_group_objects'", "@classmethod def late_init_task_groupable(cls): def make_task_group_objects(cls): cls.task_groups = association_proxy( 'task_group_objects', 'task_group',", "orm query = super(TaskGroupObject, cls).eager_query() return query.options( orm.subqueryload('task_group')) def _display_name(self):", "self.object_id = value.id if value is not None else None", "else None self.object_type = value.__class__.__name__ if value is not None", "target class TaskGroupable(object): @classmethod def late_init_task_groupable(cls): def make_task_group_objects(cls): cls.task_groups =", "db.Column(db.String, nullable=False) @property def object_attr(self): return '{0}_object'.format(self.object_type) @property def object(self):", "def eager_query(cls): from sqlalchemy import orm query = super(TaskGroupObject, cls).eager_query()", "def eager_query(cls): from sqlalchemy import orm query = super(TaskGroupable, cls).eager_query()", "Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: <EMAIL>", "setattr(self, self.object_attr, value) @staticmethod def _extra_table_args(cls): return ( db.UniqueConstraint('task_group_id', 'object_id',", "@property def object_attr(self): return '{0}_object'.format(self.object_type) @property def object(self): return getattr(self,", "authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0", "super(TaskGroupObject, cls).eager_query() return query.options( orm.subqueryload('task_group')) def _display_name(self): return self.object.display_name +", ") joinstr = 'and_(foreign(TaskGroupObject.object_id) == {type}.id, '\\ 'foreign(TaskGroupObject.object_type) == \"{type}\")'", "class TaskGroupObject(Timeboxed, Mapping, db.Model): __tablename__ = 'task_group_objects' task_group_id = db.Column(", "\"{type}\")' joinstr = joinstr.format(type=cls.__name__) return db.relationship( 'TaskGroupObject', primaryjoin=joinstr, backref='{0}_object'.format(cls.__name__), cascade='all,", "'object_type'), db.Index('ix_task_group_id', 'task_group_id'), ) _publish_attrs = [ 'task_group', 'object', ]", "'task_group_objects', 'task_group', creator=lambda task_group: TaskGroupObject( task_group=task_group, object_type=cls.__name__, ) ) joinstr", "Mapping from ggrc.models.mixins import Timeboxed from ggrc.models.reflection import PublishOnly class", "] target = self.copy_into(_other, columns, **kwargs) return target class TaskGroupable(object):", "= association_proxy( 'task_group_objects', 'task_group', creator=lambda task_group: TaskGroupObject( task_group=task_group, object_type=cls.__name__, )", "= [ 'task_group', 'object_id', 'object_type' ] target = self.copy_into(_other, columns,", "class TaskGroupable(object): @classmethod def late_init_task_groupable(cls): def make_task_group_objects(cls): cls.task_groups = association_proxy(", "else None return setattr(self, self.object_attr, value) @staticmethod def _extra_table_args(cls): return", ") cls.task_group_objects = make_task_group_objects(cls) _publish_attrs = [ PublishOnly('task_groups'), 'task_group_objects', ]", "object_id = db.Column(db.Integer, nullable=False) object_type = db.Column(db.String, nullable=False) @property def", "db.Column(db.Integer, nullable=False) object_type = db.Column(db.String, nullable=False) @property def object_attr(self): return", "(C) 2013 Google Inc., authors, and contributors <see AUTHORS file>", "object(self): return getattr(self, self.object_attr) @object.setter def object(self, value): self.object_id =", "value.__class__.__name__ if value is not None \\ else None return", "creator=lambda task_group: TaskGroupObject( task_group=task_group, object_type=cls.__name__, ) ) joinstr = 'and_(foreign(TaskGroupObject.object_id)", "db.Integer, db.ForeignKey('task_groups.id'), nullable=False) object_id = db.Column(db.Integer, nullable=False) object_type = db.Column(db.String,", "eager_query(cls): from sqlalchemy import orm query = super(TaskGroupable, cls).eager_query() return", "PublishOnly('task_groups'), 'task_group_objects', ] _include_links = [] @classmethod def eager_query(cls): from", "= 'and_(foreign(TaskGroupObject.object_id) == {type}.id, '\\ 'foreign(TaskGroupObject.object_type) == \"{type}\")' joinstr =", "'foreign(TaskGroupObject.object_type) == \"{type}\")' joinstr = joinstr.format(type=cls.__name__) return db.relationship( 'TaskGroupObject', primaryjoin=joinstr,", "_other=None, **kwargs): columns = [ 'task_group', 'object_id', 'object_type' ] target", "task_group: TaskGroupObject( task_group=task_group, object_type=cls.__name__, ) ) joinstr = 'and_(foreign(TaskGroupObject.object_id) ==", "import orm query = super(TaskGroupObject, cls).eager_query() return query.options( orm.subqueryload('task_group')) def", "return setattr(self, self.object_attr, value) @staticmethod def _extra_table_args(cls): return ( db.UniqueConstraint('task_group_id',", "= 'task_group_objects' task_group_id = db.Column( db.Integer, db.ForeignKey('task_groups.id'), nullable=False) object_id =", "object_type = db.Column(db.String, nullable=False) @property def object_attr(self): return '{0}_object'.format(self.object_type) @property", "None return setattr(self, self.object_attr, value) @staticmethod def _extra_table_args(cls): return (", "[] @classmethod def eager_query(cls): from sqlalchemy import orm query =", "= [] @classmethod def eager_query(cls): from sqlalchemy import orm query", "self.object_attr, value) @staticmethod def _extra_table_args(cls): return ( db.UniqueConstraint('task_group_id', 'object_id', 'object_type'),", "def _extra_table_args(cls): return ( db.UniqueConstraint('task_group_id', 'object_id', 'object_type'), db.Index('ix_task_group_id', 'task_group_id'), )", "and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see", "under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: <EMAIL> #", "Inc., authors, and contributors <see AUTHORS file> # Licensed under", "'and_(foreign(TaskGroupObject.object_id) == {type}.id, '\\ 'foreign(TaskGroupObject.object_type) == \"{type}\")' joinstr = joinstr.format(type=cls.__name__)", "_extra_table_args(cls): return ( db.UniqueConstraint('task_group_id', 'object_id', 'object_type'), db.Index('ix_task_group_id', 'task_group_id'), ) _publish_attrs", "( db.UniqueConstraint('task_group_id', 'object_id', 'object_type'), db.Index('ix_task_group_id', 'task_group_id'), ) _publish_attrs = [", "cls).eager_query() return query.options( orm.subqueryload('task_group')) def _display_name(self): return self.object.display_name + '<->'", "primaryjoin=joinstr, backref='{0}_object'.format(cls.__name__), cascade='all, delete-orphan', ) cls.task_group_objects = make_task_group_objects(cls) _publish_attrs =", "is not None \\ else None return setattr(self, self.object_attr, value)", "make_task_group_objects(cls): cls.task_groups = association_proxy( 'task_group_objects', 'task_group', creator=lambda task_group: TaskGroupObject( task_group=task_group,", "self.copy_into(_other, columns, **kwargs) return target class TaskGroupable(object): @classmethod def late_init_task_groupable(cls):", "== {type}.id, '\\ 'foreign(TaskGroupObject.object_type) == \"{type}\")' joinstr = joinstr.format(type=cls.__name__) return", "ggrc.models.mixins import Timeboxed from ggrc.models.reflection import PublishOnly class TaskGroupObject(Timeboxed, Mapping,", "[ 'task_group', 'object', ] _sanitize_html = [] @classmethod def eager_query(cls):", "object_attr(self): return '{0}_object'.format(self.object_type) @property def object(self): return getattr(self, self.object_attr) @object.setter", "make_task_group_objects(cls) _publish_attrs = [ PublishOnly('task_groups'), 'task_group_objects', ] _include_links = []", "delete-orphan', ) cls.task_group_objects = make_task_group_objects(cls) _publish_attrs = [ PublishOnly('task_groups'), 'task_group_objects',", "late_init_task_groupable(cls): def make_task_group_objects(cls): cls.task_groups = association_proxy( 'task_group_objects', 'task_group', creator=lambda task_group:", "columns, **kwargs) return target class TaskGroupable(object): @classmethod def late_init_task_groupable(cls): def", "None \\ else None return setattr(self, self.object_attr, value) @staticmethod def", "cls.task_group_objects = make_task_group_objects(cls) _publish_attrs = [ PublishOnly('task_groups'), 'task_group_objects', ] _include_links", "copy(self, _other=None, **kwargs): columns = [ 'task_group', 'object_id', 'object_type' ]", "[ 'task_group', 'object_id', 'object_type' ] target = self.copy_into(_other, columns, **kwargs)", "contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE", "from ggrc.models.mixins import Timeboxed from ggrc.models.reflection import PublishOnly class TaskGroupObject(Timeboxed,", "**kwargs): columns = [ 'task_group', 'object_id', 'object_type' ] target =", "<EMAIL> from sqlalchemy.ext.associationproxy import association_proxy from ggrc import db from" ]
[ "endtask task check0; begin if(RAM_DATA_RW !== Do0) begin $display(\"\\\\n>>Test Failed!", "2**A_W; reg CLK; reg [(SIZE-1):0] WE0; reg EN0; reg ENR;", "= \"\"\" /* An auto generated testbench to verify RAM{word_num}x{word_size}", "WE0 = {SIZE{8'h00}}; end endtask task mem_write_word(input [SIZE*8-1:0] word, input", "& 'hFFFF_FFFC ; RANDOM_BYTE = $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_1(", "2.0 (the \"License\"); # you may not use this file", "wire [(SIZE*8-1):0] Do0; wire [(SIZE*8-1):0] Do1; reg [A_W-1:0] A0, A1,", "[(SIZE*8-1):0] RAM[(M_SZ)-1 : 0]; reg [(SIZE*8-1):0] RAM_DATA_RW; genvar c; generate", "[(SIZE-1):0] WE0; reg EN0; reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0;", "initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}_1RW1R.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}_1RW1R); @(done) $finish; end /* Memory", "i=i+1) begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_1(ADDR & {{SIZE-1{8'hFF}},", "0x%X from %0D\", Do1, addr1); `endif check0(); check1(); end endtask", ".WSIZE(`SIZE)) SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0), .EN1(ENR), .Di0(Di0), .Do0(Do0), .Do1(Do1),", "begin_single_ported_test = \"\"\" initial begin CLK = 0; WE0 =", "Byte Write then Read Phase = 3; `ifdef VERBOSE_1 $display(\"\\\\nFinished", "genvar c; generate for (c=0; c < SIZE; c =", "\"\"\" end_test = \"\"\" end \"\"\" tasks = \"\"\" task", "Do0) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d, Iteration: %0d\", Phase, i);", "// Perform a single word write then read mem_write_word({{SIZE{{8'h90}}}}, 4);", "begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d, Iteration: %0d\", Phase, i); $display(\"Address:", "begin if(RAM_DATA_R !== Do1) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d, Iteration:", "addr); `endif check0(); end endtask task check0; begin if(RAM_DATA_RW !==", "//`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/sky130_fd_sc_hd.v\" // // Temporary override: IcarusVerilog cannot read these", "https://github.com/Cloud-V/DFFRAM for further info. # # Licensed under the Apache", "[(SIZE*8-1):0] Do0; wire [(SIZE*8-1):0] Do1; reg [A_W-1:0] A0, A1, ADDR;", "License. RAM_instantiation = \"\"\" /* An auto generated testbench to", "WE0 = {{SIZE/2{addr[$clog2(SIZE)-1]}},{SIZE/2{~addr[$clog2(SIZE)-1]}}}; Di0 = (hword << (addr[$clog2(SIZE)-1] * (SIZE/2)*8));", "( .CLK(CLK), .WE0(WE0), .EN0(EN0), .EN1(ENR), .Di0(Di0), .Do0(Do0), .Do1(Do1), .A0(A0[A_W-1:$clog2(SIZE)]), .A1(A1[A_W-1:$clog2(SIZE)])", "Write then Read Phase = 2; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase", "begin @(posedge CLK); A0 = addr; WE0 = {SIZE{8'hFF}}; Di0", "start_test_common = \"\"\" always #10 CLK = !CLK; integer i;", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "Iteration: %0d\", Phase, i); $display(\"Address: 0x%X, READ: 0x%X - Should", "\"hd_primitives.v\" `include \"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}; localparam SIZE =", "{word_size}/8 //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/primitives.v\" //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/sky130_fd_sc_hd.v\" // // Temporary override: IcarusVerilog", "from different ports ************************************************************/ // Fill the memory with a", "1; ENR = 1; \"\"\" dual_ported_custom_test = \"\"\" Phase =", "= addr; WE0 = {SIZE{8'hFF}}; Di0 = word; @(posedge CLK);", "= \"\"\" Phase = 0; // Perform a single word", "(<EMAIL>) <NAME> (<EMAIL>) */ `define VERBOSE_1 `define VERBOSE_2 `define UNIT_DELAY", "endgenerate \"\"\" begin_single_ported_test = \"\"\" initial begin CLK = 0;", "VERBOSE_1 $display(\"\\\\nFinished Phase 5, starting Phase 6\"); `endif for(i=0; i<M_SZ;", "<NAME> (<EMAIL>) <NAME> (<EMAIL>) */ `define VERBOSE_1 `define VERBOSE_2 `define", "[A_W-1:0] A0, ADDR; reg [7:0] Phase; reg [7:0] RANDOM_BYTE; event", "the memory with a known pattern // Word Write then", "reason ^ `include \"hd_primitives.v\" `include \"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}_1RW1R;", "RANDOM_BYTE = $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR & {{SIZE-1{8'hFF}},", "// Byte Write then Read Phase = 6; `ifdef VERBOSE_1", ".CLK(CLK), .WE0(WE0), .EN0(EN0), .EN1(ENR), .Di0(Di0), .Do0(Do0), .Do1(Do1), .A0(A0[A_W-1:$clog2(SIZE)]), .A1(A1[A_W-1:$clog2(SIZE)]) );", "wire [(SIZE*8-1):0] Do0; reg [A_W-1:0] A0, ADDR; reg [7:0] Phase;", "\"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}_1RW1R; localparam SIZE = `SIZE; localparam", "begin $dumpfile(\"tb_RAM{word_num}x{word_size}_1RW1R.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}_1RW1R); @(done) $finish; end /* Memory golden", "if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end end end endgenerate \"\"\" begin_single_ported_test", "if (ENR) begin RAM_DATA_R <= RAM[A1/SIZE]; end end end endgenerate", "A1= addr1;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef VERBOSE_2", "i=i+SIZE) begin ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFC ; RANDOM_BYTE =", "task mem_write_hword(input [SIZE*8-1:0] hword, input [A_W-1:0] addr); begin @(posedge CLK);", "WE0 = 0; EN0 = 1; ENR = 1; \"\"\"", "); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}_1RW1R.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}_1RW1R); @(done) $finish; end /*", "localparam A_W = {addr_width}+$clog2(SIZE); localparam M_SZ = 2**A_W; reg CLK;", "integer i; \"\"\" test_port_1RW1R = \"\"\" /*********************************************************** Write and read", "use this file except in compliance with the License. #", "1\"); `endif for(i=0; i<M_SZ; i=i+SIZE) begin ADDR = (($urandom%M_SZ)) &", "then Read Phase = 2; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 1,", "1; \"\"\" dual_ported_custom_test = \"\"\" Phase = 0; // Perform", "reg [7:0] Phase; reg [7:0] RANDOM_BYTE; event done; RAM{word_num}_1RW1R #(.USE_LATCH(`USE_LATCH),", "further info. # # Licensed under the Apache License, Version", "= addr;//[A_WIDTH:$clog2(SIZE)]; WE0 = {{SIZE/2{addr[$clog2(SIZE)-1]}},{SIZE/2{~addr[$clog2(SIZE)-1]}}}; Di0 = (hword << (addr[$clog2(SIZE)-1]", "reg EN0; reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0; reg [A_W-1:0]", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "2 word write then read 2 words mem_write_word({{SIZE{{8'h90}}}}, 4); mem_write_word({{SIZE{{8'h33}}}},", "SIZE = `SIZE; localparam A_W = {addr_width}+$clog2(SIZE); localparam M_SZ =", "Phase = 6; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 5, starting Phase", "License. # You may obtain a copy of the License", "to verify RAM{word_num}x{word_size} Authors: <NAME> (<EMAIL>) <NAME> (<EMAIL>) */ `define", "mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end", "RANDOM_BYTE = $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR & {{SIZE-1{8'hFF}},", "(addr[$clog2(SIZE)-1:0] * 8)); @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE BYTE: 0x%X", "mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR ); end // HWord Write", "{{SIZE/2{addr[$clog2(SIZE)-1]}},{SIZE/2{~addr[$clog2(SIZE)-1]}}}; Di0 = (hword << (addr[$clog2(SIZE)-1] * (SIZE/2)*8)); @(posedge CLK);", "Di0[8*(c+1)-1:8*c]; end if (ENR) begin RAM_DATA_R <= RAM[A1/SIZE]; end end", "Di0, WE0); `endif WE0 = {SIZE{8'h00}}; end endtask task mem_read_word_0(input", "\"hd_primitives.v\" `include \"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}_1RW1R; localparam SIZE =", "(($urandom%M_SZ)) & 'hFFFF_FFFE; RANDOM_BYTE = $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_0(", "$display(\"\\\\nFinished Phase 1, starting Phase 2\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2)", "always @(posedge CLK) begin if(EN0) begin RAM_DATA_RW <= RAM[A0/SIZE]; if(WE0[c])", ".Do1(Do1), .A0(A0[A_W-1:$clog2(SIZE)]), .A1(A1[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}_1RW1R.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}_1RW1R); @(done)", "under the License is distributed on an \"AS IS\" BASIS,", "RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end if (ENR) begin RAM_DATA_R", "License for the specific language governing permissions and # limitations", "RANDOM_BYTE; event done; RAM{word_num} #(.USE_LATCH(`USE_LATCH), .WSIZE(SIZE)) SRAM ( .CLK(CLK), .WE0(WE0),", "= `SIZE; localparam A_W = {addr_width}+$clog2(SIZE); localparam M_SZ = 2**A_W;", "endtask task mem_read_word_0(input [A_W-1:0] addr); begin @(posedge CLK); A0 =", "`endif check0(); end endtask task check0; begin if(RAM_DATA_RW !== Do0)", "be: 0x%X\", A1, Do1, RAM[A1/SIZE]); $fatal(1); end end endtask \"\"\"", "& {{SIZE-1{8'hFF}}, 8'hFC} ); end \"\"\" test_port_RW = \"\"\" /***********************************************************", "WORD: 0x%X from %0D\", Do1, addr); `endif check1(); end endtask", "then read 2 words mem_write_word({{SIZE{{8'h90}}}}, 4); mem_write_word({{SIZE{{8'h33}}}}, 8); mem_read_2words(4,8); \"\"\"", "pattern // Word Write then Read Phase = 1; `ifdef", "initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}); @(done) $finish; end /* Memory", ".WSIZE(SIZE)) SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0), .Di0(Di0), .Do(Do0), .A0(A0[A_W-1:$clog2(SIZE)]) );", "WE0); `endif WE0 = {SIZE{8'h00}}; end endtask task mem_write_word(input [SIZE*8-1:0]", "= \"\"\" always #10 CLK = !CLK; integer i; \"\"\"", "'hFFFF_FFFE; RANDOM_BYTE = $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR &", "addr); begin @(posedge CLK); A1 = addr;//[9:2]; WE0 = {SIZE{8'h00}};", "); end $display (\"\\\\n>> Test Passed! <<\\\\n\"); -> done; \"\"\"", "tb_RAM{word_num}x{word_size}_1RW1R; localparam SIZE = `SIZE; localparam A_W = {addr_width}+$clog2(SIZE); localparam", "# This file is part of the DFFRAM Memory Compiler.", "Model */ reg [(SIZE*8-1):0] RAM[(M_SZ)-1 : 0]; reg [(SIZE*8-1):0] RAM_DATA_RW;", "and read from different ports ************************************************************/ // Fill the memory", "endtask task mem_read_word_1(input [A_W-1:0] addr); begin @(posedge CLK); A1 =", "$finish; end /* Memory golden Model */ reg [(SIZE*8-1):0] RAM[(M_SZ)-1", "`endif WE0 = {SIZE{8'h00}}; end endtask task mem_read_word_0(input [A_W-1:0] addr);", "`include \"{filename}\" module tb_RAM{word_num}x{word_size}_1RW1R; localparam SIZE = `SIZE; localparam A_W", "mem_read_word_1(input [A_W-1:0] addr); begin @(posedge CLK); A1 = addr;//[9:2]; WE0", "`ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 1, starting Phase 2\"); `endif for(i=0;", "check1; begin if(RAM_DATA_R !== Do1) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d,", "i; \"\"\" test_port_1RW1R = \"\"\" /*********************************************************** Write and read from", "2; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 1, starting Phase 2\"); `endif", "in compliance with the License. # You may obtain a", "$display(\"READ WORD: 0x%X from %0D\", Do0, addr); `endif check0(); end", "mem_read_word_1(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end \"\"\" test_port_RW = \"\"\"", "port ************************************************************/ Phase = 4; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 3,", "mem_read_word_0( ADDR ); end // HWord Write then Read Phase", "= $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR & {{SIZE-1{8'hFF}}, 8'hFC}", "software # distributed under the License is distributed on an", "[(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0; reg [A_W-1:0] A0, ADDR; reg", "of the DFFRAM Memory Compiler. # See https://github.com/Cloud-V/DFFRAM for further", "override: IcarusVerilog cannot read these for some reason ^ `include", "reg [7:0] Phase; reg [7:0] RANDOM_BYTE; event done; RAM{word_num} #(.USE_LATCH(`USE_LATCH),", "Write then Read Phase = 5; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase", "addr0;//[9:2]; A1= addr1;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef", "%0D\", Do1, addr1); `endif check0(); check1(); end endtask task mem_read_word_1(input", ".A0(A0[A_W-1:$clog2(SIZE)]), .A1(A1[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}_1RW1R.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}_1RW1R); @(done) $finish;", "Read Phase = 5; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 4, starting", "end endtask task mem_write_hword(input [SIZE*8-1:0] hword, input [A_W-1:0] addr); begin", "(hword << (addr[$clog2(SIZE)-1] * (SIZE/2)*8)); @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE", "#5; `ifdef VERBOSE_2 $display(\"READ WORD0: 0x%X from %0D\", Do0, addr0);", "$display(\"Address: 0x%X, READ: 0x%X - Should be: 0x%X\", A0, Do0,", "Phase; reg [7:0] RANDOM_BYTE; event done; RAM{word_num} #(.USE_LATCH(`USE_LATCH), .WSIZE(SIZE)) SRAM", "ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end // Byte Write then", "VERBOSE_1 `define VERBOSE_2 `define UNIT_DELAY #1 `define USE_LATCH 1 `define", "reg [(SIZE-1):0] WE0; reg EN0; reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0]", "mem_read_word_1( ADDR ); end // HWord Write then Read Phase", "& {{SIZE-1{8'hFF}}, 8'hFC} ); end $display (\"\\\\n>> Test Passed! <<\\\\n\");", "$urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR & {{SIZE-1{8'hFF}}, 8'hFC} );", "RAM_DATA_RW; genvar c; generate for (c=0; c < SIZE; c", "<= RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end end end endgenerate", "read these for some reason ^ `include \"hd_primitives.v\" `include \"hd_functional.v\"", "A0, ADDR; reg [7:0] Phase; reg [7:0] RANDOM_BYTE; event done;", "0]; reg [(SIZE*8-1):0] RAM_DATA_RW; reg [(SIZE*8-1):0] RAM_DATA_R; genvar c; generate", "byte, addr, addr, Di0, WE0); `endif WE0 = {SIZE{8'h00}}; end", "RANDOM_BYTE = $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR ); end", "# See https://github.com/Cloud-V/DFFRAM for further info. # # Licensed under", "generated testbench to verify RAM{word_num}x{word_size} Authors: <NAME> (<EMAIL>) <NAME> (<EMAIL>)", "reg CLK; reg [(SIZE-1):0] WE0; reg EN0; reg [(SIZE*8-1):0] Di0;", ".WE0(WE0), .EN0(EN0), .EN1(ENR), .Di0(Di0), .Do0(Do0), .Do1(Do1), .A0(A0[A_W-1:$clog2(SIZE)]), .A1(A1[A_W-1:$clog2(SIZE)]) ); initial", "!CLK; integer i; \"\"\" test_port_1RW1R = \"\"\" /*********************************************************** Write and", "WE0 = {SIZE{8'hFF}}; Di0 = word; @(posedge CLK); `ifdef VERBOSE_2", "reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0; wire [(SIZE*8-1):0] Do1; reg", "// // Temporary override: IcarusVerilog cannot read these for some", "task mem_read_2words(input [A_W-1:0] addr0, input [A_W-1:0] addr1); begin @(posedge CLK);", "%0X(%0D) (0x%X, %B)\", hword, addr, addr, Di0, WE0); `endif WE0", "= !CLK; integer i; \"\"\" test_port_1RW1R = \"\"\" /*********************************************************** Write", "= 0; // Perform a single word write then read", "file is part of the DFFRAM Memory Compiler. # See", "some reason ^ `include \"hd_primitives.v\" `include \"hd_functional.v\" `include \"{filename}\" module", "#1 `define USE_LATCH 1 `define SIZE {word_size}/8 //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/primitives.v\" //`include", "Phase 2\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2) begin ADDR = (($urandom%M_SZ))", "*/ reg [(SIZE*8-1):0] RAM[(M_SZ)-1 : 0]; reg [(SIZE*8-1):0] RAM_DATA_RW; reg", "begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_1(ADDR & {{SIZE-1{8'hFF}}, 8'hFC}", "VERBOSE_2 $display(\"READ WORD: 0x%X from %0D\", Do1, addr); `endif check1();", "$display(\"READ WORD: 0x%X from %0D\", Do1, addr); `endif check1(); end", "\"\"\" Phase = 0; // Perform a 2 word write", "starting Phase 2\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2) begin ADDR =", "{SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR ); end // HWord Write then", "$display(\"WRITE HWORD: 0x%X to %0X(%0D) (0x%X, %B)\", hword, addr, addr,", "verify RAM{word_num}x{word_size} Authors: <NAME> (<EMAIL>) <NAME> (<EMAIL>) */ `define VERBOSE_1", "\"\"\" test_port_RW = \"\"\" /*********************************************************** Write and read from same", "SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0), .Di0(Di0), .Do(Do0), .A0(A0[A_W-1:$clog2(SIZE)]) ); initial", ".EN0(EN0), .EN1(ENR), .Di0(Di0), .Do0(Do0), .Do1(Do1), .A0(A0[A_W-1:$clog2(SIZE)]), .A1(A1[A_W-1:$clog2(SIZE)]) ); initial begin", "= 4; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 3, starting Phase 4\");", "i<M_SZ; i=i+SIZE/2) begin ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFE; RANDOM_BYTE =", "begin @(posedge CLK); A1 = addr;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge", "endtask \"\"\" dual_ported_tasks = \"\"\" task mem_read_2words(input [A_W-1:0] addr0, input", "%B)\", word, addr, addr, Di0, WE0); `endif WE0 = {SIZE{8'h00}};", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "tasks = \"\"\" task mem_write_byte(input [7:0] byte, input [A_W-1:0] addr);", "begin @(posedge CLK); A0 = addr;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge", "- Should be: 0x%X\", A0, Do0, RAM[A0/SIZE]); $fatal(1); end end", "BYTE: 0x%X to %0X(%0D) (0x%X, %B)\", byte, addr, addr, Di0,", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "^ `include \"hd_primitives.v\" `include \"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}; localparam", "5, starting Phase 6\"); `endif for(i=0; i<M_SZ; i=i+1) begin ADDR", "RAM{word_num}_1RW1R #(.USE_LATCH(`USE_LATCH), .WSIZE(`SIZE)) SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0), .EN1(ENR), .Di0(Di0),", "$urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR ); end // HWord", "); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}); @(done) $finish; end /*", "end endtask task mem_read_word_0(input [A_W-1:0] addr); begin @(posedge CLK); A0", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "[7:0] RANDOM_BYTE; event done; RAM{word_num}_1RW1R #(.USE_LATCH(`USE_LATCH), .WSIZE(`SIZE)) SRAM ( .CLK(CLK),", ".Do0(Do0), .Do1(Do1), .A0(A0[A_W-1:$clog2(SIZE)]), .A1(A1[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}_1RW1R.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}_1RW1R);", "to in writing, software # distributed under the License is", "CLK); A0 = addr; WE0 = {SIZE{8'hFF}}; Di0 = word;", "addr); `endif check1(); end endtask task check1; begin if(RAM_DATA_R !==", "and the Cloud V Project. # # This file is", "# See the License for the specific language governing permissions", "[SIZE*8-1:0] hword, input [A_W-1:0] addr); begin @(posedge CLK); A0 =", "0x%X to %0X(%0D) (0x%X, %B)\", hword, addr, addr, Di0, WE0);", "the DFFRAM Memory Compiler. # See https://github.com/Cloud-V/DFFRAM for further info.", "memory with a known pattern // Word Write then Read", "or agreed to in writing, software # distributed under the", "end if (ENR) begin RAM_DATA_R <= RAM[A1/SIZE]; end end end", "required by applicable law or agreed to in writing, software", "mem_write_byte($urandom%255, ADDR); mem_read_word_0(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end $display (\"\\\\n>>", "!== Do0) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d, Iteration: %0d\", Phase,", "end end endgenerate \"\"\" begin_dual_ported_test = \"\"\" initial begin CLK", "= addr;//[A_WIDTH:2]; WE0 = (1 << addr[$clog2(SIZE)-1:0]); Di0 = (byte", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", ".WE0(WE0), .EN0(EN0), .Di0(Di0), .Do(Do0), .A0(A0[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}.vcd\"); $dumpvars(0,", "with the License. # You may obtain a copy of", "RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end end end endgenerate \"\"\" begin_single_ported_test =", "Phase = 4; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 3, starting Phase", "0x%X - Should be: 0x%X\", A0, Do0, RAM[A0/SIZE]); $fatal(1); end", ": 0]; reg [(SIZE*8-1):0] RAM_DATA_RW; genvar c; generate for (c=0;", "to %0X(%0D) (0x%X, %B)\", hword, addr, addr, Di0, WE0); `endif", "VERBOSE_1 $display(\"\\\\nFinished Phase 3, starting Phase 4\"); `endif for(i=0; i<M_SZ;", "Test Passed! <<\\\\n\"); -> done; \"\"\" end_test = \"\"\" end", "WE0 = {SIZE{8'h00}}; end endtask task mem_write_hword(input [SIZE*8-1:0] hword, input", "* 8)); @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE BYTE: 0x%X to", "reg [(SIZE*8-1):0] RAM_DATA_RW; reg [(SIZE*8-1):0] RAM_DATA_R; genvar c; generate for", "%0d, Iteration: %0d\", Phase, i); $display(\"Address: 0x%X, READ: 0x%X -", "end /* Memory golden Model */ reg [(SIZE*8-1):0] RAM[(M_SZ)-1 :", "0x%X\", A1, Do1, RAM[A1/SIZE]); $fatal(1); end end endtask \"\"\" endmodule", "************************************************************/ Phase = 4; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 3, starting", "`define VERBOSE_1 `define VERBOSE_2 `define UNIT_DELAY #1 `define USE_LATCH 1", "compliance with the License. # You may obtain a copy", "HWord Write then Read Phase = 5; `ifdef VERBOSE_1 $display(\"\\\\nFinished", "= 0; EN0 = 1; ENR = 1; \"\"\" dual_ported_custom_test", "agreed to in writing, software # distributed under the License", "Phase = 3; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 2, starting Phase", "ENR = 1; \"\"\" dual_ported_custom_test = \"\"\" Phase = 0;", "WE0 = {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD0:", "`endif for(i=0; i<M_SZ; i=i+SIZE/2) begin ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFE;", "`ifdef VERBOSE_2 $display(\"READ WORD: 0x%X from %0D\", Do1, addr); `endif", "{SIZE{8'h00}}; end endtask task mem_read_word_0(input [A_W-1:0] addr); begin @(posedge CLK);", "distributed under the License is distributed on an \"AS IS\"", "RAM[(M_SZ)-1 : 0]; reg [(SIZE*8-1):0] RAM_DATA_RW; genvar c; generate for", "= 1; \"\"\" dual_ported_custom_test = \"\"\" Phase = 0; //", ".A1(A1[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}_1RW1R.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}_1RW1R); @(done) $finish; end", "*/ reg [(SIZE*8-1):0] RAM[(M_SZ)-1 : 0]; reg [(SIZE*8-1):0] RAM_DATA_RW; genvar", "A1, ADDR; reg [7:0] Phase; reg [7:0] RANDOM_BYTE; event done;", "Phase 5\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2) begin ADDR = (($urandom%M_SZ))", "CLK); A0 = addr;//[A_WIDTH:2]; WE0 = (1 << addr[$clog2(SIZE)-1:0]); Di0", "{SIZE{8'h00}}; end endtask task mem_write_word(input [SIZE*8-1:0] word, input [A_W-1:0] addr);", "{SIZE{8'hFF}}; Di0 = word; @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE WORD:", "mem_read_2words(input [A_W-1:0] addr0, input [A_W-1:0] addr1); begin @(posedge CLK); A0=", "$display (\"\\\\n>> Test Passed! <<\\\\n\"); -> done; \"\"\" end_test =", "mem_write_word({{SIZE{{8'h90}}}}, 4); mem_read_word_0(4); \"\"\" RAM_instantiation_1RW1R = \"\"\" /* An auto", "\"\"\" test_port_1RW1R = \"\"\" /*********************************************************** Write and read from different", "HWord Write then Read Phase = 2; `ifdef VERBOSE_1 $display(\"\\\\nFinished", "= (byte << (addr[$clog2(SIZE)-1:0] * 8)); @(posedge CLK); `ifdef VERBOSE_2", "4); mem_write_word({{SIZE{{8'h33}}}}, 8); mem_read_2words(4,8); \"\"\" start_test_common = \"\"\" always #10", "express or implied. # See the License for the specific", "mem_write_hword(input [SIZE*8-1:0] hword, input [A_W-1:0] addr); begin @(posedge CLK); A0", "except in compliance with the License. # You may obtain", "= \"\"\" /*********************************************************** Write and read from different ports ************************************************************/", "5; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 4, starting Phase 5\"); `endif", "WE0 = {SIZE{8'h00}}; end endtask task mem_read_word_0(input [A_W-1:0] addr); begin", "{SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end //", "; RANDOM_BYTE = $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR );", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "addr;//[A_WIDTH:2]; WE0 = (1 << addr[$clog2(SIZE)-1:0]); Di0 = (byte <<", "end endtask task check1; begin if(RAM_DATA_R !== Do1) begin $display(\"\\\\n>>Test", "end_test = \"\"\" end \"\"\" tasks = \"\"\" task mem_write_byte(input", "0; // Perform a single word write then read mem_write_word({{SIZE{{8'h90}}}},", "not use this file except in compliance with the License.", "`ifdef VERBOSE_2 $display(\"WRITE HWORD: 0x%X to %0X(%0D) (0x%X, %B)\", hword,", "[A_W-1:0] addr0, input [A_W-1:0] addr1); begin @(posedge CLK); A0= addr0;//[9:2];", "and # limitations under the License. RAM_instantiation = \"\"\" /*", "`ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 2, starting Phase 3\"); `endif for(i=0;", "Do0, addr); `endif check0(); end endtask task check0; begin if(RAM_DATA_RW", "a 2 word write then read 2 words mem_write_word({{SIZE{{8'h90}}}}, 4);", "Phase 4, starting Phase 5\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2) begin", "writing, software # distributed under the License is distributed on", "@(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE WORD: 0x%X to %0X(%0D) (0x%X,", "WORD: 0x%X from %0D\", Do0, addr); `endif check0(); end endtask", "(0x%X, %B)\", byte, addr, addr, Di0, WE0); `endif WE0 =", "A1 = addr;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef", "you may not use this file except in compliance with", "begin RAM_DATA_RW <= RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end if", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "= c+1) begin: mem_golden_model always @(posedge CLK) begin if(EN0) begin", "for(i=0; i<M_SZ; i=i+SIZE/2) begin ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFE; RANDOM_BYTE", "then Read Phase = 5; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 4,", "Phase 4\"); `endif for(i=0; i<M_SZ; i=i+SIZE) begin ADDR = (($urandom%M_SZ))", "A0 = addr;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef", "Perform a 2 word write then read 2 words mem_write_word({{SIZE{{8'h90}}}},", "= {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD: 0x%X", "end \"\"\" tasks = \"\"\" task mem_write_byte(input [7:0] byte, input", "\"\"\" always #10 CLK = !CLK; integer i; \"\"\" test_port_1RW1R", "Read Phase = 2; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 1, starting", "addr[$clog2(SIZE)-1:0]); Di0 = (byte << (addr[$clog2(SIZE)-1:0] * 8)); @(posedge CLK);", "& {{SIZE-1{8'hFF}}, 8'hFC} ); end // Byte Write then Read", "known pattern // Word Write then Read Phase = 1;", "EN0 = 1; ENR = 1; \"\"\" dual_ported_custom_test = \"\"\"", "reg [7:0] RANDOM_BYTE; event done; RAM{word_num} #(.USE_LATCH(`USE_LATCH), .WSIZE(SIZE)) SRAM (", "& 'hFFFF_FFFE; RANDOM_BYTE = $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR", "\"\"\" Phase = 0; // Perform a single word write", "`include \"hd_primitives.v\" `include \"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}_1RW1R; localparam SIZE", "CONDITIONS OF ANY KIND, either express or implied. # See", ".EN1(ENR), .Di0(Di0), .Do0(Do0), .Do1(Do1), .A0(A0[A_W-1:$clog2(SIZE)]), .A1(A1[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}_1RW1R.vcd\");", "1; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 0, starting Phase 1\"); `endif", "begin @(posedge CLK); A0 = addr;//[A_WIDTH:2]; WE0 = (1 <<", "Phase = 1; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 0, starting Phase", "A0 = addr; WE0 = {SIZE{8'hFF}}; Di0 = word; @(posedge", "Do0; reg [A_W-1:0] A0, ADDR; reg [7:0] Phase; reg [7:0]", "/*********************************************************** Write and read from different ports ************************************************************/ // Fill", "then read mem_write_word({{SIZE{{8'h90}}}}, 4); mem_read_word_0(4); \"\"\" RAM_instantiation_1RW1R = \"\"\" /*", "reg [(SIZE*8-1):0] RAM[(M_SZ)-1 : 0]; reg [(SIZE*8-1):0] RAM_DATA_RW; reg [(SIZE*8-1):0]", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "begin: mem_golden_model always @(posedge CLK) begin if(EN0) begin RAM_DATA_RW <=", "Do0; wire [(SIZE*8-1):0] Do1; reg [A_W-1:0] A0, A1, ADDR; reg", "* (SIZE/2)*8)); @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE HWORD: 0x%X to", "{SIZE{8'h00}}; @(posedge CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD0: 0x%X from", "task check1; begin if(RAM_DATA_R !== Do1) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase:", "); end // Byte Write then Read Phase = 3;", "0; EN0 = 1; \"\"\" single_ported_custom_test = \"\"\" Phase =", "Di0; wire [(SIZE*8-1):0] Do0; wire [(SIZE*8-1):0] Do1; reg [A_W-1:0] A0,", "Do1, addr1); `endif check0(); check1(); end endtask task mem_read_word_1(input [A_W-1:0]", "mem_write_byte(input [7:0] byte, input [A_W-1:0] addr); begin @(posedge CLK); A0", "0; // Perform a 2 word write then read 2", "4, starting Phase 5\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2) begin ADDR", "done; \"\"\" end_test = \"\"\" end \"\"\" tasks = \"\"\"", "2 words mem_write_word({{SIZE{{8'h90}}}}, 4); mem_write_word({{SIZE{{8'h33}}}}, 8); mem_read_2words(4,8); \"\"\" start_test_common =", "localparam M_SZ = 2**A_W; reg CLK; reg [(SIZE-1):0] WE0; reg", "%B)\", byte, addr, addr, Di0, WE0); `endif WE0 = {SIZE{8'h00}};", "mem_read_word_0(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end $display (\"\\\\n>> Test Passed!", "`include \"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}; localparam SIZE = `SIZE;", "A0, A1, ADDR; reg [7:0] Phase; reg [7:0] RANDOM_BYTE; event", "RANDOM_BYTE; event done; RAM{word_num}_1RW1R #(.USE_LATCH(`USE_LATCH), .WSIZE(`SIZE)) SRAM ( .CLK(CLK), .WE0(WE0),", "ports ************************************************************/ // Fill the memory with a known pattern", "$display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d, Iteration: %0d\", Phase, i); $display(\"Address: 0x%X,", "end end end endgenerate \"\"\" begin_single_ported_test = \"\"\" initial begin", "CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD0: 0x%X from %0D\", Do0,", "RAM_instantiation_1RW1R = \"\"\" /* An auto generated testbench to verify", "testbench to verify RAM{word_num}x{word_size} Authors: <NAME> (<EMAIL>) <NAME> (<EMAIL>) */", "module tb_RAM{word_num}x{word_size}_1RW1R; localparam SIZE = `SIZE; localparam A_W = {addr_width}+$clog2(SIZE);", "if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end if (ENR) begin RAM_DATA_R <=", "3\"); `endif for(i=0; i<M_SZ; i=i+1) begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255,", "); end \"\"\" test_port_RW = \"\"\" /*********************************************************** Write and read", "addr); begin @(posedge CLK); A0 = addr;//[A_WIDTH:$clog2(SIZE)]; WE0 = {{SIZE/2{addr[$clog2(SIZE)-1]}},{SIZE/2{~addr[$clog2(SIZE)-1]}}};", "// Temporary override: IcarusVerilog cannot read these for some reason", "tb_RAM{word_num}x{word_size}; localparam SIZE = `SIZE; localparam A_W = {addr_width}+$clog2(SIZE); localparam", "@(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE BYTE: 0x%X to %0X(%0D) (0x%X,", "mem_golden_model always @(posedge CLK) begin if(EN0) begin RAM_DATA_RW <= RAM[A0/SIZE];", ": 0]; reg [(SIZE*8-1):0] RAM_DATA_RW; reg [(SIZE*8-1):0] RAM_DATA_R; genvar c;", "Write then Read Phase = 6; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase", "$display(\"\\\\nFinished Phase 5, starting Phase 6\"); `endif for(i=0; i<M_SZ; i=i+1)", "\"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/primitives.v\" //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/sky130_fd_sc_hd.v\" // // Temporary override: IcarusVerilog cannot read", "a single word write then read mem_write_word({{SIZE{{8'h90}}}}, 4); mem_read_word_0(4); \"\"\"", "i=i+1) begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_0(ADDR & {{SIZE-1{8'hFF}},", "<< (addr[$clog2(SIZE)-1:0] * 8)); @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE BYTE:", "reg [(SIZE*8-1):0] RAM_DATA_R; genvar c; generate for (c=0; c <", "Phase; reg [7:0] RANDOM_BYTE; event done; RAM{word_num}_1RW1R #(.USE_LATCH(`USE_LATCH), .WSIZE(`SIZE)) SRAM", "if(EN0) begin RAM_DATA_RW <= RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end", "OR CONDITIONS OF ANY KIND, either express or implied. #", "reg CLK; reg [(SIZE-1):0] WE0; reg EN0; reg ENR; reg", "%0X(%0D) (0x%X, %B)\", word, addr, addr, Di0, WE0); `endif WE0", "single word write then read mem_write_word({{SIZE{{8'h90}}}}, 4); mem_read_word_0(4); \"\"\" RAM_instantiation_1RW1R", "mem_write_word({{SIZE{{8'h33}}}}, 8); mem_read_2words(4,8); \"\"\" start_test_common = \"\"\" always #10 CLK", "'hFFFF_FFFE; RANDOM_BYTE = $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR &", "end endtask task mem_write_word(input [SIZE*8-1:0] word, input [A_W-1:0] addr); begin", "(ENR) begin RAM_DATA_R <= RAM[A1/SIZE]; end end end endgenerate \"\"\"", "# Copyright ©2020-2021 The American University in Cairo and the", "the License is distributed on an \"AS IS\" BASIS, #", "ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_1(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} );", "= {{SIZE/2{addr[$clog2(SIZE)-1]}},{SIZE/2{~addr[$clog2(SIZE)-1]}}}; Di0 = (hword << (addr[$clog2(SIZE)-1] * (SIZE/2)*8)); @(posedge", "`endif WE0 = {SIZE{8'h00}}; end endtask task mem_write_hword(input [SIZE*8-1:0] hword,", "CLK); A1 = addr;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK); #5;", "starting Phase 5\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2) begin ADDR =", "c+1) begin: mem_golden_model always @(posedge CLK) begin if(EN0) begin RAM_DATA_RW", "University in Cairo and the Cloud V Project. # #", "[SIZE*8-1:0] word, input [A_W-1:0] addr); begin @(posedge CLK); A0 =", "done; RAM{word_num} #(.USE_LATCH(`USE_LATCH), .WSIZE(SIZE)) SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0), .Di0(Di0),", "hword, input [A_W-1:0] addr); begin @(posedge CLK); A0 = addr;//[A_WIDTH:$clog2(SIZE)];", "info. # # Licensed under the Apache License, Version 2.0", "{{SIZE-1{8'hFF}}, 8'hFC} ); end $display (\"\\\\n>> Test Passed! <<\\\\n\"); ->", "See https://github.com/Cloud-V/DFFRAM for further info. # # Licensed under the", "'hFFFF_FFFC ; RANDOM_BYTE = $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR", "CLK; reg [(SIZE-1):0] WE0; reg EN0; reg ENR; reg [(SIZE*8-1):0]", "Phase 1, starting Phase 2\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2) begin", "= {SIZE{8'h00}}; end endtask task mem_read_word_0(input [A_W-1:0] addr); begin @(posedge", "read mem_write_word({{SIZE{{8'h90}}}}, 4); mem_read_word_0(4); \"\"\" RAM_instantiation_1RW1R = \"\"\" /* An", "then Read Phase = 1; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 0,", "write then read 2 words mem_write_word({{SIZE{{8'h90}}}}, 4); mem_write_word({{SIZE{{8'h33}}}}, 8); mem_read_2words(4,8);", "0, starting Phase 1\"); `endif for(i=0; i<M_SZ; i=i+SIZE) begin ADDR", "1, starting Phase 2\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2) begin ADDR", "CLK = !CLK; integer i; \"\"\" test_port_1RW1R = \"\"\" /***********************************************************", "end \"\"\" test_port_RW = \"\"\" /*********************************************************** Write and read from", "RAM_DATA_R; genvar c; generate for (c=0; c < SIZE; c", "end end endtask \"\"\" dual_ported_tasks = \"\"\" task mem_read_2words(input [A_W-1:0]", "check0; begin if(RAM_DATA_RW !== Do0) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d,", "ADDR; reg [7:0] Phase; reg [7:0] RANDOM_BYTE; event done; RAM{word_num}_1RW1R", "reg [(SIZE-1):0] WE0; reg EN0; reg ENR; reg [(SIZE*8-1):0] Di0;", "reason ^ `include \"hd_primitives.v\" `include \"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size};", "law or agreed to in writing, software # distributed under", "RAM[(M_SZ)-1 : 0]; reg [(SIZE*8-1):0] RAM_DATA_RW; reg [(SIZE*8-1):0] RAM_DATA_R; genvar", "[(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0; wire [(SIZE*8-1):0] Do1; reg [A_W-1:0]", "RAM{word_num}x{word_size} Authors: <NAME> (<EMAIL>) <NAME> (<EMAIL>) */ `define VERBOSE_1 `define", "& 'hFFFF_FFFE; RANDOM_BYTE = $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR", "begin CLK = 0; WE0 = 0; EN0 = 1;", "write then read mem_write_word({{SIZE{{8'h90}}}}, 4); mem_read_word_0(4); \"\"\" RAM_instantiation_1RW1R = \"\"\"", "(($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_0(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end $display", "Passed! <<\\\\n\"); -> done; \"\"\" end_test = \"\"\" end \"\"\"", "Phase 3\"); `endif for(i=0; i<M_SZ; i=i+1) begin ADDR = (($urandom%M_SZ));", "A0, Do0, RAM[A0/SIZE]); $fatal(1); end end endtask \"\"\" dual_ported_tasks =", "`define VERBOSE_2 `define UNIT_DELAY #1 `define USE_LATCH 1 `define SIZE", "Read Phase = 3; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 2, starting", ".A0(A0[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}); @(done) $finish; end", "-> done; \"\"\" end_test = \"\"\" end \"\"\" tasks =", "HWORD: 0x%X to %0X(%0D) (0x%X, %B)\", hword, addr, addr, Di0,", "end endgenerate \"\"\" begin_single_ported_test = \"\"\" initial begin CLK =", "to %0X(%0D) (0x%X, %B)\", word, addr, addr, Di0, WE0); `endif", "part of the DFFRAM Memory Compiler. # See https://github.com/Cloud-V/DFFRAM for", "4); mem_read_word_0(4); \"\"\" RAM_instantiation_1RW1R = \"\"\" /* An auto generated", "8); mem_read_2words(4,8); \"\"\" start_test_common = \"\"\" always #10 CLK =", "Phase 6\"); `endif for(i=0; i<M_SZ; i=i+1) begin ADDR = (($urandom%M_SZ));", "// Perform a 2 word write then read 2 words", "= \"\"\" task mem_write_byte(input [7:0] byte, input [A_W-1:0] addr); begin", "(($urandom%M_SZ)) & 'hFFFF_FFFC ; RANDOM_BYTE = $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR);", "words mem_write_word({{SIZE{{8'h90}}}}, 4); mem_write_word({{SIZE{{8'h33}}}}, 8); mem_read_2words(4,8); \"\"\" start_test_common = \"\"\"", "WORD: 0x%X to %0X(%0D) (0x%X, %B)\", word, addr, addr, Di0,", "= \"\"\" Phase = 0; // Perform a 2 word", "different ports ************************************************************/ // Fill the memory with a known", "= {SIZE{8'hFF}}; Di0 = word; @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE", "$dumpfile(\"tb_RAM{word_num}x{word_size}_1RW1R.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}_1RW1R); @(done) $finish; end /* Memory golden Model", "may obtain a copy of the License at # #", "read from different ports ************************************************************/ // Fill the memory with", "Di0 = (byte << (addr[$clog2(SIZE)-1:0] * 8)); @(posedge CLK); `ifdef", "#5; `ifdef VERBOSE_2 $display(\"READ WORD: 0x%X from %0D\", Do0, addr);", "[A_W-1:0] A0, A1, ADDR; reg [7:0] Phase; reg [7:0] RANDOM_BYTE;", "6\"); `endif for(i=0; i<M_SZ; i=i+1) begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255,", "(addr[$clog2(SIZE)-1] * (SIZE/2)*8)); @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE HWORD: 0x%X", "for (c=0; c < SIZE; c = c+1) begin: mem_golden_model", "VERBOSE_1 $display(\"\\\\nFinished Phase 2, starting Phase 3\"); `endif for(i=0; i<M_SZ;", "@(posedge CLK); A0 = addr;//[A_WIDTH:$clog2(SIZE)]; WE0 = {{SIZE/2{addr[$clog2(SIZE)-1]}},{SIZE/2{~addr[$clog2(SIZE)-1]}}}; Di0 =", "= {SIZE{8'h00}}; end endtask task mem_write_word(input [SIZE*8-1:0] word, input [A_W-1:0]", "read 2 words mem_write_word({{SIZE{{8'h90}}}}, 4); mem_write_word({{SIZE{{8'h33}}}}, 8); mem_read_2words(4,8); \"\"\" start_test_common", "= addr;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef VERBOSE_2", "end endtask task check0; begin if(RAM_DATA_RW !== Do0) begin $display(\"\\\\n>>Test", "`include \"hd_primitives.v\" `include \"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}; localparam SIZE", "{{SIZE-1{8'hFF}}, 8'hFC} ); end // Byte Write then Read Phase", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "= (($urandom%M_SZ)) & 'hFFFF_FFFE; RANDOM_BYTE = $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR);", "[(SIZE*8-1):0] RAM[(M_SZ)-1 : 0]; reg [(SIZE*8-1):0] RAM_DATA_RW; reg [(SIZE*8-1):0] RAM_DATA_R;", "@(posedge CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD: 0x%X from %0D\",", "RAM_DATA_R <= RAM[A1/SIZE]; end end end endgenerate \"\"\" begin_dual_ported_test =", "`endif check1(); end endtask task check1; begin if(RAM_DATA_R !== Do1)", "task mem_write_byte(input [7:0] byte, input [A_W-1:0] addr); begin @(posedge CLK);", "may not use this file except in compliance with the", "[7:0] Phase; reg [7:0] RANDOM_BYTE; event done; RAM{word_num}_1RW1R #(.USE_LATCH(`USE_LATCH), .WSIZE(`SIZE))", "addr, Di0, WE0); `endif WE0 = {SIZE{8'h00}}; end endtask task", "WE0; reg EN0; reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0; reg", "from %0D\", Do0, addr0); $display(\"READ WORD1: 0x%X from %0D\", Do1,", "Authors: <NAME> (<EMAIL>) <NAME> (<EMAIL>) */ `define VERBOSE_1 `define VERBOSE_2", "addr1); `endif check0(); check1(); end endtask task mem_read_word_1(input [A_W-1:0] addr);", "/*********************************************************** Write and read from same port ************************************************************/ Phase =", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "ENR; reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0; wire [(SIZE*8-1):0] Do1;", "(<EMAIL>) */ `define VERBOSE_1 `define VERBOSE_2 `define UNIT_DELAY #1 `define", "this file except in compliance with the License. # You", "c < SIZE; c = c+1) begin: mem_golden_model always @(posedge", "EN0; reg ENR; reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0; wire", "[(SIZE-1):0] WE0; reg EN0; reg ENR; reg [(SIZE*8-1):0] Di0; wire", "5\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2) begin ADDR = (($urandom%M_SZ)) &", "Should be: 0x%X\", A0, Do0, RAM[A0/SIZE]); $fatal(1); end end endtask", "{SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end //", "WORD1: 0x%X from %0D\", Do1, addr1); `endif check0(); check1(); end", "(0x%X, %B)\", hword, addr, addr, Di0, WE0); `endif WE0 =", "`define USE_LATCH 1 `define SIZE {word_size}/8 //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/primitives.v\" //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/sky130_fd_sc_hd.v\"", "@(posedge CLK); A0 = addr;//[A_WIDTH:2]; WE0 = (1 << addr[$clog2(SIZE)-1:0]);", "(SIZE/2)*8)); @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE HWORD: 0x%X to %0X(%0D)", "\"\"\" begin_single_ported_test = \"\"\" initial begin CLK = 0; WE0", "ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_0(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} );", "end endtask \"\"\" dual_ported_tasks = \"\"\" task mem_read_2words(input [A_W-1:0] addr0,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "SIZE; c = c+1) begin: mem_golden_model always @(posedge CLK) begin", "3; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 2, starting Phase 3\"); `endif", "# # Licensed under the Apache License, Version 2.0 (the", "and read from same port ************************************************************/ Phase = 4; `ifdef", "\"\"\" dual_ported_custom_test = \"\"\" Phase = 0; // Perform a", "ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFE; RANDOM_BYTE = $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}},", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Memory golden Model */ reg [(SIZE*8-1):0] RAM[(M_SZ)-1 : 0]; reg", "permissions and # limitations under the License. RAM_instantiation = \"\"\"", "`ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 3, starting Phase 4\"); `endif for(i=0;", "= 1; ENR = 1; \"\"\" dual_ported_custom_test = \"\"\" Phase", "<< (addr[$clog2(SIZE)-1] * (SIZE/2)*8)); @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE HWORD:", "the Cloud V Project. # # This file is part", "(c=0; c < SIZE; c = c+1) begin: mem_golden_model always", "reg [(SIZE*8-1):0] RAM[(M_SZ)-1 : 0]; reg [(SIZE*8-1):0] RAM_DATA_RW; genvar c;", "dual_ported_custom_test = \"\"\" Phase = 0; // Perform a 2", "# limitations under the License. RAM_instantiation = \"\"\" /* An", "8)); @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE BYTE: 0x%X to %0X(%0D)", "0x%X from %0D\", Do1, addr); `endif check1(); end endtask task", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "@(posedge CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD0: 0x%X from %0D\",", "RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end if (ENR) begin RAM_DATA_R <= RAM[A1/SIZE];", "mem_write_word({{SIZE{{8'h90}}}}, 4); mem_write_word({{SIZE{{8'h33}}}}, 8); mem_read_2words(4,8); \"\"\" start_test_common = \"\"\" always", "mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end", "Write and read from same port ************************************************************/ Phase = 4;", "Do0, RAM[A0/SIZE]); $fatal(1); end end endtask \"\"\" dual_ported_tasks = \"\"\"", "/* An auto generated testbench to verify RAM{word_num}x{word_size} Authors: <NAME>", "= 1; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 0, starting Phase 1\");", "%B)\", hword, addr, addr, Di0, WE0); `endif WE0 = {SIZE{8'h00}};", "in Cairo and the Cloud V Project. # # This", "`define UNIT_DELAY #1 `define USE_LATCH 1 `define SIZE {word_size}/8 //`include", "0; WE0 = 0; EN0 = 1; \"\"\" single_ported_custom_test =", "{{SIZE-1{8'hFF}}, 8'hFC} ); end \"\"\" test_port_RW = \"\"\" /*********************************************************** Write", "RAM_instantiation = \"\"\" /* An auto generated testbench to verify", "\"\"\" dual_ported_tasks = \"\"\" task mem_read_2words(input [A_W-1:0] addr0, input [A_W-1:0]", "cannot read these for some reason ^ `include \"hd_primitives.v\" `include", "mem_read_word_0(input [A_W-1:0] addr); begin @(posedge CLK); A0 = addr;//[9:2]; WE0", "task mem_read_word_0(input [A_W-1:0] addr); begin @(posedge CLK); A0 = addr;//[9:2];", "mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR ); end // HWord Write", "starting Phase 1\"); `endif for(i=0; i<M_SZ; i=i+SIZE) begin ADDR =", "if(RAM_DATA_R !== Do1) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d, Iteration: %0d\",", "'hFFFF_FFFC ; RANDOM_BYTE = $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR", "M_SZ = 2**A_W; reg CLK; reg [(SIZE-1):0] WE0; reg EN0;", "<<\\\\n\"); -> done; \"\"\" end_test = \"\"\" end \"\"\" tasks", "[(SIZE*8-1):0] RAM_DATA_RW; genvar c; generate for (c=0; c < SIZE;", "is part of the DFFRAM Memory Compiler. # See https://github.com/Cloud-V/DFFRAM", "end // Byte Write then Read Phase = 3; `ifdef", "%0d\", Phase, i); $display(\"Address: 0x%X, READ: 0x%X - Should be:", "RAM_DATA_RW <= RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end if (ENR)", "CLK); `ifdef VERBOSE_2 $display(\"WRITE WORD: 0x%X to %0X(%0D) (0x%X, %B)\",", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "RANDOM_BYTE = $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR ); end", "= (($urandom%M_SZ)) & 'hFFFF_FFFC ; RANDOM_BYTE = $urandom; mem_write_word( {SIZE{RANDOM_BYTE}},", "end // HWord Write then Read Phase = 5; `ifdef", "c = c+1) begin: mem_golden_model always @(posedge CLK) begin if(EN0)", "with a known pattern // Word Write then Read Phase", "= (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_0(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end", "Do0, addr0); $display(\"READ WORD1: 0x%X from %0D\", Do1, addr1); `endif", "from %0D\", Do1, addr); `endif check1(); end endtask task check1;", "= 0; WE0 = 0; EN0 = 1; ENR =", "Di0 = word; @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE WORD: 0x%X", "$dumpvars(0, tb_RAM{word_num}x{word_size}_1RW1R); @(done) $finish; end /* Memory golden Model */", "= 2**A_W; reg CLK; reg [(SIZE-1):0] WE0; reg EN0; reg", "= \"\"\" /*********************************************************** Write and read from same port ************************************************************/", "or implied. # See the License for the specific language", "VERBOSE_2 $display(\"WRITE HWORD: 0x%X to %0X(%0D) (0x%X, %B)\", hword, addr,", "CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD: 0x%X from %0D\", Do0,", "$display(\"Address: 0x%X, READ: 0x%X - Should be: 0x%X\", A1, Do1,", "USE_LATCH 1 `define SIZE {word_size}/8 //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/primitives.v\" //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/sky130_fd_sc_hd.v\" //", "{SIZE{8'h00}}; @(posedge CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD: 0x%X from", "@(posedge CLK) begin if(EN0) begin RAM_DATA_RW <= RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c]", "( .CLK(CLK), .WE0(WE0), .EN0(EN0), .Di0(Di0), .Do(Do0), .A0(A0[A_W-1:$clog2(SIZE)]) ); initial begin", "$display(\"\\\\nFinished Phase 4, starting Phase 5\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2)", "(\"\\\\n>> Test Passed! <<\\\\n\"); -> done; \"\"\" end_test = \"\"\"", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "8'hFC} ); end $display (\"\\\\n>> Test Passed! <<\\\\n\"); -> done;", "for further info. # # Licensed under the Apache License,", "; RANDOM_BYTE = $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR );", "mem_read_word_0(4); \"\"\" RAM_instantiation_1RW1R = \"\"\" /* An auto generated testbench", "input [A_W-1:0] addr); begin @(posedge CLK); A0 = addr;//[A_WIDTH:2]; WE0", "[A_W-1:0] addr); begin @(posedge CLK); A0 = addr;//[9:2]; WE0 =", "`ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 5, starting Phase 6\"); `endif for(i=0;", "reg EN0; reg ENR; reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0;", "word write then read 2 words mem_write_word({{SIZE{{8'h90}}}}, 4); mem_write_word({{SIZE{{8'h33}}}}, 8);", "end end end endgenerate \"\"\" begin_dual_ported_test = \"\"\" initial begin", "@(posedge CLK); A1 = addr;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK);", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "end endtask task mem_read_word_1(input [A_W-1:0] addr); begin @(posedge CLK); A1", "RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end end end endgenerate \"\"\"", "reg ENR; reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0; wire [(SIZE*8-1):0]", "An auto generated testbench to verify RAM{word_num}x{word_size} Authors: <NAME> (<EMAIL>)", "3, starting Phase 4\"); `endif for(i=0; i<M_SZ; i=i+SIZE) begin ADDR", "CLK) begin if(EN0) begin RAM_DATA_RW <= RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <=", "VERBOSE_2 $display(\"WRITE WORD: 0x%X to %0X(%0D) (0x%X, %B)\", word, addr,", "end // Byte Write then Read Phase = 6; `ifdef", "%0D\", Do0, addr); `endif check0(); end endtask task check0; begin", "VERBOSE_2 $display(\"READ WORD0: 0x%X from %0D\", Do0, addr0); $display(\"READ WORD1:", "$dumpfile(\"tb_RAM{word_num}x{word_size}.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}); @(done) $finish; end /* Memory golden Model", "This file is part of the DFFRAM Memory Compiler. #", "golden Model */ reg [(SIZE*8-1):0] RAM[(M_SZ)-1 : 0]; reg [(SIZE*8-1):0]", "<= Di0[8*(c+1)-1:8*c]; end if (ENR) begin RAM_DATA_R <= RAM[A1/SIZE]; end", "Do1, RAM[A1/SIZE]); $fatal(1); end end endtask \"\"\" endmodule = \"\"\"", "= 2; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 1, starting Phase 2\");", "reg [(SIZE*8-1):0] RAM_DATA_RW; genvar c; generate for (c=0; c <", "`ifdef VERBOSE_2 $display(\"READ WORD0: 0x%X from %0D\", Do0, addr0); $display(\"READ", "(the \"License\"); # you may not use this file except", "= 5; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 4, starting Phase 5\");", "# you may not use this file except in compliance", "event done; RAM{word_num}_1RW1R #(.USE_LATCH(`USE_LATCH), .WSIZE(`SIZE)) SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0),", "Memory Compiler. # See https://github.com/Cloud-V/DFFRAM for further info. # #", "begin RAM_DATA_RW <= RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end end", "input [A_W-1:0] addr); begin @(posedge CLK); A0 = addr;//[A_WIDTH:$clog2(SIZE)]; WE0", "A0 = addr;//[A_WIDTH:2]; WE0 = (1 << addr[$clog2(SIZE)-1:0]); Di0 =", "read from same port ************************************************************/ Phase = 4; `ifdef VERBOSE_1", "[A_W-1:0] addr); begin @(posedge CLK); A0 = addr;//[A_WIDTH:$clog2(SIZE)]; WE0 =", "these for some reason ^ `include \"hd_primitives.v\" `include \"hd_functional.v\" `include", "addr1); begin @(posedge CLK); A0= addr0;//[9:2]; A1= addr1;//[9:2]; WE0 =", "event done; RAM{word_num} #(.USE_LATCH(`USE_LATCH), .WSIZE(SIZE)) SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0),", "governing permissions and # limitations under the License. RAM_instantiation =", "0x%X to %0X(%0D) (0x%X, %B)\", word, addr, addr, Di0, WE0);", "dual_ported_tasks = \"\"\" task mem_read_2words(input [A_W-1:0] addr0, input [A_W-1:0] addr1);", "addr, addr, Di0, WE0); `endif WE0 = {SIZE{8'h00}}; end endtask", "$display(\"READ WORD1: 0x%X from %0D\", Do1, addr1); `endif check0(); check1();", "for(i=0; i<M_SZ; i=i+1) begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_0(ADDR", "\"{filename}\" module tb_RAM{word_num}x{word_size}; localparam SIZE = `SIZE; localparam A_W =", "always #10 CLK = !CLK; integer i; \"\"\" test_port_1RW1R =", "(byte << (addr[$clog2(SIZE)-1:0] * 8)); @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE", "1; \"\"\" single_ported_custom_test = \"\"\" Phase = 0; // Perform", "`endif for(i=0; i<M_SZ; i=i+SIZE) begin ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFC", "ADDR); mem_read_word_1(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end \"\"\" test_port_RW =", "Compiler. # See https://github.com/Cloud-V/DFFRAM for further info. # # Licensed", "ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFC ; RANDOM_BYTE = $urandom; mem_write_word(", "# # Unless required by applicable law or agreed to", "Temporary override: IcarusVerilog cannot read these for some reason ^", "i<M_SZ; i=i+SIZE) begin ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFC ; RANDOM_BYTE", "begin ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFC ; RANDOM_BYTE = $urandom;", "from same port ************************************************************/ Phase = 4; `ifdef VERBOSE_1 $display(\"\\\\nFinished", "from %0D\", Do0, addr); `endif check0(); end endtask task check0;", "CLK); `ifdef VERBOSE_2 $display(\"WRITE BYTE: 0x%X to %0X(%0D) (0x%X, %B)\",", "= word; @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE WORD: 0x%X to", "[(SIZE*8-1):0] RAM_DATA_RW; reg [(SIZE*8-1):0] RAM_DATA_R; genvar c; generate for (c=0;", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "begin if(EN0) begin RAM_DATA_RW <= RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c];", "= 0; // Perform a 2 word write then read", "// Byte Write then Read Phase = 3; `ifdef VERBOSE_1", "< SIZE; c = c+1) begin: mem_golden_model always @(posedge CLK)", "$display(\"\\\\nFinished Phase 0, starting Phase 1\"); `endif for(i=0; i<M_SZ; i=i+SIZE)", "\"\"\" tasks = \"\"\" task mem_write_byte(input [7:0] byte, input [A_W-1:0]", "VERBOSE_2 `define UNIT_DELAY #1 `define USE_LATCH 1 `define SIZE {word_size}/8", "ADDR); mem_read_word_1( ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end // Byte", "Version 2.0 (the \"License\"); # you may not use this", "Byte Write then Read Phase = 6; `ifdef VERBOSE_1 $display(\"\\\\nFinished", "begin if(RAM_DATA_RW !== Do0) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d, Iteration:", "[7:0] RANDOM_BYTE; event done; RAM{word_num} #(.USE_LATCH(`USE_LATCH), .WSIZE(SIZE)) SRAM ( .CLK(CLK),", "i=i+SIZE/2) begin ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFE; RANDOM_BYTE = $urandom;", "initial begin CLK = 0; WE0 = 0; EN0 =", "(($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_1(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end \"\"\"", "RAM_DATA_RW; reg [(SIZE*8-1):0] RAM_DATA_R; genvar c; generate for (c=0; c", "DFFRAM Memory Compiler. # See https://github.com/Cloud-V/DFFRAM for further info. #", "- Should be: 0x%X\", A1, Do1, RAM[A1/SIZE]); $fatal(1); end end", "2\"); `endif for(i=0; i<M_SZ; i=i+SIZE/2) begin ADDR = (($urandom%M_SZ)) &", "for some reason ^ `include \"hd_primitives.v\" `include \"hd_functional.v\" `include \"{filename}\"", "); end // HWord Write then Read Phase = 5;", "$display(\"WRITE BYTE: 0x%X to %0X(%0D) (0x%X, %B)\", byte, addr, addr,", ".EN0(EN0), .Di0(Di0), .Do(Do0), .A0(A0[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size});", "ADDR); mem_read_word_0(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end $display (\"\\\\n>> Test", "language governing permissions and # limitations under the License. RAM_instantiation", "begin ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFE; RANDOM_BYTE = $urandom; mem_write_hword(", "$dumpvars(0, tb_RAM{word_num}x{word_size}); @(done) $finish; end /* Memory golden Model */", "check1(); end endtask task mem_read_word_1(input [A_W-1:0] addr); begin @(posedge CLK);", "Phase 0, starting Phase 1\"); `endif for(i=0; i<M_SZ; i=i+SIZE) begin", "implied. # See the License for the specific language governing", "Write then Read Phase = 1; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase", "4\"); `endif for(i=0; i<M_SZ; i=i+SIZE) begin ADDR = (($urandom%M_SZ)) &", "0x%X\", A0, Do0, RAM[A0/SIZE]); $fatal(1); end end endtask \"\"\" dual_ported_tasks", "under the Apache License, Version 2.0 (the \"License\"); # you", "\"\"\" RAM_instantiation_1RW1R = \"\"\" /* An auto generated testbench to", "be: 0x%X\", A0, Do0, RAM[A0/SIZE]); $fatal(1); end end endtask \"\"\"", "`define SIZE {word_size}/8 //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/primitives.v\" //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/sky130_fd_sc_hd.v\" // // Temporary", "Phase 3, starting Phase 4\"); `endif for(i=0; i<M_SZ; i=i+SIZE) begin", "Phase 5, starting Phase 6\"); `endif for(i=0; i<M_SZ; i=i+1) begin", "i); $display(\"Address: 0x%X, READ: 0x%X - Should be: 0x%X\", A0,", ".CLK(CLK), .WE0(WE0), .EN0(EN0), .Di0(Di0), .Do(Do0), .A0(A0[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}.vcd\");", "Cloud V Project. # # This file is part of", "endgenerate \"\"\" begin_dual_ported_test = \"\"\" initial begin CLK = 0;", "Perform a single word write then read mem_write_word({{SIZE{{8'h90}}}}, 4); mem_read_word_0(4);", "a known pattern // Word Write then Read Phase =", "endtask task mem_write_word(input [SIZE*8-1:0] word, input [A_W-1:0] addr); begin @(posedge", "word write then read mem_write_word({{SIZE{{8'h90}}}}, 4); mem_read_word_0(4); \"\"\" RAM_instantiation_1RW1R =", "= $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR ); end //", "test_port_1RW1R = \"\"\" /*********************************************************** Write and read from different ports", "@(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE HWORD: 0x%X to %0X(%0D) (0x%X,", "= \"\"\" end \"\"\" tasks = \"\"\" task mem_write_byte(input [7:0]", "Phase 2, starting Phase 3\"); `endif for(i=0; i<M_SZ; i=i+1) begin", "by applicable law or agreed to in writing, software #", "begin RAM_DATA_R <= RAM[A1/SIZE]; end end end endgenerate \"\"\" begin_dual_ported_test", "mem_read_2words(4,8); \"\"\" start_test_common = \"\"\" always #10 CLK = !CLK;", "VERBOSE_1 $display(\"\\\\nFinished Phase 1, starting Phase 2\"); `endif for(i=0; i<M_SZ;", "#(.USE_LATCH(`USE_LATCH), .WSIZE(`SIZE)) SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0), .EN1(ENR), .Di0(Di0), .Do0(Do0),", "input [A_W-1:0] addr1); begin @(posedge CLK); A0= addr0;//[9:2]; A1= addr1;//[9:2];", "begin @(posedge CLK); A0 = addr;//[A_WIDTH:$clog2(SIZE)]; WE0 = {{SIZE/2{addr[$clog2(SIZE)-1]}},{SIZE/2{~addr[$clog2(SIZE)-1]}}}; Di0", "addr; WE0 = {SIZE{8'hFF}}; Di0 = word; @(posedge CLK); `ifdef", "Phase, i); $display(\"Address: 0x%X, READ: 0x%X - Should be: 0x%X\",", "localparam SIZE = `SIZE; localparam A_W = {addr_width}+$clog2(SIZE); localparam M_SZ", "= 0; WE0 = 0; EN0 = 1; \"\"\" single_ported_custom_test", "{SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR ); end // HWord Write then", "Should be: 0x%X\", A1, Do1, RAM[A1/SIZE]); $fatal(1); end end endtask", "mem_read_word_1( ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end // Byte Write", "8'hFC} ); end \"\"\" test_port_RW = \"\"\" /*********************************************************** Write and", "0; EN0 = 1; ENR = 1; \"\"\" dual_ported_custom_test =", "from %0D\", Do1, addr1); `endif check0(); check1(); end endtask task", "[A_W-1:0] addr1); begin @(posedge CLK); A0= addr0;//[9:2]; A1= addr1;//[9:2]; WE0", "Phase = 0; // Perform a 2 word write then", "Do1, addr); `endif check1(); end endtask task check1; begin if(RAM_DATA_R", "[(SIZE*8-1):0] Do0; reg [A_W-1:0] A0, ADDR; reg [7:0] Phase; reg", "); end // HWord Write then Read Phase = 2;", "$urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR & {{SIZE-1{8'hFF}}, 8'hFC} );", "8'hFC} ); end // Byte Write then Read Phase =", "starting Phase 6\"); `endif for(i=0; i<M_SZ; i=i+1) begin ADDR =", "(1 << addr[$clog2(SIZE)-1:0]); Di0 = (byte << (addr[$clog2(SIZE)-1:0] * 8));", "`ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 4, starting Phase 5\"); `endif for(i=0;", ".Di0(Di0), .Do0(Do0), .Do1(Do1), .A0(A0[A_W-1:$clog2(SIZE)]), .A1(A1[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}_1RW1R.vcd\"); $dumpvars(0,", "[7:0] byte, input [A_W-1:0] addr); begin @(posedge CLK); A0 =", "the License. RAM_instantiation = \"\"\" /* An auto generated testbench", "begin_dual_ported_test = \"\"\" initial begin CLK = 0; WE0 =", "\"\"\" initial begin CLK = 0; WE0 = 0; EN0", "*/ `define VERBOSE_1 `define VERBOSE_2 `define UNIT_DELAY #1 `define USE_LATCH", "@(posedge CLK); A0 = addr;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK);", "WE0; reg EN0; reg ENR; reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0]", "Phase 1\"); `endif for(i=0; i<M_SZ; i=i+SIZE) begin ADDR = (($urandom%M_SZ))", "word, input [A_W-1:0] addr); begin @(posedge CLK); A0 = addr;", "= (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_1(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end", "addr); begin @(posedge CLK); A0 = addr;//[9:2]; WE0 = {SIZE{8'h00}};", "<= Di0[8*(c+1)-1:8*c]; end end end endgenerate \"\"\" begin_single_ported_test = \"\"\"", "RAM[A1/SIZE]; end end end endgenerate \"\"\" begin_dual_ported_test = \"\"\" initial", "// Word Write then Read Phase = 1; `ifdef VERBOSE_1", "Do1; reg [A_W-1:0] A0, A1, ADDR; reg [7:0] Phase; reg", "<NAME> (<EMAIL>) */ `define VERBOSE_1 `define VERBOSE_2 `define UNIT_DELAY #1", "$display(\"WRITE WORD: 0x%X to %0X(%0D) (0x%X, %B)\", word, addr, addr,", "\"\"\" task mem_write_byte(input [7:0] byte, input [A_W-1:0] addr); begin @(posedge", "!== Do1) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d, Iteration: %0d\", Phase,", "American University in Cairo and the Cloud V Project. #", "task mem_write_word(input [SIZE*8-1:0] word, input [A_W-1:0] addr); begin @(posedge CLK);", "[A_W-1:0] addr); begin @(posedge CLK); A0 = addr;//[A_WIDTH:2]; WE0 =", "# # This file is part of the DFFRAM Memory", "UNIT_DELAY #1 `define USE_LATCH 1 `define SIZE {word_size}/8 //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/primitives.v\"", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "Unless required by applicable law or agreed to in writing,", "Fill the memory with a known pattern // Word Write", "ADDR ); end // HWord Write then Read Phase =", "`include \"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}_1RW1R; localparam SIZE = `SIZE;", "for(i=0; i<M_SZ; i=i+SIZE) begin ADDR = (($urandom%M_SZ)) & 'hFFFF_FFFC ;", "single_ported_custom_test = \"\"\" Phase = 0; // Perform a single", "@(posedge CLK); A0= addr0;//[9:2]; A1= addr1;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge", "`endif check0(); check1(); end endtask task mem_read_word_1(input [A_W-1:0] addr); begin", ".Do(Do0), .A0(A0[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}); @(done) $finish;", "Cairo and the Cloud V Project. # # This file", "the specific language governing permissions and # limitations under the", "limitations under the License. RAM_instantiation = \"\"\" /* An auto", "CLK = 0; WE0 = 0; EN0 = 1; \"\"\"", "); end // Byte Write then Read Phase = 6;", "applicable law or agreed to in writing, software # distributed", "$fatal(1); end end endtask \"\"\" dual_ported_tasks = \"\"\" task mem_read_2words(input", "A0 = addr;//[A_WIDTH:$clog2(SIZE)]; WE0 = {{SIZE/2{addr[$clog2(SIZE)-1]}},{SIZE/2{~addr[$clog2(SIZE)-1]}}}; Di0 = (hword <<", "auto generated testbench to verify RAM{word_num}x{word_size} Authors: <NAME> (<EMAIL>) <NAME>", "WE0); `endif WE0 = {SIZE{8'h00}}; end endtask task mem_write_hword(input [SIZE*8-1:0]", "SIZE {word_size}/8 //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/primitives.v\" //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/sky130_fd_sc_hd.v\" // // Temporary override:", "A0= addr0;//[9:2]; A1= addr1;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK); #5;", "0x%X - Should be: 0x%X\", A1, Do1, RAM[A1/SIZE]); $fatal(1); end", "0x%X to %0X(%0D) (0x%X, %B)\", byte, addr, addr, Di0, WE0);", "mem_write_word(input [SIZE*8-1:0] word, input [A_W-1:0] addr); begin @(posedge CLK); A0", "addr0); $display(\"READ WORD1: 0x%X from %0D\", Do1, addr1); `endif check0();", "\"\"\" start_test_common = \"\"\" always #10 CLK = !CLK; integer", "The American University in Cairo and the Cloud V Project.", "= {addr_width}+$clog2(SIZE); localparam M_SZ = 2**A_W; reg CLK; reg [(SIZE-1):0]", "CLK = 0; WE0 = 0; EN0 = 1; ENR", "CLK); A0 = addr;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK); #5;", "in writing, software # distributed under the License is distributed", "done; RAM{word_num}_1RW1R #(.USE_LATCH(`USE_LATCH), .WSIZE(`SIZE)) SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0), .EN1(ENR),", "reg [7:0] RANDOM_BYTE; event done; RAM{word_num}_1RW1R #(.USE_LATCH(`USE_LATCH), .WSIZE(`SIZE)) SRAM (", "ADDR; reg [7:0] Phase; reg [7:0] RANDOM_BYTE; event done; RAM{word_num}", "reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0; reg [A_W-1:0] A0, ADDR;", "Di0[8*(c+1)-1:8*c]; end end end endgenerate \"\"\" begin_single_ported_test = \"\"\" initial", "%0X(%0D) (0x%X, %B)\", byte, addr, addr, Di0, WE0); `endif WE0", "check0(); check1(); end endtask task mem_read_word_1(input [A_W-1:0] addr); begin @(posedge", "%0D\", Do1, addr); `endif check1(); end endtask task check1; begin", "Word Write then Read Phase = 1; `ifdef VERBOSE_1 $display(\"\\\\nFinished", "mem_read_word_0( ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end // Byte Write", "Read Phase = 6; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 5, starting", "if(RAM_DATA_RW !== Do0) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d, Iteration: %0d\",", "= {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD0: 0x%X", "/* Memory golden Model */ reg [(SIZE*8-1):0] RAM[(M_SZ)-1 : 0];", "Di0; wire [(SIZE*8-1):0] Do0; reg [A_W-1:0] A0, ADDR; reg [7:0]", "0x%X, READ: 0x%X - Should be: 0x%X\", A1, Do1, RAM[A1/SIZE]);", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "word; @(posedge CLK); `ifdef VERBOSE_2 $display(\"WRITE WORD: 0x%X to %0X(%0D)", "begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_0(ADDR & {{SIZE-1{8'hFF}}, 8'hFC}", "<< addr[$clog2(SIZE)-1:0]); Di0 = (byte << (addr[$clog2(SIZE)-1:0] * 8)); @(posedge", "License, Version 2.0 (the \"License\"); # you may not use", "end $display (\"\\\\n>> Test Passed! <<\\\\n\"); -> done; \"\"\" end_test", "`ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 0, starting Phase 1\"); `endif for(i=0;", "A1, Do1, RAM[A1/SIZE]); $fatal(1); end end endtask \"\"\" endmodule =", "# You may obtain a copy of the License at", "end end endgenerate \"\"\" begin_single_ported_test = \"\"\" initial begin CLK", "(($urandom%M_SZ)) & 'hFFFF_FFFE; RANDOM_BYTE = $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_1(", "// Fill the memory with a known pattern // Word", "\"\"\" begin_dual_ported_test = \"\"\" initial begin CLK = 0; WE0", "= \"\"\" task mem_read_2words(input [A_W-1:0] addr0, input [A_W-1:0] addr1); begin", "READ: 0x%X - Should be: 0x%X\", A1, Do1, RAM[A1/SIZE]); $fatal(1);", "RAM[A1/SIZE]); $fatal(1); end end endtask \"\"\" endmodule = \"\"\" endmodule", "VERBOSE_2 $display(\"READ WORD: 0x%X from %0D\", Do0, addr); `endif check0();", "[A_W-1:0] addr); begin @(posedge CLK); A0 = addr; WE0 =", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Write then Read Phase = 3; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase", "= 1; \"\"\" single_ported_custom_test = \"\"\" Phase = 0; //", "// HWord Write then Read Phase = 5; `ifdef VERBOSE_1", "check1(); end endtask task check1; begin if(RAM_DATA_R !== Do1) begin", "addr1;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef VERBOSE_2 $display(\"READ", "RAM{word_num} #(.USE_LATCH(`USE_LATCH), .WSIZE(SIZE)) SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0), .Di0(Di0), .Do(Do0),", "mem_write_byte($urandom%255, ADDR); mem_read_word_1(ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end \"\"\" test_port_RW", "©2020-2021 The American University in Cairo and the Cloud V", "[(SIZE*8-1):0] Do1; reg [A_W-1:0] A0, A1, ADDR; reg [7:0] Phase;", "Di0 = (hword << (addr[$clog2(SIZE)-1] * (SIZE/2)*8)); @(posedge CLK); `ifdef", "%0D\", Do0, addr0); $display(\"READ WORD1: 0x%X from %0D\", Do1, addr1);", "byte, input [A_W-1:0] addr); begin @(posedge CLK); A0 = addr;//[A_WIDTH:2];", "test_port_RW = \"\"\" /*********************************************************** Write and read from same port", "task check0; begin if(RAM_DATA_RW !== Do0) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase:", "\"\"\" /*********************************************************** Write and read from different ports ************************************************************/ //", "c; generate for (c=0; c < SIZE; c = c+1)", "$fatal(1); end end endtask \"\"\" endmodule = \"\"\" endmodule \"\"\"", "Write and read from different ports ************************************************************/ // Fill the", "<<\\\\t(Phase: %0d, Iteration: %0d\", Phase, i); $display(\"Address: 0x%X, READ: 0x%X", "i<M_SZ; i=i+1) begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_1(ADDR &", "$display(\"\\\\nFinished Phase 2, starting Phase 3\"); `endif for(i=0; i<M_SZ; i=i+1)", "the License for the specific language governing permissions and #", "`ifdef VERBOSE_2 $display(\"READ WORD: 0x%X from %0D\", Do0, addr); `endif", "hword, addr, addr, Di0, WE0); `endif WE0 = {SIZE{8'h00}}; end", "Di0, WE0); `endif WE0 = {SIZE{8'h00}}; end endtask task mem_write_hword(input", "Apache License, Version 2.0 (the \"License\"); # you may not", "either express or implied. # See the License for the", "\"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}; localparam SIZE = `SIZE; localparam", "ADDR); mem_read_word_0( ADDR ); end // HWord Write then Read", "CLK); A0= addr0;//[9:2]; A1= addr1;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK);", "CLK); `ifdef VERBOSE_2 $display(\"WRITE HWORD: 0x%X to %0X(%0D) (0x%X, %B)\",", "Phase = 0; // Perform a single word write then", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "WE0 = 0; EN0 = 1; \"\"\" single_ported_custom_test = \"\"\"", "then Read Phase = 3; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 2,", "VERBOSE_1 $display(\"\\\\nFinished Phase 4, starting Phase 5\"); `endif for(i=0; i<M_SZ;", "= $urandom; mem_write_hword( {SIZE/2{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR & {{SIZE-1{8'hFF}}, 8'hFC}", "Di0, WE0); `endif WE0 = {SIZE{8'h00}}; end endtask task mem_write_word(input", "endtask task check1; begin if(RAM_DATA_R !== Do1) begin $display(\"\\\\n>>Test Failed!", "= 6; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 5, starting Phase 6\");", "then Read Phase = 6; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 5,", "WE0); `endif WE0 = {SIZE{8'h00}}; end endtask task mem_read_word_0(input [A_W-1:0]", "`ifdef VERBOSE_2 $display(\"WRITE BYTE: 0x%X to %0X(%0D) (0x%X, %B)\", byte,", ".Di0(Di0), .Do(Do0), .A0(A0[A_W-1:$clog2(SIZE)]) ); initial begin $dumpfile(\"tb_RAM{word_num}x{word_size}.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}); @(done)", "tb_RAM{word_num}x{word_size}); @(done) $finish; end /* Memory golden Model */ reg", "generate for (c=0; c < SIZE; c = c+1) begin:", "`SIZE; localparam A_W = {addr_width}+$clog2(SIZE); localparam M_SZ = 2**A_W; reg", "tb_RAM{word_num}x{word_size}_1RW1R); @(done) $finish; end /* Memory golden Model */ reg", "\"\"\" /*********************************************************** Write and read from same port ************************************************************/ Phase", "addr); begin @(posedge CLK); A0 = addr;//[A_WIDTH:2]; WE0 = (1", "@(done) $finish; end /* Memory golden Model */ reg [(SIZE*8-1):0]", "$urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_1( ADDR ); end // HWord", "Project. # # This file is part of the DFFRAM", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "begin @(posedge CLK); A0= addr0;//[9:2]; A1= addr1;//[9:2]; WE0 = {SIZE{8'h00}};", "end // HWord Write then Read Phase = 2; `ifdef", "module tb_RAM{word_num}x{word_size}; localparam SIZE = `SIZE; localparam A_W = {addr_width}+$clog2(SIZE);", "EN0 = 1; \"\"\" single_ported_custom_test = \"\"\" Phase = 0;", "{SIZE{8'h00}}; end endtask task mem_write_hword(input [SIZE*8-1:0] hword, input [A_W-1:0] addr);", "endtask task mem_write_hword(input [SIZE*8-1:0] hword, input [A_W-1:0] addr); begin @(posedge", "[(SIZE*8-1):0] RAM_DATA_R; genvar c; generate for (c=0; c < SIZE;", "<= RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end if (ENR) begin", "addr0, input [A_W-1:0] addr1); begin @(posedge CLK); A0= addr0;//[9:2]; A1=", "= {SIZE{8'h00}}; end endtask task mem_write_hword(input [SIZE*8-1:0] hword, input [A_W-1:0]", "// HWord Write then Read Phase = 2; `ifdef VERBOSE_1", "************************************************************/ // Fill the memory with a known pattern //", "#10 CLK = !CLK; integer i; \"\"\" test_port_1RW1R = \"\"\"", "for(i=0; i<M_SZ; i=i+1) begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_1(ADDR", "`ifdef VERBOSE_2 $display(\"WRITE WORD: 0x%X to %0X(%0D) (0x%X, %B)\", word,", "WORD0: 0x%X from %0D\", Do0, addr0); $display(\"READ WORD1: 0x%X from", "WE0 = (1 << addr[$clog2(SIZE)-1:0]); Di0 = (byte << (addr[$clog2(SIZE)-1:0]", "SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0), .EN1(ENR), .Di0(Di0), .Do0(Do0), .Do1(Do1), .A0(A0[A_W-1:$clog2(SIZE)]),", "[A_W-1:0] addr); begin @(posedge CLK); A1 = addr;//[9:2]; WE0 =", "2**A_W; reg CLK; reg [(SIZE-1):0] WE0; reg EN0; reg [(SIZE*8-1):0]", "WE0 = {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD:", "CLK; reg [(SIZE-1):0] WE0; reg EN0; reg [(SIZE*8-1):0] Di0; wire", "\"\"\" task mem_read_2words(input [A_W-1:0] addr0, input [A_W-1:0] addr1); begin @(posedge", "V Project. # # This file is part of the", "reg [A_W-1:0] A0, A1, ADDR; reg [7:0] Phase; reg [7:0]", "begin $dumpfile(\"tb_RAM{word_num}x{word_size}.vcd\"); $dumpvars(0, tb_RAM{word_num}x{word_size}); @(done) $finish; end /* Memory golden", "#5; `ifdef VERBOSE_2 $display(\"READ WORD: 0x%X from %0D\", Do1, addr);", "0]; reg [(SIZE*8-1):0] RAM_DATA_RW; genvar c; generate for (c=0; c", "^ `include \"hd_primitives.v\" `include \"hd_functional.v\" `include \"{filename}\" module tb_RAM{word_num}x{word_size}_1RW1R; localparam", "@(posedge CLK); A0 = addr; WE0 = {SIZE{8'hFF}}; Di0 =", "\"\"\" end \"\"\" tasks = \"\"\" task mem_write_byte(input [7:0] byte,", "\"\"\" single_ported_custom_test = \"\"\" Phase = 0; // Perform a", "= 3; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 2, starting Phase 3\");", "0x%X from %0D\", Do0, addr); `endif check0(); end endtask task", "end endgenerate \"\"\" begin_dual_ported_test = \"\"\" initial begin CLK =", "4; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 3, starting Phase 4\"); `endif", "\"License\"); # you may not use this file except in", "IcarusVerilog cannot read these for some reason ^ `include \"hd_primitives.v\"", "(0x%X, %B)\", word, addr, addr, Di0, WE0); `endif WE0 =", "Read Phase = 1; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 0, starting", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "\"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/sky130_fd_sc_hd.v\" // // Temporary override: IcarusVerilog cannot read these for", "starting Phase 4\"); `endif for(i=0; i<M_SZ; i=i+SIZE) begin ADDR =", "starting Phase 3\"); `endif for(i=0; i<M_SZ; i=i+1) begin ADDR =", "6; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 5, starting Phase 6\"); `endif", "= (hword << (addr[$clog2(SIZE)-1] * (SIZE/2)*8)); @(posedge CLK); `ifdef VERBOSE_2", "\"\"\" /* An auto generated testbench to verify RAM{word_num}x{word_size} Authors:", "A_W = {addr_width}+$clog2(SIZE); localparam M_SZ = 2**A_W; reg CLK; reg", "= \"\"\" initial begin CLK = 0; WE0 = 0;", "ADDR); mem_read_word_1( ADDR ); end // HWord Write then Read", "\"{filename}\" module tb_RAM{word_num}x{word_size}_1RW1R; localparam SIZE = `SIZE; localparam A_W =", "# distributed under the License is distributed on an \"AS", "`endif WE0 = {SIZE{8'h00}}; end endtask task mem_write_word(input [SIZE*8-1:0] word,", "addr); begin @(posedge CLK); A0 = addr; WE0 = {SIZE{8'hFF}};", "#(.USE_LATCH(`USE_LATCH), .WSIZE(SIZE)) SRAM ( .CLK(CLK), .WE0(WE0), .EN0(EN0), .Di0(Di0), .Do(Do0), .A0(A0[A_W-1:$clog2(SIZE)])", "# Unless required by applicable law or agreed to in", "Do1) begin $display(\"\\\\n>>Test Failed! <<\\\\t(Phase: %0d, Iteration: %0d\", Phase, i);", "i); $display(\"Address: 0x%X, READ: 0x%X - Should be: 0x%X\", A1,", "addr;//[A_WIDTH:$clog2(SIZE)]; WE0 = {{SIZE/2{addr[$clog2(SIZE)-1]}},{SIZE/2{~addr[$clog2(SIZE)-1]}}}; Di0 = (hword << (addr[$clog2(SIZE)-1] *", "READ: 0x%X - Should be: 0x%X\", A0, Do0, RAM[A0/SIZE]); $fatal(1);", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "0x%X from %0D\", Do0, addr0); $display(\"READ WORD1: 0x%X from %0D\",", "CLK); #5; `ifdef VERBOSE_2 $display(\"READ WORD: 0x%X from %0D\", Do1,", "addr;//[9:2]; WE0 = {SIZE{8'h00}}; @(posedge CLK); #5; `ifdef VERBOSE_2 $display(\"READ", "`include \"{filename}\" module tb_RAM{word_num}x{word_size}; localparam SIZE = `SIZE; localparam A_W", "{addr_width}+$clog2(SIZE); localparam M_SZ = 2**A_W; reg CLK; reg [(SIZE-1):0] WE0;", "= (1 << addr[$clog2(SIZE)-1:0]); Di0 = (byte << (addr[$clog2(SIZE)-1:0] *", "= 0; EN0 = 1; \"\"\" single_ported_custom_test = \"\"\" Phase", "RAM_DATA_RW <= RAM[A0/SIZE]; if(WE0[c]) RAM[A0/SIZE][8*(c+1)-1:8*c] <= Di0[8*(c+1)-1:8*c]; end end end", "ADDR); mem_read_word_0( ADDR & {{SIZE-1{8'hFF}}, 8'hFC} ); end // Byte", "You may obtain a copy of the License at #", "<= RAM[A1/SIZE]; end end end endgenerate \"\"\" begin_dual_ported_test = \"\"\"", "RAM[A0/SIZE]); $fatal(1); end end endtask \"\"\" dual_ported_tasks = \"\"\" task", "Copyright ©2020-2021 The American University in Cairo and the Cloud", "0; WE0 = 0; EN0 = 1; ENR = 1;", "under the License. RAM_instantiation = \"\"\" /* An auto generated", "Phase = 2; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 1, starting Phase", "& 'hFFFF_FFFC ; RANDOM_BYTE = $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_0(", "input [A_W-1:0] addr); begin @(posedge CLK); A0 = addr; WE0", "same port ************************************************************/ Phase = 4; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase", "0x%X, READ: 0x%X - Should be: 0x%X\", A0, Do0, RAM[A0/SIZE]);", "`endif for(i=0; i<M_SZ; i=i+1) begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR);", "check0(); end endtask task check0; begin if(RAM_DATA_RW !== Do0) begin", "1 `define SIZE {word_size}/8 //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/primitives.v\" //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/sky130_fd_sc_hd.v\" // //", "//`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/primitives.v\" //`include \"{pdk_root}/sky130A/libs.ref/sky130_fd_sc_hd/verilog/sky130_fd_sc_hd.v\" // // Temporary override: IcarusVerilog cannot", "word, addr, addr, Di0, WE0); `endif WE0 = {SIZE{8'h00}}; end", "[7:0] Phase; reg [7:0] RANDOM_BYTE; event done; RAM{word_num} #(.USE_LATCH(`USE_LATCH), .WSIZE(SIZE))", "VERBOSE_1 $display(\"\\\\nFinished Phase 0, starting Phase 1\"); `endif for(i=0; i<M_SZ;", "EN0; reg [(SIZE*8-1):0] Di0; wire [(SIZE*8-1):0] Do0; reg [A_W-1:0] A0,", "reg [A_W-1:0] A0, ADDR; reg [7:0] Phase; reg [7:0] RANDOM_BYTE;", "Failed! <<\\\\t(Phase: %0d, Iteration: %0d\", Phase, i); $display(\"Address: 0x%X, READ:", "$display(\"READ WORD0: 0x%X from %0D\", Do0, addr0); $display(\"READ WORD1: 0x%X", "Phase = 5; `ifdef VERBOSE_1 $display(\"\\\\nFinished Phase 4, starting Phase", "to %0X(%0D) (0x%X, %B)\", byte, addr, addr, Di0, WE0); `endif", "the Apache License, Version 2.0 (the \"License\"); # you may", "= $urandom; mem_write_word( {SIZE{RANDOM_BYTE}}, ADDR); mem_read_word_0( ADDR ); end //", "VERBOSE_2 $display(\"WRITE BYTE: 0x%X to %0X(%0D) (0x%X, %B)\", byte, addr,", "CLK); A0 = addr;//[A_WIDTH:$clog2(SIZE)]; WE0 = {{SIZE/2{addr[$clog2(SIZE)-1]}},{SIZE/2{~addr[$clog2(SIZE)-1]}}}; Di0 = (hword", "$display(\"\\\\nFinished Phase 3, starting Phase 4\"); `endif for(i=0; i<M_SZ; i=i+SIZE)", "wire [(SIZE*8-1):0] Do1; reg [A_W-1:0] A0, A1, ADDR; reg [7:0]", "i<M_SZ; i=i+1) begin ADDR = (($urandom%M_SZ)); mem_write_byte($urandom%255, ADDR); mem_read_word_0(ADDR &", "task mem_read_word_1(input [A_W-1:0] addr); begin @(posedge CLK); A1 = addr;//[9:2];", "2, starting Phase 3\"); `endif for(i=0; i<M_SZ; i=i+1) begin ADDR" ]
[ "get_bid(self): return self.bid def set_ask(self, ask): self.ask = float(ask) def", "= None def set_bid(self, bid): self.bid = float(bid) def get_bid(self):", "return self.ask def get_product_id(self): return self.product_id def set_product_id(self, product_id): self.product_id", "float(bid) def get_bid(self): return self.bid def set_ask(self, ask): self.ask =", "product_id = None def set_bid(self, bid): self.bid = float(bid) def", "set_ask(self, ask): self.ask = float(ask) def get_ask(self): return self.ask def", "= 0 product_id = None def set_bid(self, bid): self.bid =", "class CoinbaseResponse: bid = 0 ask = 0 product_id =", "ask): self.ask = float(ask) def get_ask(self): return self.ask def get_product_id(self):", "set_bid(self, bid): self.bid = float(bid) def get_bid(self): return self.bid def", "get_ask(self): return self.ask def get_product_id(self): return self.product_id def set_product_id(self, product_id):", "ask = 0 product_id = None def set_bid(self, bid): self.bid", "bid): self.bid = float(bid) def get_bid(self): return self.bid def set_ask(self,", "self.ask def get_product_id(self): return self.product_id def set_product_id(self, product_id): self.product_id =", "def get_product_id(self): return self.product_id def set_product_id(self, product_id): self.product_id = product_id", "0 product_id = None def set_bid(self, bid): self.bid = float(bid)", "float(ask) def get_ask(self): return self.ask def get_product_id(self): return self.product_id def", "CoinbaseResponse: bid = 0 ask = 0 product_id = None", "self.bid = float(bid) def get_bid(self): return self.bid def set_ask(self, ask):", "self.ask = float(ask) def get_ask(self): return self.ask def get_product_id(self): return", "0 ask = 0 product_id = None def set_bid(self, bid):", "def get_ask(self): return self.ask def get_product_id(self): return self.product_id def set_product_id(self,", "= 0 ask = 0 product_id = None def set_bid(self,", "bid = 0 ask = 0 product_id = None def", "None def set_bid(self, bid): self.bid = float(bid) def get_bid(self): return", "= float(bid) def get_bid(self): return self.bid def set_ask(self, ask): self.ask", "def get_bid(self): return self.bid def set_ask(self, ask): self.ask = float(ask)", "def set_bid(self, bid): self.bid = float(bid) def get_bid(self): return self.bid", "<reponame>krystianbajno/stocks<filename>services/stocks-api/app/api/clients/coinbase/CoinbaseResponse.py<gh_stars>1-10 class CoinbaseResponse: bid = 0 ask = 0 product_id", "self.bid def set_ask(self, ask): self.ask = float(ask) def get_ask(self): return", "return self.bid def set_ask(self, ask): self.ask = float(ask) def get_ask(self):", "def set_ask(self, ask): self.ask = float(ask) def get_ask(self): return self.ask", "= float(ask) def get_ask(self): return self.ask def get_product_id(self): return self.product_id" ]
[ "frequency. However, the xclim.indices implementation here will calculate the result", "must be one of \"D\", \"W\" or \"M\".' ) if", "on the time step. Parameters ---------- pr : xarray.DataArray Total", ": xarray.DataArray Average daily maximum temperature at daily, weekly, or", "\"\"\" pram = rate2amount(pr) return pram.resample(time=freq).sum(dim=\"time\", keep_attrs=True) # FIXME: src_timestep", "expressed in percent. Calculated as the standard deviation of temperature", "np.argmin, np.argmax, np.nanargmin, np.nanargmax. freq : str Temporal grouping. Returns", "Total precipitation of warmest/coldest quarter. The warmest (or coldest) quarter", "= xr.open_dataset(path_to_pr_file) >>> pr_warm_qrt = prcptot_wetdry_quarter(pr=p.pr, op='wettest', src_timestep='D') Notes -----", "/ mu def _from_other_arg( criteria: xarray.DataArray, output: xarray.DataArray, op, freq:", "should be calculated prior to calling the function. \"\"\" tas_qrt", "to calling the function. \"\"\" pram = rate2amount(pr) if op", "are converted to mm/day to avoid potentially small denominator values.", ">>> t = xr.open_dataset(path_to_tas_file).tas >>> tday_seasonality = xci.temperature_seasonality(t) >>> t_weekly", "rate (e.g. mm d-1, mm week-1). Returns ------- xarray.DataArray, [%]", "not used here. @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_period( pr: xarray.DataArray, *, op:", "values are converted to mm/day to avoid potentially small denominator", "ds.resample(time=freq).map(get_other_op) def _to_quarter( freq: str, pr: Optional[xarray.DataArray] = None, tas:", "lazy_indexing # Frequencies : YS: year start, QS-DEC: seasons starting", ">>> pweek_seasonality = xci.precip_seasonality(p_weekly) Notes ----- According to the ANUCLIM", "return out @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_quarter( pr: xarray.DataArray, op: str =", "\"driest\"' ) out = select_resample_op(pr_qrt, oper, freq) out.attrs[\"units\"] = pr_qrt.units", "keep_attrs=True) raise NotImplementedError( f'Unknown operation \"{op}\" ; op parameter but", "period. src_timestep : {'D', 'W', 'M'} Input data time frequency", "operation \"{op}\" ; op parameter but be one of \"wettest\"", "at daily, weekly, or monthly frequency. op : {'warmest', 'coldest'}", "the annual temperature range. Parameters ---------- tasmin : xarray.DataArray Average", "def get_other_op(dataset): all_nans = dataset.criteria.isnull().all(dim=dim) index = op(dataset.criteria.where(~all_nans, 0), dim=dim)", "cell of file `tas.day.nc` the annual temperature seasonality: >>> import", "import select_resample_op from .run_length import lazy_indexing # Frequencies : YS:", "in percent. Calculated as the standard deviation of precipitation values", "defined as 13 week periods, otherwise are 3 months. Parameters", "= daily_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) etr = extreme_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) with", "of file `tas.day.nc` the annual temperature seasonality: >>> import xclim.indices", "week-1], [mm month-1] or similar. op : {'wettest', 'driest'} Operation", "'wettest' calculate for the wettest quarter; 'driest' calculate for the", "[mm week-1], [mm month-1] or similar. src_timestep : {'D', 'W',", "if op == \"driest\": return pram.resample(time=freq).min(dim=\"time\", keep_attrs=True) raise NotImplementedError( f'Unknown", "= \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of wettest/driest", "week, or month, depending on the time step. Parameters ----------", "on a week # Ensure units are back to a", "xarray.DataArray, pr: xarray.DataArray, op: str = None, src_timestep: str =", "daily, weekly or monthly time series to quarterly time series", "Resampling frequency. Returns ------- xarray.DataArray, [length] Total precipitation. Notes -----", "Returns ------- xarray.DataArray, [%] Isothermality Notes ----- According to the", "[%] Precipitation coefficient of variation Examples -------- The following would", "month, depending on the time step. Parameters ---------- pr :", "[ \"temperature_seasonality\", \"precip_seasonality\", \"tg_mean_warmcold_quarter\", \"tg_mean_wetdry_quarter\", \"prcptot_wetdry_quarter\", \"prcptot_warmcold_quarter\", \"prcptot\", \"prcptot_wetdry_period\", \"isothermality\",", "month start # See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases # -------------------------------------------------- # # ATTENTION:", "== \"driest\": return pram.resample(time=freq).min(dim=\"time\", keep_attrs=True) raise NotImplementedError( f'Unknown operation \"{op}\"", "from xclim.core.units import ( convert_units_to, declare_units, pint_multiply, rate2amount, units, units2pint,", "return pram.resample(time=freq).min(dim=\"time\", keep_attrs=True) raise NotImplementedError( f'Unknown operation \"{op}\" ; op", "seasons starting in december, MS: month start # See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases", "pr = convert_units_to(pr, \"mm d-1\") with xarray.set_options(keep_attrs=True): seas = 100", ": 'wettest' calculate wettest period ; 'driest' calculate driest period.", "select_resample_op(pr_qrt, oper, freq) out.attrs[\"units\"] = pr_qrt.units return out @declare_units(pr=\"[precipitation]\", tas=\"[temperature]\")", "as tas] Mean temperature values of the {op} quarter of", "temperature at daily, weekly, or monthly frequency. tasmax : xarray.DataArray", "mean diurnal range divided by the annual temperature range. Parameters", "wettest (or driest) quarter of the year is determined, and", "xclim.core.units import ( convert_units_to, declare_units, pint_multiply, rate2amount, units, units2pint, )", "\"W\" or \"M\".' ) if tas is not None: tas", "flux [mm d-1], [mm week-1], [mm month-1] or similar. op", "time frequency - One of daily, weekly or monthly. freq", "calculated prior to calling the function. \"\"\" pram = rate2amount(pr)", "daily maximum temperature at daily, weekly, or monthly frequency. freq", "frequency. \"\"\" ds = xarray.Dataset(data_vars={\"criteria\": criteria, \"output\": output}) dim =", "str = \"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of", "; 'coldest' calculate for the coldest quarter. src_timestep : {'D',", "or monthly. freq : str Resampling frequency. Returns ------- xarray.DataArray", "variation). The annual temperature coefficient of variation expressed in percent.", "months. Parameters ---------- pr : xarray.DataArray Total precipitation rate at", ">>> import xclim.indices as xci >>> p = xr.open_dataset(path_to_pr_file).pr >>>", "None: tas = tg_mean(tas, freq=\"7D\") if pr is not None:", "output=tas_qrt, op=xr_op, freq=freq) out.attrs = tas.attrs return out @declare_units(pr=\"[precipitation]\") def", "Input units need to be a rate >>> p_weekly.attrs['units'] =", "not one of \"wettest\" or \"driest\"' ) out = select_resample_op(pr_qrt,", "out = _from_other_arg(criteria=tas_qrt, output=pr_qrt, op=xr_op, freq=freq) out.attrs = pr_qrt.attrs return", "import lazy_indexing # Frequencies : YS: year start, QS-DEC: seasons", "for the warmest quarter ; 'coldest' calculate for the coldest", "FIXME: src_timestep is not used here. @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_period( pr:", "the standard deviation of precipitation values for a given year", "the annual temperature warmest quarter mean temperature: >>> import xclim.indices", "at daily, weekly, or monthly frequency. tasmax : xarray.DataArray Average", "daily (\"D\") or weekly (\"W\"), quarters are defined as 13", "3 else: raise NotImplementedError( f'Unknown input time frequency \"{freq}\": must", "step. Parameters ---------- pr : xarray.DataArray Total precipitation flux [mm", "pram.units if tas is not None: out = tas.rolling(time=window, center=False).mean(skipna=False)", "\"%\" return iso @declare_units(tas=\"[temperature]\") def temperature_seasonality(tas: xarray.DataArray) -> xarray.DataArray: r\"\"\"ANUCLIM", "or monthly frequency. Units need to be defined as a", "As such weekly or monthly input values, if desired, should", "= select_resample_op(pr_qrt, oper, freq) out.attrs[\"units\"] = pr_qrt.units return out @declare_units(pr=\"[precipitation]\",", "[mm d-1], [mm week-1], [mm month-1] or similar. src_timestep :", "the mean of those values. Parameters ---------- pr : xarray.DataArray", "be calculated prior to calling the function. \"\"\" tas =", "\"output\": output}) dim = \"time\" def get_other_op(dataset): all_nans = dataset.criteria.isnull().all(dim=dim)", "import ( convert_units_to, declare_units, pint_multiply, rate2amount, units, units2pint, ) from", "prior to calling the function. \"\"\" out = _to_quarter(src_timestep, tas=tas)", "time series to quarterly time series according to ANUCLIM specifications.\"\"\"", "\"D\", \"W\" or \"M\".' ) if tas is not None:", "values of the {op} quarter of each year. Examples --------", "seasonality: >>> import xclim.indices as xci >>> t = xr.open_dataset(path_to_tas_file).tas", "to calling the function. \"\"\" # determine input data frequency", ">>> import xclim.indices as xci >>> t = xr.open_dataset(path_to_tas_file) >>>", "def prcptot_warmcold_quarter( pr: xarray.DataArray, tas: xarray.DataArray, op: str = None,", "wettest/driest day, week, or month, depending on the time step.", "at daily, weekly, or monthly frequency. Units need to be", "are 3 months. Parameters ---------- tas : xarray.DataArray Mean temperature", "p = xr.open_dataset(path_to_pr_file) >>> pr_warm_qrt = prcptot_wetdry_quarter(pr=p.pr, op='wettest', src_timestep='D') Notes", "returns mm values pr_qrt = _to_quarter(src_timestep, pr=pr) try: oper =", "to calling the function. \"\"\" tas = convert_units_to(tas, \"K\") with", "daily, weekly, or monthly frequency. tas : xarray.DataArray Mean temperature", "tas = tg_mean(tas, freq=\"7D\") if pr is not None: #", "= op(dataset.criteria.where(~all_nans, 0), dim=dim) return lazy_indexing(dataset.output, index=index, dim=dim).where(~all_nans) return ds.resample(time=freq).map(get_other_op)", "annual precipitation Coefficient of Variation (C of V) expressed in", "or monthly time series to quarterly time series according to", "Optional import numpy as np import xarray from xclim.core.units import", "tas.rolling(time=window, center=False).mean(skipna=False) out.attrs = tas.attrs out = ensure_chunk_size(out, time=-1) return", "import xclim.indices as xci >>> p = xr.open_dataset(path_to_pr_file).pr >>> pday_seasonality", "but it does mean that the values are usually quite", "as 13 week periods, otherwise as 3 months. Parameters ----------", "by the annual temperature range. Parameters ---------- tasmin : xarray.DataArray", "[same as tas] Mean temperature values of the {op} quearter", "one of \"D\", \"W\" or \"M\".' ) if tas is", "_to_quarter(src_timestep, tas=tas) # returns mm values pr_qrt = _to_quarter(src_timestep, pr=pr)", "this period is calculated. If the input data frequency is", "(or equivalent) values are converted to mm/day to avoid potentially", "ANUCLIM indices.\"\"\" std = arr.resample(time=\"YS\").std(dim=\"time\") mu = arr.resample(time=\"YS\").mean(dim=\"time\") return std", "temperature of this period is calculated. If the input data", "Parameters ---------- tas : xarray.DataArray Mean temperature at daily, weekly,", "! # # -------------------------------------------------- # __all__ = [ \"temperature_seasonality\", \"precip_seasonality\",", "------- xarray.DataArray, [length] Total precipitation. Notes ----- According to the", "f'Unknown operation \"{op}\" ; op parameter but be one of", "op : {'wettest', 'driest'} Operation to perform: 'wettest' calculate for", "tasmax=\"[temperature]\") def isothermality( tasmin: xarray.DataArray, tasmax: xarray.DataArray, freq: str =", "'W', 'M'} Input data time frequency - One of daily,", "and the total precipitation of this period is calculated. If", "based on operation returning an index from criteria. Parameters ----------", "as np import xarray from xclim.core.units import ( convert_units_to, declare_units,", "values of the {op} quearter of each year. Examples --------", "be calculated prior to calling the function. \"\"\" # determine", "temperature: >>> import xclim.indices as xci >>> t = xr.open_dataset(path_to_tas_file)", "quarters are defined as 13 week periods, otherwise as 3", "r\"\"\"Isothermality. The mean diurnal range divided by the annual temperature", "result with input data with daily frequency as well. \"\"\"", ") -> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of wettest/driest quarter. The", "def tg_mean_wetdry_quarter( tas: xarray.DataArray, pr: xarray.DataArray, op: str = None,", "Returns ------- xarray.DataArray, [length] Total precipitation. Notes ----- According to", "annual wettest quarter total precipitation: >>> from xclim.indices import prcptot_wetdry_quarter", "xarray.DataArray: r\"\"\"ANUCLIM Precipitation Seasonality (C of V). The annual precipitation", "zero, but it does mean that the values are usually", "values should be at a weekly (or monthly) frequency. However,", "of the mean of those values. Parameters ---------- pr :", "frequency. op : str {'warmest', 'coldest'} Operation to perform: 'warmest'", "given year expressed as a percentage of the mean of", "freq=freq) with xarray.set_options(keep_attrs=True): iso = dtr / etr * 100", "as the standard deviation of precipitation values for a given", ": {'wettest', 'driest'} Operation to perform : 'wettest' calculate wettest", "= None, freq: str = \"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM", "expressed as a percentage of the mean of those temperatures.", "rate at daily, weekly, or monthly frequency. tas : xarray.DataArray", "convert_units_to(pr, \"mm d-1\") with xarray.set_options(keep_attrs=True): seas = 100 * _anuclim_coeff_var(pr)", "calculate for the coldest quarter. src_timestep : {'D', 'W', 'M'}", "-------------------------------------------------- # # ATTENTION: ASSUME ALL INDICES WRONG UNTIL TESTED", "/ s\"): pr = convert_units_to(pr, \"mm d-1\") with xarray.set_options(keep_attrs=True): seas", "out.attrs[\"units\"] = pram.units if tas is not None: out =", "= \"%\" return seas @declare_units(pr=\"[precipitation]\") def precip_seasonality( pr: xarray.DataArray, )", "\"wettest\" or \"driest\"' ) out = select_resample_op(pr_qrt, oper, freq) out.attrs[\"units\"]", "is determined, and the mean temperature of this period is", "`pr.day.nc` the annual precipitation seasonality: >>> import xclim.indices as xci", "= xci.temperature_seasonality(t_weekly) Notes ----- For this calculation, the mean in", "similar. src_timestep : {'D', 'W', 'M'} Input data time frequency", "select_resample_op from .run_length import lazy_indexing # Frequencies : YS: year", "data frequency is daily (\"D\") or weekly (\"W\") quarters are", "# noqa: D100 from typing import Optional import numpy as", "xci.tg_mean(t, freq='7D') >>> tweek_seasonality = xci.temperature_seasonality(t_weekly) Notes ----- For this", "(or coldest) quarter of the year is determined, and the", "xarray.DataArray) -> xarray.DataArray: r\"\"\"ANUCLIM temperature seasonality (coefficient of variation). The", "not None: pram = rate2amount(pr) out = pram.rolling(time=window, center=False).sum() out.attrs", "pr = convert_units_to(precip_accumulation(pr, freq=\"7D\"), \"mm\") pr.attrs[\"units\"] = \"mm/week\" freq =", "r\"\"\"ANUCLIM Total precipitation of wettest/driest quarter. The wettest (or driest)", "r\"\"\"ANUCLIM Total precipitation of warmest/coldest quarter. The warmest (or coldest)", "frequency. tasmax : xarray.DataArray Average daily maximum temperature at daily,", "wettest quarter ; 'driest' calculate driest quarter. src_timestep : {'D',", "should be calculated prior to calling the function. \"\"\" out", "{'wettest', 'driest'} Operation to perform : 'wettest' calculate wettest period", "will calculate the result with input data with daily frequency", "this calculation, the mean in degrees Kelvin is used. This", "standard deviation of temperature values for a given year expressed", "'coldest' calculate for the coldest quarter. src_timestep : {'D', 'W',", "src_timestep: str, freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM", "tg_mean(tas, freq=\"7D\") if pr is not None: # Accumulate on", "criteria is met at the given frequency. \"\"\" ds =", "or monthly frequency. op : {'wettest', 'driest'} Operation to perform:", "data with daily frequency as well. \"\"\" pram = rate2amount(pr)", "the mean in degrees Kelvin is used. This avoids the", "._simple import tg_mean from .generic import select_resample_op from .run_length import", "temperature at daily, weekly, or monthly frequency. freq : str", "*, op: str, src_timestep: str, freq: str = \"YS\" )", "\"prcptot_wetdry_period\", \"isothermality\", ] _xr_argops = { \"wettest\": xarray.DataArray.argmax, \"warmest\": xarray.DataArray.argmax,", "xarray.DataArray Average daily maximum temperature at daily, weekly, or monthly", "seas @declare_units(tas=\"[temperature]\") def tg_mean_warmcold_quarter( tas: xarray.DataArray, op: str = None,", "\"YS\" ) -> xarray.DataArray: r\"\"\"Isothermality. The mean diurnal range divided", "\"time\" def get_other_op(dataset): all_nans = dataset.criteria.isnull().all(dim=dim) index = op(dataset.criteria.where(~all_nans, 0),", "# See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases # -------------------------------------------------- # # ATTENTION: ASSUME ALL", "tas.attrs return out @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_quarter( pr: xarray.DataArray, op: str", "TESTED ! # # -------------------------------------------------- # __all__ = [ \"temperature_seasonality\",", "\"K\") with xarray.set_options(keep_attrs=True): seas = 100 * _anuclim_coeff_var(tas) seas.attrs[\"units\"] =", "are 3 months. Parameters ---------- pr : xarray.DataArray Total precipitation", "of the {op} quarter of each year Notes ----- According", "[length] Total precipitation of the {op} period. Notes ----- According", "{'D', 'W', 'M'} Input data time frequency - One of", "freq : str Resampling frequency. Returns ------- xarray.DataArray, [same as", "freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM precipitation of", "\"\"\" # determine input data frequency tas_qrt = _to_quarter(src_timestep, tas=tas)", "of the year is determined, and the mean temperature of", "except KeyError: raise NotImplementedError( f'Unknown operation \"{op}\" ; not one", "; 'driest' calculate driest quarter. src_timestep : {'D', 'W', 'M'}", "def prcptot( pr: xarray.DataArray, src_timestep: str = None, freq: str", "pr: xarray.DataArray, tas: xarray.DataArray, op: str = None, src_timestep: str", "\"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of warmest/coldest quarter.", "= { \"wettest\": \"max\", \"warmest\": \"max\", \"dryest\": \"min\", \"driest\": \"min\",", "equivalent) values are converted to mm/day to avoid potentially small", "; not one of \"wettest\" or \"driest\"' ) out =", "quarter total precipitation: >>> from xclim.indices import prcptot_wetdry_quarter >>> p", "= _to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op] out = _from_other_arg(criteria=tas_qrt, output=pr_qrt,", "xarray.DataArray: r\"\"\"ANUCLIM precipitation of the wettest/driest day, week, or month,", "temperature coefficient of variation Examples -------- The following would compute", "calculate for the driest quarter. src_timestep : {'D', 'W', 'M'}", "calculate driest quarter. src_timestep : {'D', 'W', 'M'} Input data", "driest quarter. src_timestep : {'D', 'W', 'M'} Input data time", "tas=\"[temperature]\") def prcptot_warmcold_quarter( pr: xarray.DataArray, tas: xarray.DataArray, op: str =", "frequency. Returns ------- xarray.DataArray, [same as tas] Mean temperature values", "variation for ANUCLIM indices.\"\"\" std = arr.resample(time=\"YS\").std(dim=\"time\") mu = arr.resample(time=\"YS\").mean(dim=\"time\")", "xarray.DataArray: \"\"\"Convert daily, weekly or monthly time series to quarterly", ": str Resampling frequency. Returns ------- xarray.DataArray : [mm] Total", "src_timestep: str = None, freq: str = \"YS\", ) ->", "str = \"YS\" ) -> xarray.DataArray: r\"\"\"Isothermality. The mean diurnal", "= tg_mean(tas, freq=\"7D\") if pr is not None: # Accumulate", "of \"wettest\" or \"driest\"' ) out = select_resample_op(pr_qrt, oper, freq)", "s\"): pr = convert_units_to(pr, \"mm d-1\") with xarray.set_options(keep_attrs=True): seas =", "criteria. Parameters ---------- criteria : DataArray Series on which operation", "precipitation values of the {op} quarter of each year Notes", "driest) quarter of the year is determined, and the mean", "driest period. src_timestep : {'D', 'W', 'M'} Input data time", "/ 2)) if pr is not None: pr = ensure_chunk_size(pr,", "@declare_units(pr=\"[precipitation]\") def precip_seasonality( pr: xarray.DataArray, ) -> xarray.DataArray: r\"\"\"ANUCLIM Precipitation", "= _to_quarter(src_timestep, tas=tas) # returns mm values pr_qrt = _to_quarter(src_timestep,", "def precip_seasonality( pr: xarray.DataArray, ) -> xarray.DataArray: r\"\"\"ANUCLIM Precipitation Seasonality", "at daily, weekly, or monthly frequency. tas : xarray.DataArray Mean", "xci.precip_seasonality(p) >>> p_weekly = xci.precip_accumulation(p, freq='7D') # Input units need", "seas.attrs[\"units\"] = \"%\" return seas @declare_units(tas=\"[temperature]\") def tg_mean_warmcold_quarter( tas: xarray.DataArray,", "maximum temperature at daily, weekly, or monthly frequency. freq :", "tweek_seasonality = xci.temperature_seasonality(t_weekly) Notes ----- For this calculation, the mean", "Total precipitation rate at daily, weekly, or monthly frequency. Units", "prior to calling the function. \"\"\" dtr = daily_temperature_range(tasmin=tasmin, tasmax=tasmax,", "pr: xarray.DataArray, *, op: str, src_timestep: str, freq: str =", "= _from_other_arg(criteria=tas_qrt, output=pr_qrt, op=xr_op, freq=freq) out.attrs = pr_qrt.attrs return out", "(ch. 6), input values should be at a weekly (or", "\"max\", \"dryest\": \"min\", \"driest\": \"min\", \"coldest\": \"min\", } @declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\")", "`tas.day.nc` the annual temperature seasonality: >>> import xclim.indices as xci", "calling the function. \"\"\" pram = rate2amount(pr) if op ==", "output}) dim = \"time\" def get_other_op(dataset): all_nans = dataset.criteria.isnull().all(dim=dim) index", ": [mm] Total precipitation values of the {op} quarter of", "annual temperature range. Parameters ---------- tasmin : xarray.DataArray Average daily", "criteria: xarray.DataArray, output: xarray.DataArray, op, freq: str ) -> xarray.DataArray:", ") from ._simple import tg_mean from .generic import select_resample_op from", "of the {op} quearter of each year. Examples -------- The", "the year is determined, and the total precipitation of this", "precipitation Coefficient of Variation (C of V) expressed in percent.", "of warmest/coldest quarter. The warmest (or coldest) quarter of the", "frequency. tas : xarray.DataArray Mean temperature at daily, weekly, or", "pr : xarray.DataArray Total precipitation flux [mm d-1], [mm week-1],", "xarray.DataArray Mean temperature at daily, weekly, or monthly frequency. Returns", "daily, weekly, or monthly frequency. op : str {'warmest', 'coldest'}", "xarray.DataArray, op, freq: str ) -> xarray.DataArray: \"\"\"Pick values from", "Returns ------- xarray.DataArray, [length] Total precipitation values of the {op}", "{op} quarter of each year. Notes ----- According to the", "str = None, src_timestep: str = None, freq: str =", "Total precipitation rate at daily, weekly, or monthly frequency. op", "Resampling frequency. Returns ------- xarray.DataArray, [length] Total precipitation of the", "quarter of the year is determined, and the mean temperature", "mu def _from_other_arg( criteria: xarray.DataArray, output: xarray.DataArray, op, freq: str", "import xclim.indices as xci >>> t = xr.open_dataset(path_to_tas_file) >>> t_warm_qrt", "monthly time series to quarterly time series according to ANUCLIM", "def _to_quarter( freq: str, pr: Optional[xarray.DataArray] = None, tas: Optional[xarray.DataArray]", ": DataArray Series to be indexed. op : func Function", "the wettest/driest day, week, or month, depending on the time", "of \"wettest\" or \"driest\"' ) def _anuclim_coeff_var(arr: xarray.DataArray) -> xarray.DataArray:", "Series to be indexed. op : func Function returning an", "returning an index, for example np.argmin, np.argmax, np.nanargmin, np.nanargmax. freq", "frequency. Returns ------- xarray.DataArray, [%] Isothermality Notes ----- According to", "deviation of precipitation values for a given year expressed as", "monthly frequency. op : {'wettest', 'driest'} Operation to perform :", "Units need to be defined as a rate (e.g. mm", "quarter ; 'driest' calculate driest quarter. src_timestep : {'D', 'W',", "Mean temperature coefficient of variation Examples -------- The following would", "_xr_argops = { \"wettest\": xarray.DataArray.argmax, \"warmest\": xarray.DataArray.argmax, \"dryest\": xarray.DataArray.argmin, \"driest\":", "mean of those values. Parameters ---------- pr : xarray.DataArray Total", "D100 from typing import Optional import numpy as np import", "those temperatures. Parameters ---------- tas : xarray.DataArray Mean temperature at", "{ \"wettest\": xarray.DataArray.argmax, \"warmest\": xarray.DataArray.argmax, \"dryest\": xarray.DataArray.argmin, \"driest\": xarray.DataArray.argmin, \"coldest\":", "NotImplementedError( f'Unknown operation \"{op}\" ; not one of \"wettest\" or", "\"min\", } @declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\") def isothermality( tasmin: xarray.DataArray, tasmax: xarray.DataArray,", "xarray.DataArray, [%] Isothermality Notes ----- According to the ANUCLIM user-guide", "Coefficient of Variation (C of V) expressed in percent. Calculated", "= xci.tg_mean_warmcold_quarter(tas=t.tas, op='warmest', src_timestep='daily') Notes ----- According to the ANUCLIM", "or monthly frequency. op : {'warmest', 'coldest'} Operation to perform:", "of V) expressed in percent. Calculated as the standard deviation", "# # ATTENTION: ASSUME ALL INDICES WRONG UNTIL TESTED !", "= tas.attrs return out @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_quarter( pr: xarray.DataArray, op:", "str, src_timestep: str, freq: str = \"YS\" ) -> xarray.DataArray:", "op : str {'warmest', 'coldest'} Operation to perform: 'warmest' calculate", "coldest) quarter of the year is determined, and the mean", "used here. @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_period( pr: xarray.DataArray, *, op: str,", "of variation). The annual temperature coefficient of variation expressed in", "\"\"\" out = _to_quarter(src_timestep, tas=tas) oper = _np_ops[op] out =", "-> xarray.DataArray: \"\"\"Pick values from output based on operation returning", "# -------------------------------------------------- # # ATTENTION: ASSUME ALL INDICES WRONG UNTIL", "determined, and the total precipitation of this period is calculated.", "of file `pr.day.nc` the annual wettest quarter total precipitation: >>>", "xarray.DataArray.argmax, \"warmest\": xarray.DataArray.argmax, \"dryest\": xarray.DataArray.argmin, \"driest\": xarray.DataArray.argmin, \"coldest\": xarray.DataArray.argmin, }", "frequency tas_qrt = _to_quarter(src_timestep, tas=tas) # returns mm values pr_qrt", "xarray.DataArray, freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"Isothermality. The", "input data with daily frequency as well. As such weekly", "= prcptot_wetdry_quarter(pr=p.pr, op='wettest', src_timestep='D') Notes ----- According to the ANUCLIM", "if pr is not None: pr = ensure_chunk_size(pr, time=np.ceil(window /", "weekly, or monthly frequency. pr : xarray.DataArray Total precipitation rate", "a \"rate\" for rate2amount below pr = convert_units_to(precip_accumulation(pr, freq=\"7D\"), \"mm\")", "as xci >>> p = xr.open_dataset(path_to_pr_file).pr >>> pday_seasonality = xci.precip_seasonality(p)", "frequency is daily (\"D) or weekly (\"W\"), quarters are defined", "is calculated. If the input data frequency is daily (\"D)", "be calculated prior to calling the function. \"\"\" tas_qrt =", "the values are usually quite small. According to the ANUCLIM", "xarray.DataArray Mean temperature at daily, weekly, or monthly frequency. pr", "xarray.DataArray, tas: xarray.DataArray, op: str = None, src_timestep: str =", "Parameters ---------- criteria : DataArray Series on which operation returning", "xci.precip_accumulation(p, freq='7D') # Input units need to be a rate", "for each grid cell of file `tas.day.nc` the annual temperature", "with daily frequency as well. \"\"\" pram = rate2amount(pr) return", "Frequencies : YS: year start, QS-DEC: seasons starting in december,", "= pr_qrt.attrs return out @declare_units(pr=\"[precipitation]\") def prcptot( pr: xarray.DataArray, src_timestep:", "# FIXME: src_timestep is not used here. @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_period(", ">>> t_weekly = xci.tg_mean(t, freq='7D') >>> tweek_seasonality = xci.temperature_seasonality(t_weekly) Notes", "xarray.DataArray Mean temperature at daily, weekly, or monthly frequency. op", "13 week periods, otherwise are 3 months. Parameters ---------- tas", "---------- pr : xarray.DataArray Total precipitation rate at daily, weekly,", ") -> xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of warmest/coldest quarter. The", "return seas @declare_units(tas=\"[temperature]\") def tg_mean_warmcold_quarter( tas: xarray.DataArray, op: str =", "wettest/driest quarter. The wettest (or driest) quarter of the year", "f'Unknown operation \"{op}\" ; not one of \"wettest\" or \"driest\"'", "xarray.DataArray) -> xarray.DataArray: \"\"\"Calculate the annual coefficient of variation for", "= xci.tg_mean(t, freq='7D') >>> tweek_seasonality = xci.temperature_seasonality(t_weekly) Notes ----- For", "{op} quarter of each year. Examples -------- The following would", "freq) out.attrs[\"units\"] = pr_qrt.units return out @declare_units(pr=\"[precipitation]\", tas=\"[temperature]\") def prcptot_warmcold_quarter(", "operation returning index is applied. output : DataArray Series to", "out.attrs = pr.attrs out.attrs[\"units\"] = pram.units if tas is not", "of this period is calculated. If the input data frequency", "= _to_quarter(src_timestep, pr=pr) try: oper = _np_ops[op] except KeyError: raise", "or monthly input values, if desired, should be calculated prior", "out = tas.rolling(time=window, center=False).mean(skipna=False) out.attrs = tas.attrs out = ensure_chunk_size(out,", "Isothermality Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch.", "the annual wettest quarter total precipitation: >>> from xclim.indices import", "\"min\", \"coldest\": \"min\", } @declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\") def isothermality( tasmin: xarray.DataArray,", "temperature at daily, weekly, or monthly frequency. op : str", "= None, ) -> xarray.DataArray: \"\"\"Convert daily, weekly or monthly", "of file `pr.day.nc` the annual precipitation seasonality: >>> import xclim.indices", "= xr.open_dataset(path_to_tas_file) >>> t_warm_qrt = xci.tg_mean_warmcold_quarter(tas=t.tas, op='warmest', src_timestep='daily') Notes -----", "rate2amount(pr) out = pram.rolling(time=window, center=False).sum() out.attrs = pr.attrs out.attrs[\"units\"] =", "- One of daily, weekly or monthly. freq : str", "seasonality (coefficient of variation). The annual temperature coefficient of variation", "precipitation seasonality: >>> import xclim.indices as xci >>> p =", "None, ) -> xarray.DataArray: \"\"\"Convert daily, weekly or monthly time", "output with input data with daily frequency as well. As", "'wettest' calculate wettest period ; 'driest' calculate driest period. src_timestep", "in december, MS: month start # See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases # --------------------------------------------------", "return out @declare_units(pr=\"[precipitation]\") def prcptot( pr: xarray.DataArray, src_timestep: str =", "Resampling frequency. Returns ------- xarray.DataArray : [mm] Total precipitation values", ") out = select_resample_op(pr_qrt, oper, freq) out.attrs[\"units\"] = pr_qrt.units return", "calculate the output with input data with daily frequency as", "quarter; 'driest' calculate for the driest quarter. src_timestep : {'D',", "0), dim=dim) return lazy_indexing(dataset.output, index=index, dim=dim).where(~all_nans) return ds.resample(time=freq).map(get_other_op) def _to_quarter(", "\"prcptot\", \"prcptot_wetdry_period\", \"isothermality\", ] _xr_argops = { \"wettest\": xarray.DataArray.argmax, \"warmest\":", "-> xarray.DataArray: r\"\"\"Isothermality. The mean diurnal range divided by the", "warmest/coldest quarter. The warmest (or coldest) quarter of the year", "xarray.set_options(keep_attrs=True): seas = 100 * _anuclim_coeff_var(tas) seas.attrs[\"units\"] = \"%\" return", "Operation to perform: 'warmest' calculate warmest quarter; 'coldest' calculate coldest", "\"mm/week\" >>> pweek_seasonality = xci.precip_seasonality(p_weekly) Notes ----- According to the", "the annual precipitation seasonality: >>> import xclim.indices as xci >>>", "defined as a rate (e.g. mm d-1, mm week-1). Returns", "precipitation. Parameters ---------- pr : xarray.DataArray Total precipitation flux [mm", "from .run_length import lazy_indexing # Frequencies : YS: year start,", "def tg_mean_warmcold_quarter( tas: xarray.DataArray, op: str = None, src_timestep: str", "seas = 100 * _anuclim_coeff_var(pr) seas.attrs[\"units\"] = \"%\" return seas", "xci >>> p = xr.open_dataset(path_to_pr_file).pr >>> pday_seasonality = xci.precip_seasonality(p) >>>", "be calculated prior to calling the function. \"\"\" out =", "precipitation rate at daily, weekly, or monthly frequency. op :", "= \"mm/week\" freq = \"W\" if freq.upper().startswith(\"W\"): window = 13", "\"driest\"' ) def _anuclim_coeff_var(arr: xarray.DataArray) -> xarray.DataArray: \"\"\"Calculate the annual", ": str Resampling frequency. Returns ------- xarray.DataArray, [length] Total precipitation", "year Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch.", "Ensure units are back to a \"rate\" for rate2amount below", "select_resample_op(out, oper, freq) out.attrs[\"units\"] = tas.units return out @declare_units(tas=\"[temperature]\", pr=\"[precipitation]\")", "@declare_units(pr=\"[precipitation]\") def prcptot_wetdry_period( pr: xarray.DataArray, *, op: str, src_timestep: str,", "freq) out.attrs[\"units\"] = tas.units return out @declare_units(tas=\"[temperature]\", pr=\"[precipitation]\") def tg_mean_wetdry_quarter(", "criteria, \"output\": output}) dim = \"time\" def get_other_op(dataset): all_nans =", "prcptot_wetdry_period( pr: xarray.DataArray, *, op: str, src_timestep: str, freq: str", "(e.g. mm d-1, mm week-1). Returns ------- xarray.DataArray, [%] Precipitation", "monthly frequency. tas : xarray.DataArray Mean temperature at daily, weekly,", "_from_other_arg(criteria=tas_qrt, output=pr_qrt, op=xr_op, freq=freq) out.attrs = pr_qrt.attrs return out @declare_units(pr=\"[precipitation]\")", "# # -------------------------------------------------- # __all__ = [ \"temperature_seasonality\", \"precip_seasonality\", \"tg_mean_warmcold_quarter\",", "'coldest' calculate coldest quarter. src_timestep : {'D', 'W', 'M'} Input", "[mm month-1] or similar. src_timestep : {'D', 'W', 'M'} Input", "daily, weekly, or monthly frequency. Returns ------- xarray.DataArray, [%] Mean", "# determine input data frequency tas_qrt = _to_quarter(src_timestep, tas=tas) #", "xarray.DataArray, tasmax: xarray.DataArray, freq: str = \"YS\" ) -> xarray.DataArray:", "of the year is determined, and the total precipitation of", "out.attrs = pr_qrt.attrs return out @declare_units(pr=\"[precipitation]\") def prcptot( pr: xarray.DataArray,", "week-1). Returns ------- xarray.DataArray, [%] Precipitation coefficient of variation Examples", "to calling the function. \"\"\" # returns mm values pr_qrt", "op, freq: str ) -> xarray.DataArray: \"\"\"Pick values from output", "Calculated as the standard deviation of temperature values for a", "or monthly. freq : str Resampling frequency. Returns ------- xarray.DataArray,", "\"prcptot_warmcold_quarter\", \"prcptot\", \"prcptot_wetdry_period\", \"isothermality\", ] _xr_argops = { \"wettest\": xarray.DataArray.argmax,", "pr is not None: # Accumulate on a week #", "total precipitation. Parameters ---------- pr : xarray.DataArray Total precipitation flux", "Accumulate on a week # Ensure units are back to", "precipitation values for a given year expressed as a percentage", "function. \"\"\" dtr = daily_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) etr = extreme_temperature_range(tasmin=tasmin,", "} _np_ops = { \"wettest\": \"max\", \"warmest\": \"max\", \"dryest\": \"min\",", "function. \"\"\" out = _to_quarter(src_timestep, tas=tas) oper = _np_ops[op] out", "s-1 (or equivalent) values are converted to mm/day to avoid", "def prcptot_wetdry_quarter( pr: xarray.DataArray, op: str = None, src_timestep: str", "declare_units, pint_multiply, rate2amount, units, units2pint, ) from xclim.core.utils import ensure_chunk_size", "for a given year expressed as a percentage of the", "[mm month-1] or similar. op : {'wettest', 'driest'} Operation to", "frequency is daily (\"D\") or weekly (\"W\") quarters are defined", "well. \"\"\" pram = rate2amount(pr) return pram.resample(time=freq).sum(dim=\"time\", keep_attrs=True) # FIXME:", "total precipitation: >>> from xclim.indices import prcptot_wetdry_quarter >>> p =", "of precipitation values for a given year expressed as a", "arr.resample(time=\"YS\").std(dim=\"time\") mu = arr.resample(time=\"YS\").mean(dim=\"time\") return std / mu def _from_other_arg(", "def _anuclim_coeff_var(arr: xarray.DataArray) -> xarray.DataArray: \"\"\"Calculate the annual coefficient of", "xarray from xclim.core.units import ( convert_units_to, declare_units, pint_multiply, rate2amount, units,", "tas is not None: tas = tg_mean(tas, freq=\"7D\") if pr", "for the driest quarter. src_timestep : {'D', 'W', 'M'} Input", "= pr.attrs out.attrs[\"units\"] = pram.units if tas is not None:", "weekly (\"W\") quarters are defined as 13 week periods, otherwise", "variation expressed in percent. Calculated as the standard deviation of", "Mean temperature values of the {op} quearter of each year.", "weekly (\"W\"), quarters are defined as 13 week periods, otherwise", "tas] Mean temperature values of the {op} quarter of each", "determine input data frequency tas_qrt = _to_quarter(src_timestep, tas=tas) # returns", "the input data frequency is daily (\"D\") or weekly (\"W\"),", "one of \"wettest\" or \"driest\"' ) def _anuclim_coeff_var(arr: xarray.DataArray) ->", "= pram.units if tas is not None: out = tas.rolling(time=window,", "out = select_resample_op(out, oper, freq) out.attrs[\"units\"] = tas.units return out", "xci >>> t = xr.open_dataset(path_to_tas_file) >>> t_warm_qrt = xci.tg_mean_warmcold_quarter(tas=t.tas, op='warmest',", "monthly frequency. pr : xarray.DataArray Total precipitation rate at daily,", "will calculate the output with input data with daily frequency", "None: out = tas.rolling(time=window, center=False).mean(skipna=False) out.attrs = tas.attrs out =", ") -> xarray.DataArray: \"\"\"Convert daily, weekly or monthly time series", "out = _from_other_arg(criteria=pr_qrt, output=tas_qrt, op=xr_op, freq=freq) out.attrs = tas.attrs return", "the {op} quarter of each year. Examples -------- The following", "temperature coefficient of variation expressed in percent. Calculated as the", "t_weekly = xci.tg_mean(t, freq='7D') >>> tweek_seasonality = xci.temperature_seasonality(t_weekly) Notes -----", "mm/day to avoid potentially small denominator values. \"\"\" # If", "by zero, but it does mean that the values are", "as xci >>> t = xr.open_dataset(path_to_tas_file).tas >>> tday_seasonality = xci.temperature_seasonality(t)", "return iso @declare_units(tas=\"[temperature]\") def temperature_seasonality(tas: xarray.DataArray) -> xarray.DataArray: r\"\"\"ANUCLIM temperature", "the {op} quearter of each year. Examples -------- The following", "None: # Accumulate on a week # Ensure units are", "not None: tas = ensure_chunk_size(tas, time=np.ceil(window / 2)) if pr", "\"M\".' ) if tas is not None: tas = ensure_chunk_size(tas,", "precipitation values of the {op} quarter of each year. Examples", "\"\"\" # If units in mm/sec convert to mm/days to", "implementation here will calculate the output with input data with", "for rate2amount below pr = convert_units_to(precip_accumulation(pr, freq=\"7D\"), \"mm\") pr.attrs[\"units\"] =", "Returns ------- DataArray Output values where criteria is met at", "'warmest' calculate for the warmest quarter ; 'coldest' calculate for", "to quarterly time series according to ANUCLIM specifications.\"\"\" if freq.upper().startswith(\"D\"):", "small denominator if units2pint(pr) == units(\"mm / s\"): pr =", "------- xarray.DataArray, [%] Precipitation coefficient of variation Examples -------- The", "weekly, or monthly frequency. op : str {'warmest', 'coldest'} Operation", "quarter. The warmest (or coldest) quarter of the year is", "calculate wettest quarter ; 'driest' calculate driest quarter. src_timestep :", "Total precipitation of the {op} period. Notes ----- According to", "----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch. 6), input", ": str Resampling frequency. Returns ------- xarray.DataArray, [length] Total precipitation.", "the xclim.indices implementation here will calculate the result with input", "with daily frequency as well. As such weekly or monthly", "to perform: 'wettest' calculate for the wettest quarter; 'driest' calculate", "tg_mean_warmcold_quarter( tas: xarray.DataArray, op: str = None, src_timestep: str =", "raise NotImplementedError( f'Unknown operation \"{op}\" ; op parameter but be", "------- DataArray Output values where criteria is met at the", "src_timestep='D') Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch.", "file `pr.day.nc` the annual precipitation seasonality: >>> import xclim.indices as", "If the input data frequency is daily (\"D) or weekly", "week # Ensure units are back to a \"rate\" for", "the {op} quarter of each year. Notes ----- According to", "\"dryest\": \"min\", \"driest\": \"min\", \"coldest\": \"min\", } @declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\") def", "quarter of each year. Notes ----- According to the ANUCLIM", "values of the {op} quarter of each year Notes -----", "extreme_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) with xarray.set_options(keep_attrs=True): iso = dtr / etr", "str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM precipitation of the", "rate at daily, weekly, or monthly frequency. Units need to", "units, units2pint, ) from xclim.core.utils import ensure_chunk_size from ._multivariate import", "---------- pr : xarray.DataArray Total precipitation flux [mm d-1], [mm", "xarray.DataArray, ) -> xarray.DataArray: r\"\"\"ANUCLIM Precipitation Seasonality (C of V).", "(C of V). The annual precipitation Coefficient of Variation (C", "wettest period ; 'driest' calculate driest period. src_timestep : {'D',", "str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of", "According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch. 6), input values", "daily (\"D\") or weekly (\"W\") quarters are defined as 13", "output based on operation returning an index from criteria. Parameters", "Average daily maximum temperature at daily, weekly, or monthly frequency.", "elif freq.upper().startswith(\"M\"): window = 3 else: raise NotImplementedError( f'Unknown input", "from xclim.indices import prcptot_wetdry_quarter >>> p = xr.open_dataset(path_to_pr_file) >>> pr_warm_qrt", "Mean temperature at daily, weekly, or monthly frequency. op :", "-> xarray.DataArray: r\"\"\"ANUCLIM precipitation of the wettest/driest day, week, or", "perform: 'wettest' calculate for the wettest quarter; 'driest' calculate for", "are defined as 13 week periods, otherwise are 3 months.", "convert_units_to(precip_accumulation(pr, freq=\"7D\"), \"mm\") pr.attrs[\"units\"] = \"mm/week\" freq = \"W\" if", "pr_qrt.units return out @declare_units(pr=\"[precipitation]\", tas=\"[temperature]\") def prcptot_warmcold_quarter( pr: xarray.DataArray, tas:", "week periods, otherwise are 3 months. Parameters ---------- tas :", "or monthly frequency. freq : str Resampling frequency. Returns -------", "xci.precip_seasonality(p_weekly) Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch.", "values are usually quite small. According to the ANUCLIM user-guide", "each year. Examples -------- The following would compute for each", "oper, freq) out.attrs[\"units\"] = tas.units return out @declare_units(tas=\"[temperature]\", pr=\"[precipitation]\") def", "import prcptot_wetdry_quarter >>> p = xr.open_dataset(path_to_pr_file) >>> pr_warm_qrt = prcptot_wetdry_quarter(pr=p.pr,", "weekly or monthly. freq : str Resampling frequency. Returns -------", "------- xarray.DataArray, [length] Total precipitation of the {op} period. Notes", "= _from_other_arg(criteria=pr_qrt, output=tas_qrt, op=xr_op, freq=freq) out.attrs = tas.attrs return out", "= \"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of warmest/coldest", "op == \"driest\": return pram.resample(time=freq).min(dim=\"time\", keep_attrs=True) raise NotImplementedError( f'Unknown operation", "@declare_units(tas=\"[temperature]\", pr=\"[precipitation]\") def tg_mean_wetdry_quarter( tas: xarray.DataArray, pr: xarray.DataArray, op: str", "\"\"\"Calculate the annual coefficient of variation for ANUCLIM indices.\"\"\" std", "for example np.argmin, np.argmax, np.nanargmin, np.nanargmax. freq : str Temporal", "input values, if desired, should be calculated prior to calling", "For this calculation, the mean in degrees Kelvin is used.", "frequency. However, the xclim.indices implementation here will calculate the output", "following would compute for each grid cell of file `pr.day.nc`", "be calculated prior to calling the function. If input units", "import xarray from xclim.core.units import ( convert_units_to, declare_units, pint_multiply, rate2amount,", "2)) if pr is not None: pram = rate2amount(pr) out", "\"\"\" # returns mm values pr_qrt = _to_quarter(src_timestep, pr=pr) try:", "------- xarray.DataArray, [same as tas] Mean temperature values of the", "freq='7D') # Input units need to be a rate >>>", "xclim.core.utils import ensure_chunk_size from ._multivariate import ( daily_temperature_range, extreme_temperature_range, precip_accumulation,", "or monthly frequency. Returns ------- xarray.DataArray, [%] Mean temperature coefficient", ": str Resampling frequency. Returns ------- xarray.DataArray, [%] Isothermality Notes", "-> xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of wettest/driest quarter. The wettest", "xarray.DataArray Total precipitation flux [mm d-1], [mm week-1], [mm month-1]", "13 elif freq.upper().startswith(\"M\"): window = 3 else: raise NotImplementedError( f'Unknown", "day, week, or month, depending on the time step. Parameters", "at daily, weekly, or monthly frequency. freq : str Resampling", "op : {'warmest', 'coldest'} Operation to perform: 'warmest' calculate for", "units2pint(pr) == units(\"mm / s\"): pr = convert_units_to(pr, \"mm d-1\")", "xci >>> t = xr.open_dataset(path_to_tas_file).tas >>> tday_seasonality = xci.temperature_seasonality(t) >>>", "and the mean temperature of this period is calculated. If", "function. \"\"\" # determine input data frequency tas_qrt = _to_quarter(src_timestep,", "p_weekly.attrs['units'] = \"mm/week\" >>> pweek_seasonality = xci.precip_seasonality(p_weekly) Notes ----- According", "pram.resample(time=freq).sum(dim=\"time\", keep_attrs=True) # FIXME: src_timestep is not used here. @declare_units(pr=\"[precipitation]\")", "= tas.rolling(time=window, center=False).mean(skipna=False) out.attrs = tas.attrs out = ensure_chunk_size(out, time=-1)", "calculate for the wettest quarter; 'driest' calculate for the driest", "to perform : 'wettest' calculate wettest quarter ; 'driest' calculate", "Examples -------- The following would compute for each grid cell", "Mean temperature of wettest/driest quarter. The wettest (or driest) quarter", "\"coldest\": \"min\", } @declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\") def isothermality( tasmin: xarray.DataArray, tasmax:", "to be indexed. op : func Function returning an index,", "of temperature values for a given year expressed as a", "tas_qrt = _to_quarter(src_timestep, tas=tas) pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op =", "with input data with daily frequency as well. As such", "with xarray.set_options(keep_attrs=True): out = _from_other_arg(criteria=pr_qrt, output=tas_qrt, op=xr_op, freq=freq) out.attrs =", "Mean temperature at daily, weekly, or monthly frequency. Returns -------", "= \"%\" return seas @declare_units(tas=\"[temperature]\") def tg_mean_warmcold_quarter( tas: xarray.DataArray, op:", "= _to_quarter(src_timestep, tas=tas) pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op]", "input data frequency is daily (\"D\") or weekly (\"W\"), quarters", "---------- tasmin : xarray.DataArray Average daily minimum temperature at daily,", "weekly (or monthly) frequency. However, the xclim.indices implementation here will", "pr_qrt = _to_quarter(src_timestep, pr=pr) try: oper = _np_ops[op] except KeyError:", "-> xarray.DataArray: \"\"\"Convert daily, weekly or monthly time series to", "not None: pr = ensure_chunk_size(pr, time=np.ceil(window / 2)) if pr", "month-1] or similar. op : {'wettest', 'driest'} Operation to perform", "Operation to perform : 'wettest' calculate wettest quarter ; 'driest'", "# ATTENTION: ASSUME ALL INDICES WRONG UNTIL TESTED ! #", ">>> p = xr.open_dataset(path_to_pr_file) >>> pr_warm_qrt = prcptot_wetdry_quarter(pr=p.pr, op='wettest', src_timestep='D')", "is met at the given frequency. \"\"\" ds = xarray.Dataset(data_vars={\"criteria\":", "frequency \"{freq}\": must be one of \"D\", \"W\" or \"M\".'", "(\"D) or weekly (\"W\"), quarters are defined as 13 week", "p_weekly = xci.precip_accumulation(p, freq='7D') # Input units need to be", "the given frequency. \"\"\" ds = xarray.Dataset(data_vars={\"criteria\": criteria, \"output\": output})", "-> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of warmest/coldest quarter. The warmest", "the mean of those temperatures. Parameters ---------- tas : xarray.DataArray", "{'warmest', 'coldest'} Operation to perform: 'warmest' calculate warmest quarter; 'coldest'", "flux [mm d-1], [mm week-1], [mm month-1] or similar. src_timestep", "tas: xarray.DataArray, op: str = None, src_timestep: str = None,", "pr=pr) try: oper = _np_ops[op] except KeyError: raise NotImplementedError( f'Unknown", "deviation of temperature values for a given year expressed as", "Seasonality (C of V). The annual precipitation Coefficient of Variation", "indexed. op : func Function returning an index, for example", "weekly or monthly input values, if desired, should be calculated", "{'wettest', 'driest'} Operation to perform: 'wettest' calculate for the wettest", "r\"\"\"ANUCLIM precipitation of the wettest/driest day, week, or month, depending", "values pr_qrt = _to_quarter(src_timestep, pr=pr) try: oper = _np_ops[op] except", "mu = arr.resample(time=\"YS\").mean(dim=\"time\") return std / mu def _from_other_arg( criteria:", "xarray.DataArray.argmin, \"coldest\": xarray.DataArray.argmin, } _np_ops = { \"wettest\": \"max\", \"warmest\":", "mm s-1 (or equivalent) values are converted to mm/day to", "iso.attrs[\"units\"] = \"%\" return iso @declare_units(tas=\"[temperature]\") def temperature_seasonality(tas: xarray.DataArray) ->", "driest) quarter of the year is determined, and the total", "One of daily, weekly or monthly. freq : str Resampling", "keep_attrs=True) if op == \"driest\": return pram.resample(time=freq).min(dim=\"time\", keep_attrs=True) raise NotImplementedError(", "coefficient of variation Examples -------- The following would compute for", "mm/sec convert to mm/days to avoid potentially small denominator if", "if freq.upper().startswith(\"W\"): window = 13 elif freq.upper().startswith(\"M\"): window = 3", "\"\"\"Pick values from output based on operation returning an index", ">>> p = xr.open_dataset(path_to_pr_file).pr >>> pday_seasonality = xci.precip_seasonality(p) >>> p_weekly", "pr.attrs[\"units\"] = \"mm/week\" freq = \"W\" if freq.upper().startswith(\"W\"): window =", "xarray.DataArray, [length] Total precipitation. Notes ----- According to the ANUCLIM", "op == \"wettest\": return pram.resample(time=freq).max(dim=\"time\", keep_attrs=True) if op == \"driest\":", "DataArray Series on which operation returning index is applied. output", "units2pint, ) from xclim.core.utils import ensure_chunk_size from ._multivariate import (", "freq : str Resampling frequency. Returns ------- xarray.DataArray, [length] Total", "precipitation. Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch.", "those values. Parameters ---------- pr : xarray.DataArray Total precipitation rate", "is not None: tas = tg_mean(tas, freq=\"7D\") if pr is", "of those values. Parameters ---------- pr : xarray.DataArray Total precipitation", "'coldest'} Operation to perform: 'warmest' calculate warmest quarter; 'coldest' calculate", "temperature range. Parameters ---------- tasmin : xarray.DataArray Average daily minimum", "grid cell of file `pr.day.nc` the annual wettest quarter total", "xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of warmest/coldest quarter. The warmest (or", "at a weekly (or monthly) frequency. However, the xclim.indices implementation", "of those temperatures. Parameters ---------- tas : xarray.DataArray Mean temperature", "mean that the values are usually quite small. According to", "denominator if units2pint(pr) == units(\"mm / s\"): pr = convert_units_to(pr,", "time series according to ANUCLIM specifications.\"\"\" if freq.upper().startswith(\"D\"): if tas", "is used. This avoids the possibility of having to divide", "None, freq: str = \"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Mean", "== units(\"mm / s\"): pr = convert_units_to(pr, \"mm d-1\") with", "index, for example np.argmin, np.argmax, np.nanargmin, np.nanargmax. freq : str", "return out @declare_units(tas=\"[temperature]\", pr=\"[precipitation]\") def tg_mean_wetdry_quarter( tas: xarray.DataArray, pr: xarray.DataArray,", "Notes ----- For this calculation, the mean in degrees Kelvin", "daily, weekly, or monthly frequency. freq : str Resampling frequency.", ": {'wettest', 'driest'} Operation to perform: 'wettest' calculate for the", "convert_units_to(tas, \"K\") with xarray.set_options(keep_attrs=True): seas = 100 * _anuclim_coeff_var(tas) seas.attrs[\"units\"]", "@declare_units(pr=\"[precipitation]\") def prcptot_wetdry_quarter( pr: xarray.DataArray, op: str = None, src_timestep:", "time=np.ceil(window / 2)) if pr is not None: pram =", "denominator values. \"\"\" # If units in mm/sec convert to", "output=pr_qrt, op=xr_op, freq=freq) out.attrs = pr_qrt.attrs return out @declare_units(pr=\"[precipitation]\") def", "defined as 13 week periods, otherwise as 3 months. Parameters", "well. As such weekly or monthly input values, if desired,", "Operation to perform: 'wettest' calculate for the wettest quarter; 'driest'", "out @declare_units(pr=\"[precipitation]\", tas=\"[temperature]\") def prcptot_warmcold_quarter( pr: xarray.DataArray, tas: xarray.DataArray, op:", "ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch. 6), input values should be at", "str Resampling frequency. Returns ------- xarray.DataArray, [%] Isothermality Notes -----", "= \"%\" return iso @declare_units(tas=\"[temperature]\") def temperature_seasonality(tas: xarray.DataArray) -> xarray.DataArray:", "weekly, or monthly frequency. tas : xarray.DataArray Mean temperature at", "# returns mm values pr_qrt = _to_quarter(src_timestep, pr=pr) try: oper", "str Resampling frequency. Returns ------- xarray.DataArray : [mm] Total precipitation", "func Function returning an index, for example np.argmin, np.argmax, np.nanargmin,", "Optional[xarray.DataArray] = None, ) -> xarray.DataArray: \"\"\"Convert daily, weekly or", "it does mean that the values are usually quite small.", "try: oper = _np_ops[op] except KeyError: raise NotImplementedError( f'Unknown operation", "(\"W\"), quarters are defined as 13 week periods, otherwise are", "f'Unknown input time frequency \"{freq}\": must be one of \"D\",", "\"driest\": xarray.DataArray.argmin, \"coldest\": xarray.DataArray.argmin, } _np_ops = { \"wettest\": \"max\",", "np.nanargmin, np.nanargmax. freq : str Temporal grouping. Returns ------- DataArray", "coldest) quarter of the year is determined, and the total", "WRONG UNTIL TESTED ! # # -------------------------------------------------- # __all__ =", "freq='7D') >>> tweek_seasonality = xci.temperature_seasonality(t_weekly) Notes ----- For this calculation,", "should be calculated prior to calling the function. If input", "in percent. Calculated as the standard deviation of temperature values", "out = _to_quarter(src_timestep, tas=tas) oper = _np_ops[op] out = select_resample_op(out,", ">>> tweek_seasonality = xci.temperature_seasonality(t_weekly) Notes ----- For this calculation, the", "p = xr.open_dataset(path_to_pr_file).pr >>> pday_seasonality = xci.precip_seasonality(p) >>> p_weekly =", "Mean temperature at daily, weekly, or monthly frequency. pr :", "\"rate\" for rate2amount below pr = convert_units_to(precip_accumulation(pr, freq=\"7D\"), \"mm\") pr.attrs[\"units\"]", "\"mm\") pr.attrs[\"units\"] = \"mm/week\" freq = \"W\" if freq.upper().startswith(\"W\"): window", "to mm/day to avoid potentially small denominator values. \"\"\" #", "avoids the possibility of having to divide by zero, but", "the warmest quarter ; 'coldest' calculate for the coldest quarter.", ") -> xarray.DataArray: r\"\"\"ANUCLIM Accumulated total precipitation. Parameters ---------- pr", "from output based on operation returning an index from criteria.", "std / mu def _from_other_arg( criteria: xarray.DataArray, output: xarray.DataArray, op,", "temperature seasonality: >>> import xclim.indices as xci >>> t =", "calculated prior to calling the function. \"\"\" tas_qrt = _to_quarter(src_timestep,", "= \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM Accumulated total precipitation. Parameters", "period. Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch.", "are defined as 13 week periods, otherwise as 3 months.", "which operation returning index is applied. output : DataArray Series", "input data frequency is daily (\"D) or weekly (\"W\"), quarters", "extreme_temperature_range, precip_accumulation, ) from ._simple import tg_mean from .generic import", "dtr = daily_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) etr = extreme_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq)", "be calculated prior to calling the function. \"\"\" pram =", "= 100 * _anuclim_coeff_var(tas) seas.attrs[\"units\"] = \"%\" return seas @declare_units(pr=\"[precipitation]\")", "units(\"mm / s\"): pr = convert_units_to(pr, \"mm d-1\") with xarray.set_options(keep_attrs=True):", "grid cell of file `tas.day.nc` the annual temperature seasonality: >>>", "is calculated. If the input data frequency is daily (\"D\")", ": xarray.DataArray Total precipitation rate at daily, weekly, or monthly", "= \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM precipitation of the wettest/driest", "daily, weekly, or monthly frequency. tasmax : xarray.DataArray Average daily", "[%] Mean temperature coefficient of variation Examples -------- The following", "xarray.DataArray, op: str = None, src_timestep: str = None, freq:", "xarray.DataArray, [%] Mean temperature coefficient of variation Examples -------- The", "perform: 'warmest' calculate warmest quarter; 'coldest' calculate coldest quarter. src_timestep", "file `pr.day.nc` the annual wettest quarter total precipitation: >>> from", "return pram.resample(time=freq).max(dim=\"time\", keep_attrs=True) if op == \"driest\": return pram.resample(time=freq).min(dim=\"time\", keep_attrs=True)", "grid cell of file `pr.day.nc` the annual precipitation seasonality: >>>", "[same as tas] Mean temperature values of the {op} quarter", "= xr.open_dataset(path_to_tas_file).tas >>> tday_seasonality = xci.temperature_seasonality(t) >>> t_weekly = xci.tg_mean(t,", "of the wettest/driest day, week, or month, depending on the", "for each grid cell of file `pr.day.nc` the annual wettest", "the function. \"\"\" pram = rate2amount(pr) if op == \"wettest\":", "as well. \"\"\" pram = rate2amount(pr) return pram.resample(time=freq).sum(dim=\"time\", keep_attrs=True) #", ">>> from xclim.indices import prcptot_wetdry_quarter >>> p = xr.open_dataset(path_to_pr_file) >>>", "frequency. op : {'wettest', 'driest'} Operation to perform: 'wettest' calculate", "grid cell of file `tas.day.nc` the annual temperature warmest quarter", "the annual temperature seasonality: >>> import xclim.indices as xci >>>", "(C of V) expressed in percent. Calculated as the standard", "'driest' calculate driest quarter. src_timestep : {'D', 'W', 'M'} Input", "= select_resample_op(out, oper, freq) out.attrs[\"units\"] = tas.units return out @declare_units(tas=\"[temperature]\",", "pram.rolling(time=window, center=False).sum() out.attrs = pr.attrs out.attrs[\"units\"] = pram.units if tas", "be defined as a rate (e.g. mm d-1, mm week-1).", "\"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM Accumulated total precipitation. Parameters ----------", "daily, weekly, or monthly frequency. op : {'wettest', 'driest'} Operation", "are usually quite small. According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf", "of variation for ANUCLIM indices.\"\"\" std = arr.resample(time=\"YS\").std(dim=\"time\") mu =", ") -> xarray.DataArray: r\"\"\"Isothermality. The mean diurnal range divided by", "( daily_temperature_range, extreme_temperature_range, precip_accumulation, ) from ._simple import tg_mean from", "= \"mm/week\" >>> pweek_seasonality = xci.precip_seasonality(p_weekly) Notes ----- According to", "quarter of the year is determined, and the total precipitation", "str = None, freq: str = \"YS\", ) -> xarray.DataArray:", "rate at daily, weekly, or monthly frequency. op : {'wettest',", "\"driest\": return pram.resample(time=freq).min(dim=\"time\", keep_attrs=True) raise NotImplementedError( f'Unknown operation \"{op}\" ;", "of having to divide by zero, but it does mean", "dtr / etr * 100 iso.attrs[\"units\"] = \"%\" return iso", "of \"D\", \"W\" or \"M\".' ) if tas is not", "# __all__ = [ \"temperature_seasonality\", \"precip_seasonality\", \"tg_mean_warmcold_quarter\", \"tg_mean_wetdry_quarter\", \"prcptot_wetdry_quarter\", \"prcptot_warmcold_quarter\",", "= convert_units_to(pr, \"mm d-1\") with xarray.set_options(keep_attrs=True): seas = 100 *", "function. \"\"\" # returns mm values pr_qrt = _to_quarter(src_timestep, pr=pr)", "in mm/sec convert to mm/days to avoid potentially small denominator", "pday_seasonality = xci.precip_seasonality(p) >>> p_weekly = xci.precip_accumulation(p, freq='7D') # Input", "to ANUCLIM specifications.\"\"\" if freq.upper().startswith(\"D\"): if tas is not None:", "] _xr_argops = { \"wettest\": xarray.DataArray.argmax, \"warmest\": xarray.DataArray.argmax, \"dryest\": xarray.DataArray.argmin,", "\"\"\" tas_qrt = _to_quarter(src_timestep, tas=tas) pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op", "op: str = None, src_timestep: str = None, freq: str", "str Resampling frequency. Returns ------- xarray.DataArray, [length] Total precipitation values", "with input data with daily frequency as well. \"\"\" pram", "daily, weekly, or monthly frequency. Units need to be defined", "oper, freq) out.attrs[\"units\"] = pr_qrt.units return out @declare_units(pr=\"[precipitation]\", tas=\"[temperature]\") def", ">>> pday_seasonality = xci.precip_seasonality(p) >>> p_weekly = xci.precip_accumulation(p, freq='7D') #", "calling the function. \"\"\" tas = convert_units_to(tas, \"K\") with xarray.set_options(keep_attrs=True):", "[length] Total precipitation values of the {op} quarter of each", "{op} quarter of each year Notes ----- According to the", ") -> xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of wettest/driest quarter. The", "be indexed. op : func Function returning an index, for", "import ( daily_temperature_range, extreme_temperature_range, precip_accumulation, ) from ._simple import tg_mean", "divide by zero, but it does mean that the values", "\"{op}\" ; op parameter but be one of \"wettest\" or", ": xarray.DataArray Total precipitation flux [mm d-1], [mm week-1], [mm", "13 week periods, otherwise are 3 months. Parameters ---------- pr", "ds = xarray.Dataset(data_vars={\"criteria\": criteria, \"output\": output}) dim = \"time\" def", "= None, src_timestep: str = None, freq: str = \"YS\",", "pram = rate2amount(pr) return pram.resample(time=freq).sum(dim=\"time\", keep_attrs=True) # FIXME: src_timestep is", "of V). The annual precipitation Coefficient of Variation (C of", "pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op] with xarray.set_options(keep_attrs=True): out", "Precipitation Seasonality (C of V). The annual precipitation Coefficient of", "the driest quarter. src_timestep : {'D', 'W', 'M'} Input data", "calculated. If the input data frequency is daily (\"D\") or", "rate2amount(pr) return pram.resample(time=freq).sum(dim=\"time\", keep_attrs=True) # FIXME: src_timestep is not used", "to calling the function. \"\"\" out = _to_quarter(src_timestep, tas=tas) oper", "xr.open_dataset(path_to_tas_file) >>> t_warm_qrt = xci.tg_mean_warmcold_quarter(tas=t.tas, op='warmest', src_timestep='daily') Notes ----- According", "\"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of wettest/driest quarter.", "values for a given year expressed as a percentage of", "{ \"wettest\": \"max\", \"warmest\": \"max\", \"dryest\": \"min\", \"driest\": \"min\", \"coldest\":", "calling the function. \"\"\" tas_qrt = _to_quarter(src_timestep, tas=tas) pr_qrt =", "minimum temperature at daily, weekly, or monthly frequency. tasmax :", "\"\"\" ds = xarray.Dataset(data_vars={\"criteria\": criteria, \"output\": output}) dim = \"time\"", ">>> import xclim.indices as xci >>> t = xr.open_dataset(path_to_tas_file).tas >>>", "pram = rate2amount(pr) if op == \"wettest\": return pram.resample(time=freq).max(dim=\"time\", keep_attrs=True)", "xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of wettest/driest quarter. The wettest (or", "below pr = convert_units_to(precip_accumulation(pr, freq=\"7D\"), \"mm\") pr.attrs[\"units\"] = \"mm/week\" freq", "V) expressed in percent. Calculated as the standard deviation of", "Returns ------- xarray.DataArray : [mm] Total precipitation values of the", "Temporal grouping. Returns ------- DataArray Output values where criteria is", "out @declare_units(pr=\"[precipitation]\") def prcptot( pr: xarray.DataArray, src_timestep: str = None,", "calculated prior to calling the function. \"\"\" out = _to_quarter(src_timestep,", "------- xarray.DataArray, [length] Total precipitation values of the {op} quarter", "prior to calling the function. \"\"\" pram = rate2amount(pr) if", "window = 3 else: raise NotImplementedError( f'Unknown input time frequency", "tasmin: xarray.DataArray, tasmax: xarray.DataArray, freq: str = \"YS\" ) ->", "frequency. op : {'warmest', 'coldest'} Operation to perform: 'warmest' calculate", "as a percentage of the mean of those temperatures. Parameters", "temperatures. Parameters ---------- tas : xarray.DataArray Mean temperature at daily,", "# Frequencies : YS: year start, QS-DEC: seasons starting in", "function. If input units are in mm s-1 (or equivalent)", "Resampling frequency. Returns ------- xarray.DataArray, [same as tas] Mean temperature", "user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch. 6), input values should be at a", "[mm d-1], [mm week-1], [mm month-1] or similar. op :", "divided by the annual temperature range. Parameters ---------- tasmin :", "_anuclim_coeff_var(arr: xarray.DataArray) -> xarray.DataArray: \"\"\"Calculate the annual coefficient of variation", "data frequency is daily (\"D\") or weekly (\"W\"), quarters are", "quarter. The wettest (or driest) quarter of the year is", "is not None: out = tas.rolling(time=window, center=False).mean(skipna=False) out.attrs = tas.attrs", "xarray.DataArray: r\"\"\"Isothermality. The mean diurnal range divided by the annual", "to be defined as a rate (e.g. mm d-1, mm", "year. Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch.", "op: str, src_timestep: str, freq: str = \"YS\" ) ->", "the time step. Parameters ---------- pr : xarray.DataArray Total precipitation", "(\"W\") quarters are defined as 13 week periods, otherwise are", "dim=dim) return lazy_indexing(dataset.output, index=index, dim=dim).where(~all_nans) return ds.resample(time=freq).map(get_other_op) def _to_quarter( freq:", "as xci >>> t = xr.open_dataset(path_to_tas_file) >>> t_warm_qrt = xci.tg_mean_warmcold_quarter(tas=t.tas,", "given frequency. \"\"\" ds = xarray.Dataset(data_vars={\"criteria\": criteria, \"output\": output}) dim", "r\"\"\"ANUCLIM Mean temperature of wettest/driest quarter. The wettest (or driest)", "src_timestep : {'D', 'W', 'M'} Input data time frequency -", "frequency. op : {'wettest', 'driest'} Operation to perform : 'wettest'", "frequency as well. As such weekly or monthly input values,", "3 months. Parameters ---------- tas : xarray.DataArray Mean temperature at", "@declare_units(pr=\"[precipitation]\", tas=\"[temperature]\") def prcptot_warmcold_quarter( pr: xarray.DataArray, tas: xarray.DataArray, op: str", "cell of file `pr.day.nc` the annual precipitation seasonality: >>> import", "\"warmest\": xarray.DataArray.argmax, \"dryest\": xarray.DataArray.argmin, \"driest\": xarray.DataArray.argmin, \"coldest\": xarray.DataArray.argmin, } _np_ops", "xclim.indices as xci >>> t = xr.open_dataset(path_to_tas_file).tas >>> tday_seasonality =", "= pr_qrt.units return out @declare_units(pr=\"[precipitation]\", tas=\"[temperature]\") def prcptot_warmcold_quarter( pr: xarray.DataArray,", "xarray.DataArray.argmin, } _np_ops = { \"wettest\": \"max\", \"warmest\": \"max\", \"dryest\":", "'coldest'} Operation to perform: 'warmest' calculate for the warmest quarter", "Total precipitation flux [mm d-1], [mm week-1], [mm month-1] or", "{'wettest', 'driest'} Operation to perform : 'wettest' calculate wettest quarter", ": xarray.DataArray Average daily minimum temperature at daily, weekly, or", "; 'driest' calculate driest period. src_timestep : {'D', 'W', 'M'}", "the annual coefficient of variation for ANUCLIM indices.\"\"\" std =", "be calculated prior to calling the function. \"\"\" # returns", ": str Temporal grouping. Returns ------- DataArray Output values where", "__all__ = [ \"temperature_seasonality\", \"precip_seasonality\", \"tg_mean_warmcold_quarter\", \"tg_mean_wetdry_quarter\", \"prcptot_wetdry_quarter\", \"prcptot_warmcold_quarter\", \"prcptot\",", "rate >>> p_weekly.attrs['units'] = \"mm/week\" >>> pweek_seasonality = xci.precip_seasonality(p_weekly) Notes", "freq: str = \"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation", "window = 13 elif freq.upper().startswith(\"M\"): window = 3 else: raise", "calculated prior to calling the function. \"\"\" tas = convert_units_to(tas,", "Optional[xarray.DataArray] = None, tas: Optional[xarray.DataArray] = None, ) -> xarray.DataArray:", "precip_accumulation, ) from ._simple import tg_mean from .generic import select_resample_op", "src_timestep is not used here. @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_period( pr: xarray.DataArray,", "on operation returning an index from criteria. Parameters ---------- criteria", "percentage of the mean of those temperatures. Parameters ---------- tas", "= { \"wettest\": xarray.DataArray.argmax, \"warmest\": xarray.DataArray.argmax, \"dryest\": xarray.DataArray.argmin, \"driest\": xarray.DataArray.argmin,", "range. Parameters ---------- tasmin : xarray.DataArray Average daily minimum temperature", "http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases # -------------------------------------------------- # # ATTENTION: ASSUME ALL INDICES WRONG", "---------- criteria : DataArray Series on which operation returning index", "freq: str, pr: Optional[xarray.DataArray] = None, tas: Optional[xarray.DataArray] = None,", ": str {'warmest', 'coldest'} Operation to perform: 'warmest' calculate warmest", "index = op(dataset.criteria.where(~all_nans, 0), dim=dim) return lazy_indexing(dataset.output, index=index, dim=dim).where(~all_nans) return", "standard deviation of precipitation values for a given year expressed", "series to quarterly time series according to ANUCLIM specifications.\"\"\" if", "cell of file `pr.day.nc` the annual wettest quarter total precipitation:", "start # See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases # -------------------------------------------------- # # ATTENTION: ASSUME", "the coldest quarter. src_timestep : {'D', 'W', 'M'} Input data", "is applied. output : DataArray Series to be indexed. op", "None, freq: str = \"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Total", "as a percentage of the mean of those values. Parameters", "frequency. pr : xarray.DataArray Total precipitation rate at daily, weekly,", "for the coldest quarter. src_timestep : {'D', 'W', 'M'} Input", "at daily, weekly, or monthly frequency. pr : xarray.DataArray Total", "pram.resample(time=freq).max(dim=\"time\", keep_attrs=True) if op == \"driest\": return pram.resample(time=freq).min(dim=\"time\", keep_attrs=True) raise", "See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases # -------------------------------------------------- # # ATTENTION: ASSUME ALL INDICES", "ATTENTION: ASSUME ALL INDICES WRONG UNTIL TESTED ! # #", "compute for each grid cell of file `tas.day.nc` the annual", "units need to be a rate >>> p_weekly.attrs['units'] = \"mm/week\"", "values from output based on operation returning an index from", "in mm s-1 (or equivalent) values are converted to mm/day", "\"dryest\": xarray.DataArray.argmin, \"driest\": xarray.DataArray.argmin, \"coldest\": xarray.DataArray.argmin, } _np_ops = {", "expressed in percent. Calculated as the standard deviation of precipitation", "for ANUCLIM indices.\"\"\" std = arr.resample(time=\"YS\").std(dim=\"time\") mu = arr.resample(time=\"YS\").mean(dim=\"time\") return", "= rate2amount(pr) out = pram.rolling(time=window, center=False).sum() out.attrs = pr.attrs out.attrs[\"units\"]", "\"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of warmest/coldest quarter.", "or monthly frequency. op : {'wettest', 'driest'} Operation to perform", "the result with input data with daily frequency as well.", "{op} quearter of each year. Examples -------- The following would", "or month, depending on the time step. Parameters ---------- pr", "precipitation rate at daily, weekly, or monthly frequency. tas :", "of the mean of those temperatures. Parameters ---------- tas :", "if desired, should be calculated prior to calling the function.", "None, tas: Optional[xarray.DataArray] = None, ) -> xarray.DataArray: \"\"\"Convert daily,", "= extreme_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) with xarray.set_options(keep_attrs=True): iso = dtr /", "xr.open_dataset(path_to_pr_file).pr >>> pday_seasonality = xci.precip_seasonality(p) >>> p_weekly = xci.precip_accumulation(p, freq='7D')", "potentially small denominator if units2pint(pr) == units(\"mm / s\"): pr", "if op == \"wettest\": return pram.resample(time=freq).max(dim=\"time\", keep_attrs=True) if op ==", "@declare_units(pr=\"[precipitation]\") def prcptot( pr: xarray.DataArray, src_timestep: str = None, freq:", "returning an index from criteria. Parameters ---------- criteria : DataArray", "is not None: tas = ensure_chunk_size(tas, time=np.ceil(window / 2)) if", "monthly frequency. op : {'warmest', 'coldest'} Operation to perform: 'warmest'", "= _np_ops[op] out = select_resample_op(out, oper, freq) out.attrs[\"units\"] = tas.units", "pr is not None: pram = rate2amount(pr) out = pram.rolling(time=window,", "to perform: 'warmest' calculate warmest quarter; 'coldest' calculate coldest quarter.", "index is applied. output : DataArray Series to be indexed.", "units in mm/sec convert to mm/days to avoid potentially small", "_to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op] out = _from_other_arg(criteria=tas_qrt, output=pr_qrt, op=xr_op,", "temperature warmest quarter mean temperature: >>> import xclim.indices as xci", "precipitation of this period is calculated. If the input data", ") -> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of warmest/coldest quarter. The", "\"%\" return seas @declare_units(tas=\"[temperature]\") def tg_mean_warmcold_quarter( tas: xarray.DataArray, op: str", "one of \"wettest\" or \"driest\"' ) out = select_resample_op(pr_qrt, oper,", "= 100 * _anuclim_coeff_var(pr) seas.attrs[\"units\"] = \"%\" return seas @declare_units(tas=\"[temperature]\")", "xarray.DataArray: r\"\"\"ANUCLIM Accumulated total precipitation. Parameters ---------- pr : xarray.DataArray", "d-1], [mm week-1], [mm month-1] or similar. src_timestep : {'D',", "std = arr.resample(time=\"YS\").std(dim=\"time\") mu = arr.resample(time=\"YS\").mean(dim=\"time\") return std / mu", "daily minimum temperature at daily, weekly, or monthly frequency. tasmax", "would compute for each grid cell of file `tas.day.nc` the", "met at the given frequency. \"\"\" ds = xarray.Dataset(data_vars={\"criteria\": criteria,", "------- xarray.DataArray, [%] Isothermality Notes ----- According to the ANUCLIM", "tas is not None: tas = ensure_chunk_size(tas, time=np.ceil(window / 2))", "seas = 100 * _anuclim_coeff_var(tas) seas.attrs[\"units\"] = \"%\" return seas", "as the standard deviation of temperature values for a given", "tas : xarray.DataArray Mean temperature at daily, weekly, or monthly", "at daily, weekly, or monthly frequency. Returns ------- xarray.DataArray, [%]", "_np_ops[op] out = select_resample_op(out, oper, freq) out.attrs[\"units\"] = tas.units return", "= ensure_chunk_size(tas, time=np.ceil(window / 2)) if pr is not None:", "or weekly (\"W\") quarters are defined as 13 week periods,", "a percentage of the mean of those temperatures. Parameters ----------", "quarters are defined as 13 week periods, otherwise are 3", "similar. op : {'wettest', 'driest'} Operation to perform : 'wettest'", "calculated prior to calling the function. \"\"\" dtr = daily_temperature_range(tasmin=tasmin,", "time=np.ceil(window / 2)) if pr is not None: pr =", "None, src_timestep: str = None, freq: str = \"YS\" )", "percent. Calculated as the standard deviation of temperature values for", "Returns ------- xarray.DataArray, [same as tas] Mean temperature values of", "str = \"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of", "Resampling frequency. Returns ------- xarray.DataArray, [length] Total precipitation values of", "the output with input data with daily frequency as well.", "tasmax : xarray.DataArray Average daily maximum temperature at daily, weekly,", "week periods, otherwise are 3 months. Parameters ---------- pr :", "import tg_mean from .generic import select_resample_op from .run_length import lazy_indexing", "frequency is daily (\"D\") or weekly (\"W\"), quarters are defined", "precipitation flux [mm d-1], [mm week-1], [mm month-1] or similar.", "of file `tas.day.nc` the annual temperature warmest quarter mean temperature:", ">>> tday_seasonality = xci.temperature_seasonality(t) >>> t_weekly = xci.tg_mean(t, freq='7D') >>>", "the wettest quarter; 'driest' calculate for the driest quarter. src_timestep", "months. Parameters ---------- tas : xarray.DataArray Mean temperature at daily,", "INDICES WRONG UNTIL TESTED ! # # -------------------------------------------------- # __all__", "for the wettest quarter; 'driest' calculate for the driest quarter.", "pweek_seasonality = xci.precip_seasonality(p_weekly) Notes ----- According to the ANUCLIM user-guide", "tas_qrt = _to_quarter(src_timestep, tas=tas) # returns mm values pr_qrt =", "xr.open_dataset(path_to_pr_file) >>> pr_warm_qrt = prcptot_wetdry_quarter(pr=p.pr, op='wettest', src_timestep='D') Notes ----- According", "monthly. freq : str Resampling frequency. Returns ------- xarray.DataArray :", "are in mm s-1 (or equivalent) values are converted to", "at the given frequency. \"\"\" ds = xarray.Dataset(data_vars={\"criteria\": criteria, \"output\":", "mm values pr_qrt = _to_quarter(src_timestep, pr=pr) try: oper = _np_ops[op]", "input data with daily frequency as well. \"\"\" pram =", "if units2pint(pr) == units(\"mm / s\"): pr = convert_units_to(pr, \"mm", "indices.\"\"\" std = arr.resample(time=\"YS\").std(dim=\"time\") mu = arr.resample(time=\"YS\").mean(dim=\"time\") return std /", "data frequency is daily (\"D) or weekly (\"W\"), quarters are", "of variation Examples -------- The following would compute for each", "UNTIL TESTED ! # # -------------------------------------------------- # __all__ = [", "of each year Notes ----- According to the ANUCLIM user-guide", "the input data frequency is daily (\"D) or weekly (\"W\"),", "here will calculate the result with input data with daily", "should be calculated prior to calling the function. \"\"\" pram", "[length] Total precipitation. Notes ----- According to the ANUCLIM user-guide", "\"temperature_seasonality\", \"precip_seasonality\", \"tg_mean_warmcold_quarter\", \"tg_mean_wetdry_quarter\", \"prcptot_wetdry_quarter\", \"prcptot_warmcold_quarter\", \"prcptot\", \"prcptot_wetdry_period\", \"isothermality\", ]", "to mm/days to avoid potentially small denominator if units2pint(pr) ==", "to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch. 6), input values should", "freq=freq) etr = extreme_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) with xarray.set_options(keep_attrs=True): iso =", "center=False).sum() out.attrs = pr.attrs out.attrs[\"units\"] = pram.units if tas is", "[mm] Total precipitation values of the {op} quarter of each", "NotImplementedError( f'Unknown operation \"{op}\" ; op parameter but be one", ": func Function returning an index, for example np.argmin, np.argmax,", "result with input data with daily frequency as well. As", "def isothermality( tasmin: xarray.DataArray, tasmax: xarray.DataArray, freq: str = \"YS\"", "DataArray Series to be indexed. op : func Function returning", "data with daily frequency as well. As such weekly or", "\"coldest\": xarray.DataArray.argmin, } _np_ops = { \"wettest\": \"max\", \"warmest\": \"max\",", "the function. \"\"\" dtr = daily_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) etr =", "xarray.DataArray, [length] Total precipitation values of the {op} quarter of", "freq: str = \"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Mean temperature", "file `tas.day.nc` the annual temperature warmest quarter mean temperature: >>>", "xclim.indices as xci >>> t = xr.open_dataset(path_to_tas_file) >>> t_warm_qrt =", "\"\"\" tas = convert_units_to(tas, \"K\") with xarray.set_options(keep_attrs=True): seas = 100", "would compute for each grid cell of file `pr.day.nc` the", "a weekly (or monthly) frequency. However, the xclim.indices implementation here", "as tas] Mean temperature values of the {op} quearter of", "calling the function. \"\"\" # determine input data frequency tas_qrt", "calculate driest period. src_timestep : {'D', 'W', 'M'} Input data", "The annual precipitation Coefficient of Variation (C of V) expressed", "3 months. Parameters ---------- pr : xarray.DataArray Total precipitation rate", "desired, should be calculated prior to calling the function. \"\"\"", "daily, weekly, or monthly frequency. op : {'warmest', 'coldest'} Operation", "year. Examples -------- The following would compute for each grid", "\"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM precipitation of the wettest/driest day,", "daily frequency as well. As such weekly or monthly input", "week periods, otherwise as 3 months. Parameters ---------- tas :", "if pr is not None: # Accumulate on a week", "need to be defined as a rate (e.g. mm d-1,", "frequency - One of daily, weekly or monthly. freq :", "starting in december, MS: month start # See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases #", "frequency. Returns ------- xarray.DataArray : [mm] Total precipitation values of", "monthly. freq : str Resampling frequency. Returns ------- xarray.DataArray, [length]", "KeyError: raise NotImplementedError( f'Unknown operation \"{op}\" ; not one of", "coefficient of variation for ANUCLIM indices.\"\"\" std = arr.resample(time=\"YS\").std(dim=\"time\") mu", "not None: out = tas.rolling(time=window, center=False).mean(skipna=False) out.attrs = tas.attrs out", "xci.tg_mean_warmcold_quarter(tas=t.tas, op='warmest', src_timestep='daily') Notes ----- According to the ANUCLIM user-guide", "\"{freq}\": must be one of \"D\", \"W\" or \"M\".' )", "pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op] out = _from_other_arg(criteria=tas_qrt,", "prcptot_wetdry_quarter >>> p = xr.open_dataset(path_to_pr_file) >>> pr_warm_qrt = prcptot_wetdry_quarter(pr=p.pr, op='wettest',", "Returns ------- xarray.DataArray, [%] Mean temperature coefficient of variation Examples", "'driest' calculate for the driest quarter. src_timestep : {'D', 'W',", "src_timestep: str = None, freq: str = \"YS\" ) ->", "= arr.resample(time=\"YS\").mean(dim=\"time\") return std / mu def _from_other_arg( criteria: xarray.DataArray,", "_anuclim_coeff_var(pr) seas.attrs[\"units\"] = \"%\" return seas @declare_units(tas=\"[temperature]\") def tg_mean_warmcold_quarter( tas:", "Parameters ---------- tasmin : xarray.DataArray Average daily minimum temperature at", "'driest'} Operation to perform : 'wettest' calculate wettest period ;", "of the {op} period. Notes ----- According to the ANUCLIM", "tasmax: xarray.DataArray, freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"Isothermality.", "back to a \"rate\" for rate2amount below pr = convert_units_to(precip_accumulation(pr,", "xclim.indices implementation here will calculate the result with input data", "xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of warmest/coldest quarter. The warmest (or", "@declare_units(tas=\"[temperature]\") def temperature_seasonality(tas: xarray.DataArray) -> xarray.DataArray: r\"\"\"ANUCLIM temperature seasonality (coefficient", "op=xr_op, freq=freq) out.attrs = tas.attrs return out @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_quarter(", "the function. If input units are in mm s-1 (or", "or \"driest\"' ) def _anuclim_coeff_var(arr: xarray.DataArray) -> xarray.DataArray: \"\"\"Calculate the", "otherwise as 3 months. Parameters ---------- tas : xarray.DataArray Mean", "iso = dtr / etr * 100 iso.attrs[\"units\"] = \"%\"", "pr = ensure_chunk_size(pr, time=np.ceil(window / 2)) if pr is not", "period ; 'driest' calculate driest period. src_timestep : {'D', 'W',", "precipitation of the {op} period. Notes ----- According to the", "dataset.criteria.isnull().all(dim=dim) index = op(dataset.criteria.where(~all_nans, 0), dim=dim) return lazy_indexing(dataset.output, index=index, dim=dim).where(~all_nans)", "warmest quarter ; 'coldest' calculate for the coldest quarter. src_timestep", "xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of wettest/driest quarter. The wettest (or", "oper = _np_ops[op] except KeyError: raise NotImplementedError( f'Unknown operation \"{op}\"", "op='warmest', src_timestep='daily') Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf", "calculated prior to calling the function. \"\"\" # determine input", "pr is not None: pr = ensure_chunk_size(pr, time=np.ceil(window / 2))", "Kelvin is used. This avoids the possibility of having to", "'driest' calculate driest period. src_timestep : {'D', 'W', 'M'} Input", "tas.units return out @declare_units(tas=\"[temperature]\", pr=\"[precipitation]\") def tg_mean_wetdry_quarter( tas: xarray.DataArray, pr:", "mean in degrees Kelvin is used. This avoids the possibility", "variation Examples -------- The following would compute for each grid", "pr=\"[precipitation]\") def tg_mean_wetdry_quarter( tas: xarray.DataArray, pr: xarray.DataArray, op: str =", "output : DataArray Series to be indexed. op : func", "that the values are usually quite small. According to the", "xarray.DataArray.argmax, \"dryest\": xarray.DataArray.argmin, \"driest\": xarray.DataArray.argmin, \"coldest\": xarray.DataArray.argmin, } _np_ops =", "freq : str Resampling frequency. Returns ------- xarray.DataArray : [mm]", "None: pram = rate2amount(pr) out = pram.rolling(time=window, center=False).sum() out.attrs =", ": xarray.DataArray Mean temperature at daily, weekly, or monthly frequency.", "Parameters ---------- pr : xarray.DataArray Total precipitation flux [mm d-1],", "a given year expressed as a percentage of the mean", "None: pr = ensure_chunk_size(pr, time=np.ceil(window / 2)) if pr is", "frequency as well. \"\"\" pram = rate2amount(pr) return pram.resample(time=freq).sum(dim=\"time\", keep_attrs=True)", "should be calculated prior to calling the function. \"\"\" tas", "tday_seasonality = xci.temperature_seasonality(t) >>> t_weekly = xci.tg_mean(t, freq='7D') >>> tweek_seasonality", "is daily (\"D\") or weekly (\"W\") quarters are defined as", "freq = \"W\" if freq.upper().startswith(\"W\"): window = 13 elif freq.upper().startswith(\"M\"):", "{op} period. Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf", "* _anuclim_coeff_var(tas) seas.attrs[\"units\"] = \"%\" return seas @declare_units(pr=\"[precipitation]\") def precip_seasonality(", "numpy as np import xarray from xclim.core.units import ( convert_units_to,", "parameter but be one of \"wettest\" or \"driest\"' ) def", "pram = rate2amount(pr) out = pram.rolling(time=window, center=False).sum() out.attrs = pr.attrs", "input time frequency \"{freq}\": must be one of \"D\", \"W\"", "values. Parameters ---------- pr : xarray.DataArray Total precipitation rate at", "xarray.DataArray Total precipitation rate at daily, weekly, or monthly frequency.", "mean temperature: >>> import xclim.indices as xci >>> t =", "= \"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of warmest/coldest", "https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch. 6), input values should be at a weekly", "temperature seasonality (coefficient of variation). The annual temperature coefficient of", "index=index, dim=dim).where(~all_nans) return ds.resample(time=freq).map(get_other_op) def _to_quarter( freq: str, pr: Optional[xarray.DataArray]", "diurnal range divided by the annual temperature range. Parameters ----------", "out.attrs[\"units\"] = pr_qrt.units return out @declare_units(pr=\"[precipitation]\", tas=\"[temperature]\") def prcptot_warmcold_quarter( pr:", "frequency. Units need to be defined as a rate (e.g.", "freq.upper().startswith(\"D\"): if tas is not None: tas = tg_mean(tas, freq=\"7D\")", "out @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_quarter( pr: xarray.DataArray, op: str = None,", "tas: Optional[xarray.DataArray] = None, ) -> xarray.DataArray: \"\"\"Convert daily, weekly", "(\"W\"), quarters are defined as 13 week periods, otherwise as", "center=False).mean(skipna=False) out.attrs = tas.attrs out = ensure_chunk_size(out, time=-1) return out", "\"max\", \"warmest\": \"max\", \"dryest\": \"min\", \"driest\": \"min\", \"coldest\": \"min\", }", "* _anuclim_coeff_var(pr) seas.attrs[\"units\"] = \"%\" return seas @declare_units(tas=\"[temperature]\") def tg_mean_warmcold_quarter(", "temperature values of the {op} quearter of each year. Examples", "This avoids the possibility of having to divide by zero,", "is not None: pr = ensure_chunk_size(pr, time=np.ceil(window / 2)) if", "or monthly frequency. tasmax : xarray.DataArray Average daily maximum temperature", "an index, for example np.argmin, np.argmax, np.nanargmin, np.nanargmax. freq :", "specifications.\"\"\" if freq.upper().startswith(\"D\"): if tas is not None: tas =", "'M'} Input data time frequency - One of daily, weekly", "Returns ------- xarray.DataArray, [%] Precipitation coefficient of variation Examples --------", "for each grid cell of file `pr.day.nc` the annual precipitation", ": YS: year start, QS-DEC: seasons starting in december, MS:", "# Input units need to be a rate >>> p_weekly.attrs['units']", "to be a rate >>> p_weekly.attrs['units'] = \"mm/week\" >>> pweek_seasonality", "the {op} period. Notes ----- According to the ANUCLIM user-guide", "src_timestep='daily') Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch.", "out = pram.rolling(time=window, center=False).sum() out.attrs = pr.attrs out.attrs[\"units\"] = pram.units", "(coefficient of variation). The annual temperature coefficient of variation expressed", "should be at a weekly (or monthly) frequency. However, the", "= dataset.criteria.isnull().all(dim=dim) index = op(dataset.criteria.where(~all_nans, 0), dim=dim) return lazy_indexing(dataset.output, index=index,", "quarter ; 'coldest' calculate for the coldest quarter. src_timestep :", "xarray.DataArray : [mm] Total precipitation values of the {op} quarter", "weekly or monthly time series to quarterly time series according", "= [ \"temperature_seasonality\", \"precip_seasonality\", \"tg_mean_warmcold_quarter\", \"tg_mean_wetdry_quarter\", \"prcptot_wetdry_quarter\", \"prcptot_warmcold_quarter\", \"prcptot\", \"prcptot_wetdry_period\",", "Total precipitation values of the {op} quarter of each year", "a rate (e.g. mm d-1, mm week-1). Returns ------- xarray.DataArray,", "str Resampling frequency. Returns ------- xarray.DataArray, [same as tas] Mean", "the input data frequency is daily (\"D\") or weekly (\"W\")", "pram.resample(time=freq).min(dim=\"time\", keep_attrs=True) raise NotImplementedError( f'Unknown operation \"{op}\" ; op parameter", "weekly, or monthly frequency. Units need to be defined as", "usually quite small. According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch.", "\"tg_mean_warmcold_quarter\", \"tg_mean_wetdry_quarter\", \"prcptot_wetdry_quarter\", \"prcptot_warmcold_quarter\", \"prcptot\", \"prcptot_wetdry_period\", \"isothermality\", ] _xr_argops =", "Parameters ---------- pr : xarray.DataArray Total precipitation rate at daily,", "xclim.indices implementation here will calculate the output with input data", "== \"wettest\": return pram.resample(time=freq).max(dim=\"time\", keep_attrs=True) if op == \"driest\": return", "get_other_op(dataset): all_nans = dataset.criteria.isnull().all(dim=dim) index = op(dataset.criteria.where(~all_nans, 0), dim=dim) return", "tas=tas) pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op] with xarray.set_options(keep_attrs=True):", "values, if desired, should be calculated prior to calling the", "_to_quarter(src_timestep, pr=pr) try: oper = _np_ops[op] except KeyError: raise NotImplementedError(", "here will calculate the output with input data with daily", "the mean temperature of this period is calculated. If the", "-> xarray.DataArray: r\"\"\"ANUCLIM temperature seasonality (coefficient of variation). The annual", "`tas.day.nc` the annual temperature warmest quarter mean temperature: >>> import", "`pr.day.nc` the annual wettest quarter total precipitation: >>> from xclim.indices", "@declare_units(tas=\"[temperature]\") def tg_mean_warmcold_quarter( tas: xarray.DataArray, op: str = None, src_timestep:", "ANUCLIM specifications.\"\"\" if freq.upper().startswith(\"D\"): if tas is not None: tas", "str Temporal grouping. Returns ------- DataArray Output values where criteria", "ASSUME ALL INDICES WRONG UNTIL TESTED ! # # --------------------------------------------------", "or monthly frequency. pr : xarray.DataArray Total precipitation rate at", "precipitation of warmest/coldest quarter. The warmest (or coldest) quarter of", "freq.upper().startswith(\"W\"): window = 13 elif freq.upper().startswith(\"M\"): window = 3 else:", "quite small. According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch. 6),", "quarter; 'coldest' calculate coldest quarter. src_timestep : {'D', 'W', 'M'}", "year start, QS-DEC: seasons starting in december, MS: month start", "NotImplementedError( f'Unknown input time frequency \"{freq}\": must be one of", "prcptot_warmcold_quarter( pr: xarray.DataArray, tas: xarray.DataArray, op: str = None, src_timestep:", "from typing import Optional import numpy as np import xarray", "year is determined, and the mean temperature of this period", "of variation expressed in percent. Calculated as the standard deviation", "= _to_quarter(src_timestep, tas=tas) oper = _np_ops[op] out = select_resample_op(out, oper,", "input values should be at a weekly (or monthly) frequency.", "the {op} quarter of each year Notes ----- According to", "depending on the time step. Parameters ---------- pr : xarray.DataArray", ") def _anuclim_coeff_var(arr: xarray.DataArray) -> xarray.DataArray: \"\"\"Calculate the annual coefficient", "-> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of wettest/driest quarter. The wettest", "= \"W\" if freq.upper().startswith(\"W\"): window = 13 elif freq.upper().startswith(\"M\"): window", "following would compute for each grid cell of file `tas.day.nc`", "warmest (or coldest) quarter of the year is determined, and", "index from criteria. Parameters ---------- criteria : DataArray Series on", "np import xarray from xclim.core.units import ( convert_units_to, declare_units, pint_multiply,", "each grid cell of file `pr.day.nc` the annual precipitation seasonality:", "example np.argmin, np.argmax, np.nanargmin, np.nanargmax. freq : str Temporal grouping.", "if pr is not None: pram = rate2amount(pr) out =", "if tas is not None: out = tas.rolling(time=window, center=False).mean(skipna=False) out.attrs", "weekly, or monthly frequency. tasmax : xarray.DataArray Average daily maximum", ": 'wettest' calculate wettest quarter ; 'driest' calculate driest quarter.", "100 iso.attrs[\"units\"] = \"%\" return iso @declare_units(tas=\"[temperature]\") def temperature_seasonality(tas: xarray.DataArray)", "or \"driest\"' ) out = select_resample_op(pr_qrt, oper, freq) out.attrs[\"units\"] =", "import xclim.indices as xci >>> t = xr.open_dataset(path_to_tas_file).tas >>> tday_seasonality", "\"isothermality\", ] _xr_argops = { \"wettest\": xarray.DataArray.argmax, \"warmest\": xarray.DataArray.argmax, \"dryest\":", "tg_mean_wetdry_quarter( tas: xarray.DataArray, pr: xarray.DataArray, op: str = None, src_timestep:", "The warmest (or coldest) quarter of the year is determined,", "prior to calling the function. \"\"\" # determine input data", "def _from_other_arg( criteria: xarray.DataArray, output: xarray.DataArray, op, freq: str )", "freq=\"7D\") if pr is not None: # Accumulate on a", "used. This avoids the possibility of having to divide by", "tg_mean from .generic import select_resample_op from .run_length import lazy_indexing #", "return out @declare_units(pr=\"[precipitation]\", tas=\"[temperature]\") def prcptot_warmcold_quarter( pr: xarray.DataArray, tas: xarray.DataArray,", "-------------------------------------------------- # __all__ = [ \"temperature_seasonality\", \"precip_seasonality\", \"tg_mean_warmcold_quarter\", \"tg_mean_wetdry_quarter\", \"prcptot_wetdry_quarter\",", "coefficient of variation expressed in percent. Calculated as the standard", "daily, weekly or monthly. freq : str Resampling frequency. Returns", "= ensure_chunk_size(pr, time=np.ceil(window / 2)) if pr is not None:", "tasmax=tasmax, freq=freq) with xarray.set_options(keep_attrs=True): iso = dtr / etr *", "temperature of warmest/coldest quarter. The warmest (or coldest) quarter of", "quearter of each year. Examples -------- The following would compute", "convert_units_to, declare_units, pint_multiply, rate2amount, units, units2pint, ) from xclim.core.utils import", "mm d-1, mm week-1). Returns ------- xarray.DataArray, [%] Precipitation coefficient", "weekly, or monthly frequency. freq : str Resampling frequency. Returns", "_xr_argops[op] with xarray.set_options(keep_attrs=True): out = _from_other_arg(criteria=pr_qrt, output=tas_qrt, op=xr_op, freq=freq) out.attrs", "otherwise are 3 months. Parameters ---------- tas : xarray.DataArray Mean", "calling the function. \"\"\" # returns mm values pr_qrt =", "Operation to perform : 'wettest' calculate wettest period ; 'driest'", "periods, otherwise as 3 months. Parameters ---------- tas : xarray.DataArray", "temperature values for a given year expressed as a percentage", "calculated. If the input data frequency is daily (\"D) or", "= _xr_argops[op] with xarray.set_options(keep_attrs=True): out = _from_other_arg(criteria=pr_qrt, output=tas_qrt, op=xr_op, freq=freq)", "as 3 months. Parameters ---------- tas : xarray.DataArray Mean temperature", "values of the {op} quarter of each year. Notes -----", "xr.open_dataset(path_to_tas_file).tas >>> tday_seasonality = xci.temperature_seasonality(t) >>> t_weekly = xci.tg_mean(t, freq='7D')", "calculated prior to calling the function. \"\"\" # returns mm", "is daily (\"D) or weekly (\"W\"), quarters are defined as", "of Variation (C of V) expressed in percent. Calculated as", ">>> p_weekly = xci.precip_accumulation(p, freq='7D') # Input units need to", "the function. \"\"\" tas = convert_units_to(tas, \"K\") with xarray.set_options(keep_attrs=True): seas", "Accumulated total precipitation. Parameters ---------- pr : xarray.DataArray Total precipitation", "Input data time frequency - One of daily, weekly or", "pr: xarray.DataArray, op: str = None, src_timestep: str = None,", "Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch. 6),", "monthly. freq : str Resampling frequency. Returns ------- xarray.DataArray, [same", "xr_op = _xr_argops[op] out = _from_other_arg(criteria=tas_qrt, output=pr_qrt, op=xr_op, freq=freq) out.attrs", "from criteria. Parameters ---------- criteria : DataArray Series on which", "\"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation of wettest/driest quarter.", "str ) -> xarray.DataArray: \"\"\"Pick values from output based on", "should be calculated prior to calling the function. \"\"\" dtr", "the function. \"\"\" # returns mm values pr_qrt = _to_quarter(src_timestep,", "prcptot_wetdry_quarter( pr: xarray.DataArray, op: str = None, src_timestep: str =", "annual temperature warmest quarter mean temperature: >>> import xclim.indices as", "week-1], [mm month-1] or similar. src_timestep : {'D', 'W', 'M'}", "ensure_chunk_size(pr, time=np.ceil(window / 2)) if pr is not None: pram", "quarter. src_timestep : {'D', 'W', 'M'} Input data time frequency", "precipitation of the wettest/driest day, week, or month, depending on", ") -> xarray.DataArray: \"\"\"Pick values from output based on operation", "as 13 week periods, otherwise are 3 months. Parameters ----------", "mean of those temperatures. Parameters ---------- tas : xarray.DataArray Mean", "all_nans = dataset.criteria.isnull().all(dim=dim) index = op(dataset.criteria.where(~all_nans, 0), dim=dim) return lazy_indexing(dataset.output,", "xarray.set_options(keep_attrs=True): out = _from_other_arg(criteria=pr_qrt, output=tas_qrt, op=xr_op, freq=freq) out.attrs = tas.attrs", "etr = extreme_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) with xarray.set_options(keep_attrs=True): iso = dtr", "input data frequency is daily (\"D\") or weekly (\"W\") quarters", "small. According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch. 6), input", "weekly, or monthly frequency. Returns ------- xarray.DataArray, [%] Mean temperature", "month-1] or similar. src_timestep : {'D', 'W', 'M'} Input data", "} @declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\") def isothermality( tasmin: xarray.DataArray, tasmax: xarray.DataArray, freq:", "periods, otherwise are 3 months. Parameters ---------- pr : xarray.DataArray", "temperature of wettest/driest quarter. The wettest (or driest) quarter of", "QS-DEC: seasons starting in december, MS: month start # See", "calculate coldest quarter. src_timestep : {'D', 'W', 'M'} Input data", "str Resampling frequency. Returns ------- xarray.DataArray, [length] Total precipitation of", "Total precipitation of wettest/driest quarter. The wettest (or driest) quarter", "xarray.DataArray: r\"\"\"ANUCLIM temperature seasonality (coefficient of variation). The annual temperature", "Total precipitation values of the {op} quarter of each year.", "to perform: 'warmest' calculate for the warmest quarter ; 'coldest'", "pint_multiply, rate2amount, units, units2pint, ) from xclim.core.utils import ensure_chunk_size from", "---------- tas : xarray.DataArray Mean temperature at daily, weekly, or", "= 3 else: raise NotImplementedError( f'Unknown input time frequency \"{freq}\":", "small denominator values. \"\"\" # If units in mm/sec convert", "etr * 100 iso.attrs[\"units\"] = \"%\" return iso @declare_units(tas=\"[temperature]\") def", "prior to calling the function. \"\"\" tas = convert_units_to(tas, \"K\")", "values. \"\"\" # If units in mm/sec convert to mm/days", "daily (\"D) or weekly (\"W\"), quarters are defined as 13", "the function. \"\"\" # determine input data frequency tas_qrt =", "Function returning an index, for example np.argmin, np.argmax, np.nanargmin, np.nanargmax.", "in degrees Kelvin is used. This avoids the possibility of", "\"\"\"Convert daily, weekly or monthly time series to quarterly time", "daily, weekly, or monthly frequency. pr : xarray.DataArray Total precipitation", "= pram.rolling(time=window, center=False).sum() out.attrs = pr.attrs out.attrs[\"units\"] = pram.units if", "be a rate >>> p_weekly.attrs['units'] = \"mm/week\" >>> pweek_seasonality =", "freq=freq) out.attrs = tas.attrs return out @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_quarter( pr:", "import Optional import numpy as np import xarray from xclim.core.units", "calculate warmest quarter; 'coldest' calculate coldest quarter. src_timestep : {'D',", "rate2amount below pr = convert_units_to(precip_accumulation(pr, freq=\"7D\"), \"mm\") pr.attrs[\"units\"] = \"mm/week\"", "as a rate (e.g. mm d-1, mm week-1). Returns -------", "tasmin : xarray.DataArray Average daily minimum temperature at daily, weekly,", "None, src_timestep: str = None, freq: str = \"YS\", )", "series according to ANUCLIM specifications.\"\"\" if freq.upper().startswith(\"D\"): if tas is", "return seas @declare_units(pr=\"[precipitation]\") def precip_seasonality( pr: xarray.DataArray, ) -> xarray.DataArray:", "function. \"\"\" tas = convert_units_to(tas, \"K\") with xarray.set_options(keep_attrs=True): seas =", "(or driest) quarter of the year is determined, and the", "\"warmest\": \"max\", \"dryest\": \"min\", \"driest\": \"min\", \"coldest\": \"min\", } @declare_units(tasmin=\"[temperature]\",", ">>> t = xr.open_dataset(path_to_tas_file) >>> t_warm_qrt = xci.tg_mean_warmcold_quarter(tas=t.tas, op='warmest', src_timestep='daily')", "xarray.DataArray: \"\"\"Pick values from output based on operation returning an", "# If units in mm/sec convert to mm/days to avoid", "freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"Isothermality. The mean", "values where criteria is met at the given frequency. \"\"\"", "= \"YS\", ) -> xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of wettest/driest", "applied. output : DataArray Series to be indexed. op :", "each year Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf", "the function. \"\"\" out = _to_quarter(src_timestep, tas=tas) oper = _np_ops[op]", ".run_length import lazy_indexing # Frequencies : YS: year start, QS-DEC:", "if tas is not None: tas = ensure_chunk_size(tas, time=np.ceil(window /", "temperature values of the {op} quarter of each year. Notes", "weekly, or monthly frequency. op : {'wettest', 'driest'} Operation to", "op : func Function returning an index, for example np.argmin,", "DataArray Output values where criteria is met at the given", "\"wettest\": xarray.DataArray.argmax, \"warmest\": xarray.DataArray.argmax, \"dryest\": xarray.DataArray.argmin, \"driest\": xarray.DataArray.argmin, \"coldest\": xarray.DataArray.argmin,", "/ etr * 100 iso.attrs[\"units\"] = \"%\" return iso @declare_units(tas=\"[temperature]\")", "of each year. Examples -------- The following would compute for", "perform: 'warmest' calculate for the warmest quarter ; 'coldest' calculate", "Calculated as the standard deviation of precipitation values for a", "----- For this calculation, the mean in degrees Kelvin is", "grouping. Returns ------- DataArray Output values where criteria is met", "\"%\" return seas @declare_units(pr=\"[precipitation]\") def precip_seasonality( pr: xarray.DataArray, ) ->", "The annual temperature coefficient of variation expressed in percent. Calculated", "units are in mm s-1 (or equivalent) values are converted", "to calling the function. If input units are in mm", "monthly frequency. tasmax : xarray.DataArray Average daily maximum temperature at", "year is determined, and the total precipitation of this period", "= convert_units_to(tas, \"K\") with xarray.set_options(keep_attrs=True): seas = 100 * _anuclim_coeff_var(tas)", "frequency. Returns ------- xarray.DataArray, [length] Total precipitation. Notes ----- According", "monthly frequency. Units need to be defined as a rate", "= arr.resample(time=\"YS\").std(dim=\"time\") mu = arr.resample(time=\"YS\").mean(dim=\"time\") return std / mu def", "_np_ops[op] except KeyError: raise NotImplementedError( f'Unknown operation \"{op}\" ; not", "freq=freq) out.attrs = pr_qrt.attrs return out @declare_units(pr=\"[precipitation]\") def prcptot( pr:", "13 week periods, otherwise as 3 months. Parameters ---------- tas", "def prcptot_wetdry_period( pr: xarray.DataArray, *, op: str, src_timestep: str, freq:", "xarray.set_options(keep_attrs=True): iso = dtr / etr * 100 iso.attrs[\"units\"] =", "calling the function. If input units are in mm s-1", "= tas.units return out @declare_units(tas=\"[temperature]\", pr=\"[precipitation]\") def tg_mean_wetdry_quarter( tas: xarray.DataArray,", "arr.resample(time=\"YS\").mean(dim=\"time\") return std / mu def _from_other_arg( criteria: xarray.DataArray, output:", "if tas is not None: tas = tg_mean(tas, freq=\"7D\") if", "annual temperature coefficient of variation expressed in percent. Calculated as", "calling the function. \"\"\" out = _to_quarter(src_timestep, tas=tas) oper =", "# returns mm values pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op =", "units are back to a \"rate\" for rate2amount below pr", "but be one of \"wettest\" or \"driest\"' ) def _anuclim_coeff_var(arr:", ">>> p_weekly.attrs['units'] = \"mm/week\" >>> pweek_seasonality = xci.precip_seasonality(p_weekly) Notes -----", "the total precipitation of this period is calculated. If the", "values pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op] out =", "percent. Calculated as the standard deviation of precipitation values for", "tas is not None: out = tas.rolling(time=window, center=False).mean(skipna=False) out.attrs =", "'warmest' calculate warmest quarter; 'coldest' calculate coldest quarter. src_timestep :", "= 13 elif freq.upper().startswith(\"M\"): window = 3 else: raise NotImplementedError(", "degrees Kelvin is used. This avoids the possibility of having", "of wettest/driest quarter. The wettest (or driest) quarter of the", "temperature at daily, weekly, or monthly frequency. Returns ------- xarray.DataArray,", "= None, src_timestep: str = None, freq: str = \"YS\"", "str = None, freq: str = \"YS\" ) -> xarray.DataArray:", "None, freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM Accumulated", "None: tas = ensure_chunk_size(tas, time=np.ceil(window / 2)) if pr is", "returns mm values pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op]", ".generic import select_resample_op from .run_length import lazy_indexing # Frequencies :", "str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM Accumulated total precipitation.", "However, the xclim.indices implementation here will calculate the output with", "criteria : DataArray Series on which operation returning index is", "to perform : 'wettest' calculate wettest period ; 'driest' calculate", "'driest'} Operation to perform : 'wettest' calculate wettest quarter ;", "or monthly frequency. tas : xarray.DataArray Mean temperature at daily,", "= None, tas: Optional[xarray.DataArray] = None, ) -> xarray.DataArray: \"\"\"Convert", "cell of file `tas.day.nc` the annual temperature warmest quarter mean", "t_warm_qrt = xci.tg_mean_warmcold_quarter(tas=t.tas, op='warmest', src_timestep='daily') Notes ----- According to the", "daily frequency as well. \"\"\" pram = rate2amount(pr) return pram.resample(time=freq).sum(dim=\"time\",", "or monthly frequency. op : str {'warmest', 'coldest'} Operation to", "\"{op}\" ; not one of \"wettest\" or \"driest\"' ) out", "daily_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) etr = extreme_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) with xarray.set_options(keep_attrs=True):", "Operation to perform: 'warmest' calculate for the warmest quarter ;", "a rate >>> p_weekly.attrs['units'] = \"mm/week\" >>> pweek_seasonality = xci.precip_seasonality(p_weekly)", "calculate the result with input data with daily frequency as", "of daily, weekly or monthly. freq : str Resampling frequency.", "d-1\") with xarray.set_options(keep_attrs=True): seas = 100 * _anuclim_coeff_var(pr) seas.attrs[\"units\"] =", "return lazy_indexing(dataset.output, index=index, dim=dim).where(~all_nans) return ds.resample(time=freq).map(get_other_op) def _to_quarter( freq: str,", "wettest quarter total precipitation: >>> from xclim.indices import prcptot_wetdry_quarter >>>", "tasmax=tasmax, freq=freq) etr = extreme_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) with xarray.set_options(keep_attrs=True): iso", "# Accumulate on a week # Ensure units are back", "pr=pr) xr_op = _xr_argops[op] with xarray.set_options(keep_attrs=True): out = _from_other_arg(criteria=pr_qrt, output=tas_qrt,", "from xclim.core.utils import ensure_chunk_size from ._multivariate import ( daily_temperature_range, extreme_temperature_range,", "= xci.precip_accumulation(p, freq='7D') # Input units need to be a", "# -------------------------------------------------- # __all__ = [ \"temperature_seasonality\", \"precip_seasonality\", \"tg_mean_warmcold_quarter\", \"tg_mean_wetdry_quarter\",", "are back to a \"rate\" for rate2amount below pr =", "coldest quarter. src_timestep : {'D', 'W', 'M'} Input data time", "iso @declare_units(tas=\"[temperature]\") def temperature_seasonality(tas: xarray.DataArray) -> xarray.DataArray: r\"\"\"ANUCLIM temperature seasonality", "be one of \"wettest\" or \"driest\"' ) def _anuclim_coeff_var(arr: xarray.DataArray)", "= xarray.Dataset(data_vars={\"criteria\": criteria, \"output\": output}) dim = \"time\" def get_other_op(dataset):", "frequency. freq : str Resampling frequency. Returns ------- xarray.DataArray, [%]", "calculated prior to calling the function. If input units are", "input data frequency tas_qrt = _to_quarter(src_timestep, tas=tas) # returns mm", "freq=\"7D\"), \"mm\") pr.attrs[\"units\"] = \"mm/week\" freq = \"W\" if freq.upper().startswith(\"W\"):", "else: raise NotImplementedError( f'Unknown input time frequency \"{freq}\": must be", "tas=tas) oper = _np_ops[op] out = select_resample_op(out, oper, freq) out.attrs[\"units\"]", "freq.upper().startswith(\"M\"): window = 3 else: raise NotImplementedError( f'Unknown input time", "However, the xclim.indices implementation here will calculate the result with", "frequency. Returns ------- xarray.DataArray, [length] Total precipitation values of the", "is daily (\"D\") or weekly (\"W\"), quarters are defined as", "_to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op] with xarray.set_options(keep_attrs=True): out = _from_other_arg(criteria=pr_qrt,", "If units in mm/sec convert to mm/days to avoid potentially", "\"tg_mean_wetdry_quarter\", \"prcptot_wetdry_quarter\", \"prcptot_warmcold_quarter\", \"prcptot\", \"prcptot_wetdry_period\", \"isothermality\", ] _xr_argops = {", "to calling the function. \"\"\" dtr = daily_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq)", "of the {op} quarter of each year. Notes ----- According", "100 * _anuclim_coeff_var(tas) seas.attrs[\"units\"] = \"%\" return seas @declare_units(pr=\"[precipitation]\") def", "ensure_chunk_size(tas, time=np.ceil(window / 2)) if pr is not None: pr", "warmest quarter mean temperature: >>> import xclim.indices as xci >>>", "percentage of the mean of those values. Parameters ---------- pr", "monthly input values, if desired, should be calculated prior to", "file `tas.day.nc` the annual temperature seasonality: >>> import xclim.indices as", "or weekly (\"W\"), quarters are defined as 13 week periods,", "pr.attrs out.attrs[\"units\"] = pram.units if tas is not None: out", "calling the function. \"\"\" dtr = daily_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) etr", "op : {'wettest', 'driest'} Operation to perform : 'wettest' calculate", "to divide by zero, but it does mean that the", "= convert_units_to(precip_accumulation(pr, freq=\"7D\"), \"mm\") pr.attrs[\"units\"] = \"mm/week\" freq = \"W\"", "out @declare_units(tas=\"[temperature]\", pr=\"[precipitation]\") def tg_mean_wetdry_quarter( tas: xarray.DataArray, pr: xarray.DataArray, op:", "6), input values should be at a weekly (or monthly)", "op=xr_op, freq=freq) out.attrs = pr_qrt.attrs return out @declare_units(pr=\"[precipitation]\") def prcptot(", "precipitation rate at daily, weekly, or monthly frequency. Units need", "having to divide by zero, but it does mean that", "the standard deviation of temperature values for a given year", "quarter of each year Notes ----- According to the ANUCLIM", "desired, should be calculated prior to calling the function. If", "@declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\") def isothermality( tasmin: xarray.DataArray, tasmax: xarray.DataArray, freq: str", "(\"D\") or weekly (\"W\"), quarters are defined as 13 week", "expressed as a percentage of the mean of those values.", "'wettest' calculate wettest quarter ; 'driest' calculate driest quarter. src_timestep", "xarray.DataArray Average daily minimum temperature at daily, weekly, or monthly", "xarray.DataArray, src_timestep: str = None, freq: str = \"YS\" )", "ALL INDICES WRONG UNTIL TESTED ! # # -------------------------------------------------- #", "periods, otherwise are 3 months. Parameters ---------- tas : xarray.DataArray", "potentially small denominator values. \"\"\" # If units in mm/sec", "precipitation of wettest/driest quarter. The wettest (or driest) quarter of", "temperature_seasonality(tas: xarray.DataArray) -> xarray.DataArray: r\"\"\"ANUCLIM temperature seasonality (coefficient of variation).", "quarterly time series according to ANUCLIM specifications.\"\"\" if freq.upper().startswith(\"D\"): if", "is not None: # Accumulate on a week # Ensure", "tas] Mean temperature values of the {op} quearter of each", "seasonality: >>> import xclim.indices as xci >>> p = xr.open_dataset(path_to_pr_file).pr", "freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM Accumulated total", "import numpy as np import xarray from xclim.core.units import (", "xarray.DataArray, [%] Precipitation coefficient of variation Examples -------- The following", "= xci.precip_seasonality(p_weekly) Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf", "; op parameter but be one of \"wettest\" or \"driest\"'", "a week # Ensure units are back to a \"rate\"", "pr: Optional[xarray.DataArray] = None, tas: Optional[xarray.DataArray] = None, ) ->", "100 * _anuclim_coeff_var(pr) seas.attrs[\"units\"] = \"%\" return seas @declare_units(tas=\"[temperature]\") def", "each grid cell of file `pr.day.nc` the annual wettest quarter", "2)) if pr is not None: pr = ensure_chunk_size(pr, time=np.ceil(window", ") from xclim.core.utils import ensure_chunk_size from ._multivariate import ( daily_temperature_range,", "pr: xarray.DataArray, ) -> xarray.DataArray: r\"\"\"ANUCLIM Precipitation Seasonality (C of", "monthly frequency. Returns ------- xarray.DataArray, [%] Mean temperature coefficient of", "\"W\" if freq.upper().startswith(\"W\"): window = 13 elif freq.upper().startswith(\"M\"): window =", "xarray.set_options(keep_attrs=True): seas = 100 * _anuclim_coeff_var(pr) seas.attrs[\"units\"] = \"%\" return", ") -> xarray.DataArray: r\"\"\"ANUCLIM Precipitation Seasonality (C of V). The", "If input units are in mm s-1 (or equivalent) values", "each grid cell of file `tas.day.nc` the annual temperature warmest", "/ 2)) if pr is not None: pram = rate2amount(pr)", "freq: str ) -> xarray.DataArray: \"\"\"Pick values from output based", "= rate2amount(pr) return pram.resample(time=freq).sum(dim=\"time\", keep_attrs=True) # FIXME: src_timestep is not", "implementation here will calculate the result with input data with", "freq : str Temporal grouping. Returns ------- DataArray Output values", "import ensure_chunk_size from ._multivariate import ( daily_temperature_range, extreme_temperature_range, precip_accumulation, )", "monthly frequency. freq : str Resampling frequency. Returns ------- xarray.DataArray,", "\"\"\" pram = rate2amount(pr) if op == \"wettest\": return pram.resample(time=freq).max(dim=\"time\",", "seas.attrs[\"units\"] = \"%\" return seas @declare_units(pr=\"[precipitation]\") def precip_seasonality( pr: xarray.DataArray,", "avoid potentially small denominator if units2pint(pr) == units(\"mm / s\"):", "xarray.DataArray, [same as tas] Mean temperature values of the {op}", "return std / mu def _from_other_arg( criteria: xarray.DataArray, output: xarray.DataArray,", "d-1, mm week-1). Returns ------- xarray.DataArray, [%] Precipitation coefficient of", "\"precip_seasonality\", \"tg_mean_warmcold_quarter\", \"tg_mean_wetdry_quarter\", \"prcptot_wetdry_quarter\", \"prcptot_warmcold_quarter\", \"prcptot\", \"prcptot_wetdry_period\", \"isothermality\", ] _xr_argops", "= _to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op] with xarray.set_options(keep_attrs=True): out =", "on which operation returning index is applied. output : DataArray", "monthly frequency. op : str {'warmest', 'coldest'} Operation to perform:", ">>> pr_warm_qrt = prcptot_wetdry_quarter(pr=p.pr, op='wettest', src_timestep='D') Notes ----- According to", "mean temperature of this period is calculated. If the input", "temperature at daily, weekly, or monthly frequency. pr : xarray.DataArray", ": DataArray Series on which operation returning index is applied.", "temperature at daily, weekly, or monthly frequency. op : {'warmest',", "raise NotImplementedError( f'Unknown operation \"{op}\" ; not one of \"wettest\"", "\"prcptot_wetdry_quarter\", \"prcptot_warmcold_quarter\", \"prcptot\", \"prcptot_wetdry_period\", \"isothermality\", ] _xr_argops = { \"wettest\":", "dim=dim).where(~all_nans) return ds.resample(time=freq).map(get_other_op) def _to_quarter( freq: str, pr: Optional[xarray.DataArray] =", "each grid cell of file `tas.day.nc` the annual temperature seasonality:", "period is calculated. If the input data frequency is daily", "perform : 'wettest' calculate wettest period ; 'driest' calculate driest", "\"wettest\": return pram.resample(time=freq).max(dim=\"time\", keep_attrs=True) if op == \"driest\": return pram.resample(time=freq).min(dim=\"time\",", "xci.temperature_seasonality(t_weekly) Notes ----- For this calculation, the mean in degrees", "possibility of having to divide by zero, but it does", "str Resampling frequency. Returns ------- xarray.DataArray, [length] Total precipitation. Notes", "prior to calling the function. \"\"\" tas_qrt = _to_quarter(src_timestep, tas=tas)", "is not used here. @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_period( pr: xarray.DataArray, *,", "output: xarray.DataArray, op, freq: str ) -> xarray.DataArray: \"\"\"Pick values", "xarray.DataArray.argmin, \"driest\": xarray.DataArray.argmin, \"coldest\": xarray.DataArray.argmin, } _np_ops = { \"wettest\":", "= \"YS\" ) -> xarray.DataArray: r\"\"\"Isothermality. The mean diurnal range", "calculate for the warmest quarter ; 'coldest' calculate for the", "december, MS: month start # See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases # -------------------------------------------------- #", "[mm week-1], [mm month-1] or similar. op : {'wettest', 'driest'}", "prior to calling the function. If input units are in", "operation \"{op}\" ; not one of \"wettest\" or \"driest\"' )", "_np_ops = { \"wettest\": \"max\", \"warmest\": \"max\", \"dryest\": \"min\", \"driest\":", "t = xr.open_dataset(path_to_tas_file) >>> t_warm_qrt = xci.tg_mean_warmcold_quarter(tas=t.tas, op='warmest', src_timestep='daily') Notes", "weekly, or monthly frequency. op : {'warmest', 'coldest'} Operation to", "precipitation: >>> from xclim.indices import prcptot_wetdry_quarter >>> p = xr.open_dataset(path_to_pr_file)", ">>> t_warm_qrt = xci.tg_mean_warmcold_quarter(tas=t.tas, op='warmest', src_timestep='daily') Notes ----- According to", "mm/days to avoid potentially small denominator if units2pint(pr) == units(\"mm", "xclim.indices as xci >>> p = xr.open_dataset(path_to_pr_file).pr >>> pday_seasonality =", "_from_other_arg( criteria: xarray.DataArray, output: xarray.DataArray, op, freq: str ) ->", "str {'warmest', 'coldest'} Operation to perform: 'warmest' calculate warmest quarter;", "xci.temperature_seasonality(t) >>> t_weekly = xci.tg_mean(t, freq='7D') >>> tweek_seasonality = xci.temperature_seasonality(t_weekly)", "(\"D\") or weekly (\"W\") quarters are defined as 13 week", "time frequency \"{freq}\": must be one of \"D\", \"W\" or", "MS: month start # See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases # -------------------------------------------------- # #", "avoid potentially small denominator values. \"\"\" # If units in", "return ds.resample(time=freq).map(get_other_op) def _to_quarter( freq: str, pr: Optional[xarray.DataArray] = None,", "xarray.DataArray, [length] Total precipitation of the {op} period. Notes -----", "with xarray.set_options(keep_attrs=True): iso = dtr / etr * 100 iso.attrs[\"units\"]", "of each year. Notes ----- According to the ANUCLIM user-guide", "range divided by the annual temperature range. Parameters ---------- tasmin", "typing import Optional import numpy as np import xarray from", "'driest'} Operation to perform: 'wettest' calculate for the wettest quarter;", "Average daily minimum temperature at daily, weekly, or monthly frequency.", "Output values where criteria is met at the given frequency.", "keep_attrs=True) # FIXME: src_timestep is not used here. @declare_units(pr=\"[precipitation]\") def", "from .generic import select_resample_op from .run_length import lazy_indexing # Frequencies", "def temperature_seasonality(tas: xarray.DataArray) -> xarray.DataArray: r\"\"\"ANUCLIM temperature seasonality (coefficient of", ": str Resampling frequency. Returns ------- xarray.DataArray, [same as tas]", "seas @declare_units(pr=\"[precipitation]\") def precip_seasonality( pr: xarray.DataArray, ) -> xarray.DataArray: r\"\"\"ANUCLIM", "(or monthly) frequency. However, the xclim.indices implementation here will calculate", "or similar. op : {'wettest', 'driest'} Operation to perform :", "function. \"\"\" tas_qrt = _to_quarter(src_timestep, tas=tas) pr_qrt = _to_quarter(src_timestep, pr=pr)", "an index from criteria. Parameters ---------- criteria : DataArray Series", "._multivariate import ( daily_temperature_range, extreme_temperature_range, precip_accumulation, ) from ._simple import", "Returns ------- xarray.DataArray, [length] Total precipitation of the {op} period.", "YS: year start, QS-DEC: seasons starting in december, MS: month", "is determined, and the total precipitation of this period is", "The following would compute for each grid cell of file", "str, pr: Optional[xarray.DataArray] = None, tas: Optional[xarray.DataArray] = None, )", "wettest quarter; 'driest' calculate for the driest quarter. src_timestep :", "xarray.DataArray, *, op: str, src_timestep: str, freq: str = \"YS\"", "if freq.upper().startswith(\"D\"): if tas is not None: tas = tg_mean(tas,", "_to_quarter(src_timestep, tas=tas) oper = _np_ops[op] out = select_resample_op(out, oper, freq)", "= \"time\" def get_other_op(dataset): all_nans = dataset.criteria.isnull().all(dim=dim) index = op(dataset.criteria.where(~all_nans,", "{'warmest', 'coldest'} Operation to perform: 'warmest' calculate for the warmest", "not None: tas = tg_mean(tas, freq=\"7D\") if pr is not", "Total precipitation. Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf", "\"driest\": \"min\", \"coldest\": \"min\", } @declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\") def isothermality( tasmin:", "or similar. src_timestep : {'D', 'W', 'M'} Input data time", "pr_warm_qrt = prcptot_wetdry_quarter(pr=p.pr, op='wettest', src_timestep='D') Notes ----- According to the", "------- xarray.DataArray, [%] Mean temperature coefficient of variation Examples --------", "frequency. Returns ------- xarray.DataArray, [length] Total precipitation of the {op}", "be at a weekly (or monthly) frequency. However, the xclim.indices", "year expressed as a percentage of the mean of those", "quarter mean temperature: >>> import xclim.indices as xci >>> t", "\"wettest\": \"max\", \"warmest\": \"max\", \"dryest\": \"min\", \"driest\": \"min\", \"coldest\": \"min\",", "The wettest (or driest) quarter of the year is determined,", "pr=pr) xr_op = _xr_argops[op] out = _from_other_arg(criteria=tas_qrt, output=pr_qrt, op=xr_op, freq=freq)", "pr_qrt.attrs return out @declare_units(pr=\"[precipitation]\") def prcptot( pr: xarray.DataArray, src_timestep: str", "operation returning an index from criteria. Parameters ---------- criteria :", "np.nanargmax. freq : str Temporal grouping. Returns ------- DataArray Output", "the xclim.indices implementation here will calculate the output with input", "str, freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM precipitation", "does mean that the values are usually quite small. According", "Precipitation coefficient of variation Examples -------- The following would compute", "\"mm d-1\") with xarray.set_options(keep_attrs=True): seas = 100 * _anuclim_coeff_var(pr) seas.attrs[\"units\"]", "data frequency tas_qrt = _to_quarter(src_timestep, tas=tas) # returns mm values", "monthly frequency. op : {'wettest', 'driest'} Operation to perform: 'wettest'", "to avoid potentially small denominator values. \"\"\" # If units", "op parameter but be one of \"wettest\" or \"driest\"' )", "xclim.indices import prcptot_wetdry_quarter >>> p = xr.open_dataset(path_to_pr_file) >>> pr_warm_qrt =", "\"min\", \"driest\": \"min\", \"coldest\": \"min\", } @declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\") def isothermality(", "is not None: pram = rate2amount(pr) out = pram.rolling(time=window, center=False).sum()", "\"wettest\" or \"driest\"' ) def _anuclim_coeff_var(arr: xarray.DataArray) -> xarray.DataArray: \"\"\"Calculate", "from ._simple import tg_mean from .generic import select_resample_op from .run_length", "Series on which operation returning index is applied. output :", "= rate2amount(pr) if op == \"wettest\": return pram.resample(time=freq).max(dim=\"time\", keep_attrs=True) if", "annual temperature seasonality: >>> import xclim.indices as xci >>> t", "should be calculated prior to calling the function. \"\"\" #", "at daily, weekly, or monthly frequency. op : str {'warmest',", "prcptot_wetdry_quarter(pr=p.pr, op='wettest', src_timestep='D') Notes ----- According to the ANUCLIM user-guide", "V). The annual precipitation Coefficient of Variation (C of V)", "from ._multivariate import ( daily_temperature_range, extreme_temperature_range, precip_accumulation, ) from ._simple", "= xci.temperature_seasonality(t) >>> t_weekly = xci.tg_mean(t, freq='7D') >>> tweek_seasonality =", "determined, and the mean temperature of this period is calculated.", "Total precipitation rate at daily, weekly, or monthly frequency. tas", "converted to mm/day to avoid potentially small denominator values. \"\"\"", "with xarray.set_options(keep_attrs=True): seas = 100 * _anuclim_coeff_var(tas) seas.attrs[\"units\"] = \"%\"", "return pram.resample(time=freq).sum(dim=\"time\", keep_attrs=True) # FIXME: src_timestep is not used here.", ": {'warmest', 'coldest'} Operation to perform: 'warmest' calculate for the", "frequency. Returns ------- xarray.DataArray, [%] Mean temperature coefficient of variation", "ensure_chunk_size from ._multivariate import ( daily_temperature_range, extreme_temperature_range, precip_accumulation, ) from", "annual precipitation seasonality: >>> import xclim.indices as xci >>> p", "-> xarray.DataArray: r\"\"\"ANUCLIM Mean temperature of warmest/coldest quarter. The warmest", "or \"M\".' ) if tas is not None: tas =", "Mean temperature values of the {op} quarter of each year.", "r\"\"\"ANUCLIM Accumulated total precipitation. Parameters ---------- pr : xarray.DataArray Total", "( convert_units_to, declare_units, pint_multiply, rate2amount, units, units2pint, ) from xclim.core.utils", "xarray.DataArray, output: xarray.DataArray, op, freq: str ) -> xarray.DataArray: \"\"\"Pick", "with xarray.set_options(keep_attrs=True): seas = 100 * _anuclim_coeff_var(pr) seas.attrs[\"units\"] = \"%\"", "Variation (C of V) expressed in percent. Calculated as the", "_to_quarter(src_timestep, tas=tas) pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op] with", "calculation, the mean in degrees Kelvin is used. This avoids", "If the input data frequency is daily (\"D\") or weekly", "lazy_indexing(dataset.output, index=index, dim=dim).where(~all_nans) return ds.resample(time=freq).map(get_other_op) def _to_quarter( freq: str, pr:", "raise NotImplementedError( f'Unknown input time frequency \"{freq}\": must be one", "Resampling frequency. Returns ------- xarray.DataArray, [%] Isothermality Notes ----- According", ") if tas is not None: tas = ensure_chunk_size(tas, time=np.ceil(window", "function. \"\"\" pram = rate2amount(pr) if op == \"wettest\": return", "mm values pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op = _xr_argops[op] out", "= _np_ops[op] except KeyError: raise NotImplementedError( f'Unknown operation \"{op}\" ;", "convert to mm/days to avoid potentially small denominator if units2pint(pr)", "t = xr.open_dataset(path_to_tas_file).tas >>> tday_seasonality = xci.temperature_seasonality(t) >>> t_weekly =", "quarter of each year. Examples -------- The following would compute", "= None, freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM", "oper = _np_ops[op] out = select_resample_op(out, oper, freq) out.attrs[\"units\"] =", "rate2amount, units, units2pint, ) from xclim.core.utils import ensure_chunk_size from ._multivariate", "= xci.precip_seasonality(p) >>> p_weekly = xci.precip_accumulation(p, freq='7D') # Input units", "tas = ensure_chunk_size(tas, time=np.ceil(window / 2)) if pr is not", "[%] Isothermality Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf", "freq : str Resampling frequency. Returns ------- xarray.DataArray, [%] Isothermality", "to avoid potentially small denominator if units2pint(pr) == units(\"mm /", "tas = convert_units_to(tas, \"K\") with xarray.set_options(keep_attrs=True): seas = 100 *", "precip_seasonality( pr: xarray.DataArray, ) -> xarray.DataArray: r\"\"\"ANUCLIM Precipitation Seasonality (C", ": {'D', 'W', 'M'} Input data time frequency - One", "None, freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM Total", "the function. \"\"\" tas_qrt = _to_quarter(src_timestep, tas=tas) pr_qrt = _to_quarter(src_timestep,", "out.attrs = tas.attrs return out @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_quarter( pr: xarray.DataArray,", "be one of \"D\", \"W\" or \"M\".' ) if tas", "# Ensure units are back to a \"rate\" for rate2amount", "such weekly or monthly input values, if desired, should be", "xr_op = _xr_argops[op] with xarray.set_options(keep_attrs=True): out = _from_other_arg(criteria=pr_qrt, output=tas_qrt, op=xr_op,", "prcptot( pr: xarray.DataArray, src_timestep: str = None, freq: str =", "_from_other_arg(criteria=pr_qrt, output=tas_qrt, op=xr_op, freq=freq) out.attrs = tas.attrs return out @declare_units(pr=\"[precipitation]\")", "mm week-1). Returns ------- xarray.DataArray, [%] Precipitation coefficient of variation", "according to ANUCLIM specifications.\"\"\" if freq.upper().startswith(\"D\"): if tas is not", "Mean temperature of warmest/coldest quarter. The warmest (or coldest) quarter", "each year. Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf", "tas=tas) # returns mm values pr_qrt = _to_quarter(src_timestep, pr=pr) xr_op", "rate2amount(pr) if op == \"wettest\": return pram.resample(time=freq).max(dim=\"time\", keep_attrs=True) if op", "= _xr_argops[op] out = _from_other_arg(criteria=tas_qrt, output=pr_qrt, op=xr_op, freq=freq) out.attrs =", "_to_quarter( freq: str, pr: Optional[xarray.DataArray] = None, tas: Optional[xarray.DataArray] =", "noqa: D100 from typing import Optional import numpy as np", "at daily, weekly, or monthly frequency. op : {'wettest', 'driest'}", "not None: # Accumulate on a week # Ensure units", "\"mm/week\" freq = \"W\" if freq.upper().startswith(\"W\"): window = 13 elif", "out.attrs[\"units\"] = tas.units return out @declare_units(tas=\"[temperature]\", pr=\"[precipitation]\") def tg_mean_wetdry_quarter( tas:", "the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (ch. 6), input values should be", "monthly) frequency. However, the xclim.indices implementation here will calculate the", "op(dataset.criteria.where(~all_nans, 0), dim=dim) return lazy_indexing(dataset.output, index=index, dim=dim).where(~all_nans) return ds.resample(time=freq).map(get_other_op) def", "-------- The following would compute for each grid cell of", "r\"\"\"ANUCLIM Precipitation Seasonality (C of V). The annual precipitation Coefficient", "= dtr / etr * 100 iso.attrs[\"units\"] = \"%\" return", "xarray.DataArray: \"\"\"Calculate the annual coefficient of variation for ANUCLIM indices.\"\"\"", "\"\"\" dtr = daily_temperature_range(tasmin=tasmin, tasmax=tasmax, freq=freq) etr = extreme_temperature_range(tasmin=tasmin, tasmax=tasmax,", "pr : xarray.DataArray Total precipitation rate at daily, weekly, or", "the possibility of having to divide by zero, but it", "op='wettest', src_timestep='D') Notes ----- According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf", "prior to calling the function. \"\"\" # returns mm values", "annual coefficient of variation for ANUCLIM indices.\"\"\" std = arr.resample(time=\"YS\").std(dim=\"time\")", ") -> xarray.DataArray: r\"\"\"ANUCLIM precipitation of the wettest/driest day, week,", "tas: xarray.DataArray, pr: xarray.DataArray, op: str = None, src_timestep: str", "isothermality( tasmin: xarray.DataArray, tasmax: xarray.DataArray, freq: str = \"YS\" )", "_anuclim_coeff_var(tas) seas.attrs[\"units\"] = \"%\" return seas @declare_units(pr=\"[precipitation]\") def precip_seasonality( pr:", "start, QS-DEC: seasons starting in december, MS: month start #", "otherwise are 3 months. Parameters ---------- pr : xarray.DataArray Total", "------- xarray.DataArray : [mm] Total precipitation values of the {op}", "need to be a rate >>> p_weekly.attrs['units'] = \"mm/week\" >>>", "_xr_argops[op] out = _from_other_arg(criteria=tas_qrt, output=pr_qrt, op=xr_op, freq=freq) out.attrs = pr_qrt.attrs", "input units are in mm s-1 (or equivalent) values are", "-> xarray.DataArray: r\"\"\"ANUCLIM Accumulated total precipitation. Parameters ---------- pr :", "total precipitation of this period is calculated. If the input", "r\"\"\"ANUCLIM temperature seasonality (coefficient of variation). The annual temperature coefficient", "* 100 iso.attrs[\"units\"] = \"%\" return iso @declare_units(tas=\"[temperature]\") def temperature_seasonality(tas:", "= xr.open_dataset(path_to_pr_file).pr >>> pday_seasonality = xci.precip_seasonality(p) >>> p_weekly = xci.precip_accumulation(p,", "perform : 'wettest' calculate wettest quarter ; 'driest' calculate driest", "to calling the function. \"\"\" tas_qrt = _to_quarter(src_timestep, tas=tas) pr_qrt", "the year is determined, and the mean temperature of this", "as well. As such weekly or monthly input values, if", "a percentage of the mean of those values. Parameters ----------", "xarray.Dataset(data_vars={\"criteria\": criteria, \"output\": output}) dim = \"time\" def get_other_op(dataset): all_nans", "here. @declare_units(pr=\"[precipitation]\") def prcptot_wetdry_period( pr: xarray.DataArray, *, op: str, src_timestep:", "compute for each grid cell of file `pr.day.nc` the annual", "time step. Parameters ---------- pr : xarray.DataArray Total precipitation flux", "be calculated prior to calling the function. \"\"\" dtr =", "freq: str = \"YS\" ) -> xarray.DataArray: r\"\"\"ANUCLIM Total precipitation", "np.argmax, np.nanargmin, np.nanargmax. freq : str Temporal grouping. Returns -------", "-> xarray.DataArray: \"\"\"Calculate the annual coefficient of variation for ANUCLIM", "returning index is applied. output : DataArray Series to be", "out = select_resample_op(pr_qrt, oper, freq) out.attrs[\"units\"] = pr_qrt.units return out", "d-1], [mm week-1], [mm month-1] or similar. op : {'wettest',", "calculate wettest period ; 'driest' calculate driest period. src_timestep :", "where criteria is met at the given frequency. \"\"\" ds", "-> xarray.DataArray: r\"\"\"ANUCLIM Precipitation Seasonality (C of V). The annual", "warmest quarter; 'coldest' calculate coldest quarter. src_timestep : {'D', 'W',", "r\"\"\"ANUCLIM Mean temperature of warmest/coldest quarter. The warmest (or coldest)", "of the {op} quarter of each year. Examples -------- The", "daily_temperature_range, extreme_temperature_range, precip_accumulation, ) from ._simple import tg_mean from .generic", "pr: xarray.DataArray, src_timestep: str = None, freq: str = \"YS\"", "The mean diurnal range divided by the annual temperature range.", "dim = \"time\" def get_other_op(dataset): all_nans = dataset.criteria.isnull().all(dim=dim) index =", "data time frequency - One of daily, weekly or monthly.", "to a \"rate\" for rate2amount below pr = convert_units_to(precip_accumulation(pr, freq=\"7D\")," ]